代码之家  ›  专栏  ›  技术社区  ›  Kimvais

在Pyqt中选中/取消选中某个qTableWidgetItem时,如何执行某些槽/函数?

  •  1
  • Kimvais  · 技术社区  · 15 年前

    我有一个动态创建的表,每行有n行和m qtablewidgetitems(仅用作复选框)-每当复选框被选中或取消选中时,我需要运行知道行和列的代码。

    我的复选框子类如下:

    class CheckBox(QTableWidgetItem):
        def __init__(self):
            QTableWidgetItem.__init__(self,1000)
            self.setTextAlignment(Qt.AlignVCenter | Qt.AlignJustify)
            self.setFlags(Qt.ItemFlags(
                Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled ))
    def stateChanged(self):
        do_something(self.row(),self.column())
        ...
    

    显然,这不会重新定义在 SIGNAL('stateChanged(int)') -事情发生了,因为,嗯,什么都没有发生。

    但是,如果我这样做:

    item = CheckBox()
    self.connect(item, SIGNAL('stateChanged(int)'), item.stateChanged)
    

    在创建表的循环中,我得到一个错误:

    TypeError: arguments did not match any overloaded call:
      QObject.connect(QObject, SIGNAL(), QObject, SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox'
      QObject.connect(QObject, SIGNAL(), callable, Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox'
      QObject.connect(QObject, SIGNAL(), SLOT(), Qt.ConnectionType=Qt.AutoConnection): argument 1 has unexpected type 'CheckBox
    

    编辑 : 我也尝试重新定义 setCheckState() 但显然是这样 不是 在选中或未选中项时调用。

    编辑2 : 此外,将连接更改为

    self.connect(self.table, SIGNAL('itemClicked(item)'),
                   self.table.stateChanged)
    

    哪里 table = QTableWidget() 也无济于事。

    我该怎么做才对?

    1 回复  |  直到 15 年前
        1
  •  2
  •   Greg S    15 年前

    最简单的解决方案可能是连接到 cellChanged(int, int) 信号 QTableWidget ;请看以下示例:

    import sys
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *
    
    #signal handler
    def myCellChanged(row, col):
        print row, col
    
    #just a helper function to setup the table
    def createCheckItem(table, row, col):
        check = QTableWidgetItem("Test")
        check.setCheckState(Qt.Checked)
        table.setItem(row,col,check)
    
    app = QApplication(sys.argv)
    
    #create the 5x5 table...
    table = QTableWidget(5,5)
    map(lambda (row,col): createCheckItem(table, row, col),
       [(row, col) for row in range(0, 5) for col in range(0, 5)])
    table.show()
    
    #...and connect our signal handler to the cellChanged(int, int) signal
    QObject.connect(table, SIGNAL("cellChanged(int, int)"), myCellChanged)
    app.exec_()
    

    它创建一个5x5的复选框表;每当选中/取消选中其中一个复选框时, myCellChanged 调用并打印已更改复选框的行和列;然后您当然可以使用 QTableWidget.item(someRow, someColumn).checkState() 查看是选中还是未选中。

    推荐文章