Como faço para que algum slot/função seja executado quando um determinado QTableWidgetItem é marcado/desmarcado no PyQt
-
26-09-2019 - |
Pergunta
Eu tenho uma tabela criada dinamicamente, que possui N linhas e M QTableWidgetItems (que são usados apenas como caixas de seleção) por linha - preciso executar um código que conheça a linha e a coluna sempre que uma caixa de seleção estiver marcada ou desmarcada.
Minha subclasse CheckBox se parece com:
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())
...
Obviamente isso não redefine a função que é chamada quando SIGNAL('stateChanged(int)')
-coisa acontece, porque, bem, nada acontece.
Mas, se eu fizer isso:
item = CheckBox()
self.connect(item, SIGNAL('stateChanged(int)'), item.stateChanged)
No loop de criação da tabela, recebo um erro:
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
EDITAR:Eu também tentei redefinir setCheckState()
mas aparentemente isso faz NÃO é chamado quando o item é marcado ou desmarcado.
EDITAR 2:Além disso, alterando a conexão para
self.connect(self.table, SIGNAL('itemClicked(item)'),
self.table.stateChanged)
onde table = QTableWidget()
também não ajuda.
Como faço isso da maneira certa?
Solução
A solução mais simples é provavelmente conectar-se ao cellChanged(int, int)
sinal do QTableWidget
;dê uma olhada no exemplo a seguir:
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_()
Ele cria uma tabela 5x5 de caixas de seleção;sempre que um deles estiver marcado/desmarcado, myCellChanged
é chamado e imprime a linha e a coluna da caixa de seleção alterada;você pode então, é claro, usar QTableWidget.item(someRow, someColumn).checkState()
para ver se foi marcado ou desmarcado.