gpt4 book ai didi

python - 当 PyQt 中选中/取消选中某个 QTableWidgetItem 时,如何获取要执行的某些槽/函数

转载 作者:行者123 更新时间:2023-12-01 06:14:57 25 4
gpt4 key购买 nike

我有一个动态创建的表,每行有 N 行和 M 个 QTableWidgetItems(仅用作复选框) - 无论何时选中或取消选中复选框,我都需要运行知道行和列的代码。

我的 CheckBox 子类如下所示:

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)') -thingy 发生时调用的函数,因为什么也没有发生。

但是,如果我这样做:

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()也没有帮助。

我该如何正确地做到这一点?

最佳答案

最简单的解决方案可能是连接到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()来查看它是否被选中或未选中。

关于python - 当 PyQt 中选中/取消选中某个 QTableWidgetItem 时,如何获取要执行的某些槽/函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3829349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com