Hiperfly
Hiperfly

Reputation: 178

PyQt5: State change in Checkboxes from a QTableWidget

I'm wondering if there is a way to run a function whenever you check/uncheck a checkbox from a cell in a QTableWidget. Right now I create these checkboxes in the following way:

for row in range(len(my_list)):
    self.item = QtWidgets.QTableWidgetItem()
    self.item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
    self.item.setCheckState(QtCore.Qt.Checked)

Is there some sort of item.stateChanged.connect() method for this? I even tried to, for every click in the table, check for the state of the item in the row clicked but it returns 2 every time, as if it's always checked:

if self.mytable.item(row,1).checkState() == QtCore.Qt.Checked:

Thanks

Upvotes: 3

Views: 6145

Answers (1)

eyllanesc
eyllanesc

Reputation: 243955

There is not a signal to get it directly, so I will use the cellChanged signal of QTableWidget, I will also save the previous state in a role to be able to compare it with the current state.

from PyQt5 import QtCore, QtWidgets

LastStateRole = QtCore.Qt.UserRole

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.tablewidget = QtWidgets.QTableWidget(4, 4)
        self.setCentralWidget(self.tablewidget)

        my_list = ["A", "B", "C", "D"]
        for row in range(len(my_list)):
            item = QtWidgets.QTableWidgetItem()
            item.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
            item.setCheckState(QtCore.Qt.Checked)
            item.setData(LastStateRole, item.checkState())

            self.tablewidget.setItem(row, 0, item)

        self.tablewidget.cellChanged.connect(self.onCellChanged)

    def onCellChanged(self, row, column):
        item = self.tablewidget.item(row, column)
        lastState = item.data(LastStateRole)
        currentState = item.checkState()
        if currentState != lastState:
            print("changed: ")
            if currentState == QtCore.Qt.Checked:
                print("checked")
            else:
                print("unchecked")
            item.setData(LastStateRole, currentState)


if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

Upvotes: 4

Related Questions