Home > Software design >  How to read QCheckbox state from QTableWidget
How to read QCheckbox state from QTableWidget

Time:09-21

I am adding a QCheckBox item to one of the cells in my QTableWidget using the following:

cell_widget = QWidget()
chk_bx = QCheckBox()
chk_bx.setCheckState(QtCore.Qt.Unchecked)
lay_out = QHBoxLayout(cell_widget)
lay_out.addWidget(chk_bx)
lay_out.setAlignment(QtCore.Qt.AlignCenter)
lay_out.setContentsMargins(0,0,0,0)
cell_widget.setLayout(lay_out)
self.definedEventsTable.setCellWidget(row, select_column, cell_widget)

The variable definedEventsTable is a QTableWidget.

The above code works fine and the checkbox is correctly displayed on the GUI and is checkable. Nothing wrong there.

However, when I try to read whether or not it is checked, I cannot seem to be able to do so. Here is what I have tried:

self.definedEventsTable.item(row, select_column)
self.definedEventsTable.itemAt(row, select_column)
self.definedEventsTable.cellWidget(row, select_column)

Each of these return None and therefore cannot run isChecked(). What am I doing wrong?

EDIT

Apologies, it appears that the following is working. Clearly I fumbled around or something.

self.definedEventsTable.cellWidget(row, select_column)

However, it returns a QWidget. How can I get the QCheckbox?

CodePudding user response:

The cellWidget method returns the widget set in the cell, which in your case is "cellWidget" so there are several options to obtain the associated QCheckBox:

- Use findChild

cell_widget = self.definedEventsTable.cellWidget(row, select_column)
checkbox = cell_widget.findChild(QCheckBox)
if checkbox:
    print(checkbox)

- Custom Attribute

cell_widget = QWidget()
chk_bx = QCheckBox()
chk_bx.setCheckState(QtCore.Qt.Unchecked)
lay_out = QHBoxLayout(cell_widget)
lay_out.addWidget(chk_bx)
lay_out.setAlignment(QtCore.Qt.AlignCenter)
lay_out.setContentsMargins(0,0,0,0)
cell_widget.checkbox = chk_bx
self.definedEventsTable.setCellWidget(row, select_column, cell_widget)

Then:

cell_widget = self.definedEventsTable.cellWidget(row, select_column)
if hasattr(cell_widget, "checkbox"):
    checkbox = cell_widget.checkbox
    print(checkbox)

- Custom QWidget

class Widget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.chk_bx = QCheckBox()
        self.chk_bx.setCheckState(QtCore.Qt.Unchecked)
        lay_out = QHBoxLayout(self)
        lay_out.addWidget(self.chk_bx)
        lay_out.setAlignment(QtCore.Qt.AlignCenter)
        lay_out.setContentsMargins(0,0,0,0)
cell_widget = Widget()
self.definedEventsTable.setCellWidget(row, select_column, cell_widget)

Then:

cell_widget = self.definedEventsTable.cellWidget(row, select_column)
checkbox = cell_widget.chk_bx
print(checkbox)
  • Related