python - 如何防止用户点击进行行选择,同时保持编程行选择?

标签 python pyqt pyqt5 qtableview

在我的应用程序中,我有一个 QTableView,其中包含以编程方式选择的行,例如对数据执行查询后。

如何防止用户在单击时更改所选行,同时保持以编程方式选择行的能力?

这是我的代码:

self.table = QTableView()
pandas_model: QAbstractTableModel = PandasTableModel(self.data_frame, self)
self.table.setModel(pandas_model)
self.table.setSortingEnabled(False)
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # full width table
self.table.setSelectionMode(QAbstractItemView.MultiSelection)
self.table.setSelectionBehavior(QAbstractItemView.SelectRows)

我是否应该重写其 ItemSelectionModel 以防止用户单击时的默认行为,同时保持程序化选择模式?我怎样才能实现这个目标?

最佳答案

如果您想避免用户选择项目、行或列,您应该执行以下操作:

  • 覆盖委托(delegate) editorEvent 方法,使其不会通知 View 点击。

  • 停用单击标题部分的功能

from PyQt5 import QtCore, QtGui, QtWidgets


class Delegate(QtWidgets.QStyledItemDelegate):
    def editorEvent(self, event, model, option, index):
        res = super(Delegate, self).editorEvent(event, model, option, index)
        if event.type() in (
            QtCore.QEvent.MouseButtonPress,
            QtCore.QEvent.MouseButtonRelease,
            QtCore.QEvent.MouseButtonDblClick,
            QtCore.QEvent.MouseMove,
            QtCore.QEvent.KeyPress
        ):
            return True
        return res


class TableView(QtWidgets.QTableView):
    def __init__(self, parent=None):
        super(TableView, self).__init__(parent)
        self.setSortingEnabled(False)
        self.horizontalHeader().setSectionResizeMode(
            QtWidgets.QHeaderView.Stretch
        )
        self.setSelectionMode(QtWidgets.QAbstractItemView.MultiSelection)
        self.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        delegate = Delegate(self)
        self.setItemDelegate(delegate)
        self.horizontalHeader().setSectionsClickable(False)
        self.verticalHeader().setSectionsClickable(False)


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)

    model = QtGui.QStandardItemModel()
    for i in range(15):
        for j in range(6):
            it = QtGui.QStandardItem("{}-{}".format(i, j))
            model.setItem(i, j, it)

    table = TableView()
    table.setModel(model)

    # emulate select by query
    import random

    for row in random.sample(range(model.rowCount()), 5):
        table.selectRow(row)

    table.resize(640, 480)
    table.show()
    sys.exit(app.exec_())

关于python - 如何防止用户点击进行行选择,同时保持编程行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55974925/

相关文章:

python - 为具有最小窗口长度的连续系列过滤 pandas 或 numpy 数组

python - 使用 Pynsist 和 PyQt 构建的 GUI : Import Error 'sip'

python - 如何查找 PyQt5 类的帮助?

python - 将 SHAP 瀑布图导出到数据框

python - 不使用 cv2.findChessboardCorners 在 Python 中进行 OpenCV 相机校准

python - 如何组合数据框的月份和年份列以形成时间序列数据

python - Qt HTML Subset——可能的未记录的限制

python - 正确使用 setBackground

python-3.x - openGL 和 PyQt5 的问题

sqlite - 使用PyQt5.QtSql从联接的SQLite表中显示数据?