如何从 QTableWidget 读取 QCheckbox 状态

How to read QCheckbox state from QTableWidget

我正在使用以下方法将 QCheckBox 项添加到我的 QTableWidget 中的一个单元格中:

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)

变量definedEventsTable是一个QTableWidget

以上代码工作正常,复选框在 GUI 上正确显示并且可以选中。没什么问题。

但是,当我尝试读取它是否被选中时,我似乎无法这样做。这是我尝试过的:

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

每个 return None,因此不能 运行 isChecked()。我做错了什么?

编辑

抱歉,以下内容似乎有效。显然是我摸索着什么的。

self.definedEventsTable.cellWidget(row, select_column)

然而,它 return 是 QWidget。我怎样才能得到 QCheckbox?

cellWidget 方法 returns 在单元格中设置的小部件,在您的情况下是“cellWidget”,因此有几个选项可以获取关联的 QCheckBox:

- 使用 findChild

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

- 自定义属性

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)

然后:

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

- 自定义 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)

然后:

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