Python 将右按钮与右表连接
我在创建表中的多个选项卡和删除按钮时遇到问题。此按钮应删除当前表中的行。我的问题是,如果我创建多个新选项卡,它只会删除上次创建的表中的行。由于我不知道需要多少选项卡,所以我无法命名这些表Python 将右按钮与右表连接,python,qt,pyqt,pyqt4,slot,Python,Qt,Pyqt,Pyqt4,Slot,我在创建表中的多个选项卡和删除按钮时遇到问题。此按钮应删除当前表中的行。我的问题是,如果我创建多个新选项卡,它只会删除上次创建的表中的行。由于我不知道需要多少选项卡,所以我无法命名这些表 import sys from PyQt4 import QtGui, QtCore class Fenster(QtGui.QMainWindow): def __init__(self, parent=None): QtGui.QMainWindow.__init__(self
import sys
from PyQt4 import QtGui, QtCore
class Fenster(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.resize(300, 300)
addButton = QtGui.QPushButton(u"Add Tab")
self.connect(addButton, QtCore.SIGNAL("clicked()"), self.addTab)
layout = QtGui.QVBoxLayout()
layout.addWidget(addButton)
self.tab_widget = QtGui.QTabWidget()
self.tab_widget.updatesEnabled()
widget = QtGui.QWidget()
self.tab_widget.addTab(widget, "Tab 1")
widget.setLayout(layout)
self.setCentralWidget(self.tab_widget)
self.show()
def addTab(self):
contents = QtGui.QWidget()
delButton = QtGui.QPushButton(u"Del Row")
self.connect(delButton, QtCore.SIGNAL("clicked()"), self.delRow)
self.table = QtGui.QTableWidget(5, 2)
layout = QtGui.QVBoxLayout()
layout.addWidget(self.table)
layout.addWidget(delButton)
self.tab_widget.addTab(contents, "New Tab")
contents.setLayout(layout)
def delRow(self):
self.table.setRowCount(0)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = Fenster()
window.show()
sys.exit(app.exec_())
问题是
self.table
总是指向您创建的最后一个表小部件。delRow
方法需要知道要从哪个表中删除,因此需要对该表的引用。我建议使用以下代码。在这里,插槽接受一个指向要从中删除的表的参数
def addTab(self):
contents = QtGui.QWidget()
table = QtGui.QTableWidget(5, 2)
delButton = QtGui.QPushButton(u"Del Row")
delButton.clicked.connect(lambda: self.delRow(table))
layout = QtGui.QVBoxLayout()
layout.addWidget(table)
layout.addWidget(delButton)
self.tab_widget.addTab(contents, "New Tab")
contents.setLayout(layout)
def delRow(self, table):
table.setRowCount(0)
关于此代码,有两点:
- 我使用了新样式的signal/slot方法将单击的信号连接到slot(它更像python)
- 因为信号希望连接到一个不带参数的插槽,所以我使用
包装了lambda
方法。如果您以前没有遇到过delRow(table)
,那么它基本上就是编写单行函数的简写。您可以在Python文档中了解到这一点lambda