尝试了几个小时以找到我所缺少的东西后,这里变得困惑,为什么这段代码在点击“添加行”按钮后没有添加行! 如果我在不单击按钮的情况下添加行,则可以正常工作(使用 init 函数),但是使用按钮时,效果却不佳。
import sys
from PyQt5.QtWidgets import *
class TabWidget(QDialog):
def __init__(self):
super().__init__()
self.table=AccountTable()
self.setWindowTitle('Tab Widget Application')
tabwidget = AccountTable()
connectButton = QPushButton('add a row')
connectButton.clicked.connect(self.onConnectButtonClicked)
vbox=QVBoxLayout()
vbox.addWidget(tabwidget)
vbox.addWidget(connectButton)
self.setLayout(vbox)
def onConnectButtonClicked(self):
self.table.add_trade(2)
class AccountTable(QTableWidget):
headerls = [
'Capital $ Value', 'Capital-Trading $ Value', 'First-Trading $ Value', 'Second-Trading $ Value',
'Time Elapsed', 'PNL', 'Capital $ Return', 'withdrawable $ ', 'Closing Date' ]
def __init__(self, parent=None):
QTableWidget.__init__(self, parent)
self.setColumnCount(len(self.headerls))
self.setHorizontalHeaderLabels(self.headerls)
self.setAlternatingRowColors(True)
self.resizeColumnsToContents()
def add_trade(self,h):
for i in range(h):
row = self.rowCount()
self.insertRow(row)
if __name__ == '__main__':
app=QApplication(sys.argv)
tabwidget = TabWidget()
tabwidget.show()
app.exec()
答案 0 :(得分:1)
我不确定这是您要找的东西。我更改了几行,主要是使tabwidget成为类属性。这是完整的代码,我在行尾用# c
指示了更改。
import sys
from PyQt5.QtWidgets import *
class TabWidget(QDialog):
def __init__(self):
super().__init__()
self.table=AccountTable()
self.setWindowTitle('Tab Widget Application')
self.tabwidget = AccountTable() # c
connectButton = QPushButton('add a row')
connectButton.clicked.connect(self.onConnectButtonClicked)
vbox=QVBoxLayout()
vbox.addWidget(self.tabwidget) # c
vbox.addWidget(connectButton)
self.setLayout(vbox)
def onConnectButtonClicked(self):
self.currentRowCount = self.tabwidget.rowCount() # c
self.tabwidget.insertRow(self.currentRowCount) # c
class AccountTable(QTableWidget):
headerls = [
'Capital $ Value', 'Capital-Trading $ Value', 'First-Trading $ Value', 'Second-Trading $ Value',
'Time Elapsed', 'PNL', 'Capital $ Return', 'withdrawable $ ', 'Closing Date' ]
def __init__(self, parent=None):
QTableWidget.__init__(self, parent)
self.setColumnCount(len(self.headerls))
self.setHorizontalHeaderLabels(self.headerls)
self.setAlternatingRowColors(True)
self.resizeColumnsToContents()
if __name__ == '__main__':
app = QApplication(sys.argv)
tabwidget = TabWidget()
tabwidget.show()
app.exec()
答案 1 :(得分:0)
Python按钮单击命令具有不同的方面,当您通常使用方法名称时,它将获得该名称,但无法处理该代码中的任何内容或返回任何内容
connectButton.clicked.connect(self.onConnectButtonClicked)
如果您使用lambda,它将创建事件相关的函数,并且您的方法可以处理并返回任何内容,并且您还可以传递数据,届时回调将为
connectButton.clicked.connect(lambda: self.onConnectButtonClicked())
有关更多信息,您可以访问this link