如何在PyQt中监测特定QTableWidgetItem被选中/取消选中时执行某个槽/函数?

1 投票
1 回答
3824 浏览
提问于 2025-04-16 04:48

我有一个动态创建的表格,这个表格有 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 个回答

2

最简单的解决办法就是连接到 QTableWidgetcellChanged(int, int) 信号;看看下面这个例子:

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() 来查看它是被选中了还是取消选中了。

撰写回答