【问题标题】:How to get the QModelIndex associated with the QCheckbox placed in the QTableWIdget如何获取与放置在 QTableWIdget 中的 QCheckbox 关联的 QModelIndex
【发布时间】:2020-12-30 11:21:55
【问题描述】:

我有以下代码在 QTableWidget 的项目列表的第一列中放置一个 CheckBox。

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)

我从这个问题的答案开始: How should I connect CheckBox clicked signals in Table Widgets in PyQt5?

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

点击处理程序如下所示:

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

我面临的问题是行/列不正确。

如何恢复被点击的复选框的行/列?

【问题讨论】:

    标签: python pyqt pyqt5


    【解决方案1】:

    似乎我之前的答案并不明确,但我将采用这个答案以一种通用的方式来接受它,这将适用于从 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)
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-11-14
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-02
        • 1970-01-01
        • 2020-10-26
        相关资源
        最近更新 更多