如何获取与放置在 QTableWIdget 中的 QCheckbox 关联的 QModelIndex

How to get the QModelIndex associated with the QCheckbox placed in the QTableWIdget

我使用以下代码将 CheckBox 放置在 QTableWidget 项目列表的第一列中。

checkboxWidget = QWidget()
checkBox = QCheckBox(checkboxWidget)
checkBox.clicked.connect(self._check_changed)
#
#   If the variable is in the monitored list
#   check the checkbox
#
isMonitored = False
if (self._monitored_variables != None):
    if (self._monitored_variables[name]):
        isMonitored = True
if (isMonitored):
    checkBox.setCheckState(Qt.CheckState.Checked)
else:
    checkBox.setCheckState(Qt.CheckState.Unchecked)

layoutCheckbox = QHBoxLayout(checkboxWidget)
layoutCheckbox.addWidget(checkBox)
layoutCheckbox.setAlignment(Qt.AlignCenter)
layoutCheckbox.setContentsMargins(0, 0, 0, 0)
self._variables_view.setCellWidget(row,0, checkboxWidget)

我从这个问题的答案开始:

不同之处在于我希望 CheckBox 位于 table 单元格的中央,因此需要额外的控件。

点击处理程序如下所示:

 def _check_changed(self):
    cb = self.sender()
    print(cb.parent())
    ix = self._variables_view.indexAt(cb.pos())
    print(ix.row(), ix.column(), cb.isChecked())

我面临的问题是 row/column 不正确。

如何恢复被点击的 CheckBox 的 row/column?

看来我的问题的答案很简单。在“indexAt”方法中,“cb.pos()”需要更改为“cb.parent().pos()”。

我之前的回答似乎并不明确,但我将以一种通用的方式接受这个答案,这种方式适用于所有从 QAbstractItemView 继承的 类 和通过 setCellWidget 或 setIndexWidget 方法放置的任何类型的小部件。

一般情况:

解决的关键是获取发出信号的widget相对于QAbstractItemView视口的位置,然后使用indexAt获取QModelIndex。这可以通过以下步骤获得:

  1. 将小部件的任何相对内部位置映射到全局坐标。

  2. 将全局坐标映射到相对于视口的局部坐标。

  3. 使用带有本地坐标的 indexAt()。

    gl = widget.mapToGlobal(QtCore.QPoint())
    lp = view.viewport().mapFromGlobal(gp)
    ix = view.indexAt(lp)
    

具体案例:

在这种情况下,只需执行以下操作:

def _check_changed(self):
    widget = self.sender()
    gl = widget.mapToGlobal(QtCore.QPoint())
    lp = self._variables_view.viewport().mapFromGlobal(gp)
    ix = self._variables_view.indexAt(lp)