如何修改 QTreeWidget 选择行为

How to modify QTreeWidget Selection Behavior

下面的代码创建了一个 QTreeWidget。 单击任何项​​目将其添加到当前选择(QTreeWidget 设置为支持 MultiSelection)。但我只想在使用 Shift 或 Command 修饰键时添加到当前选择。

app = QApplication([])
widget = QTreeWidget()
widget.setSelectionMode(QAbstractItemView.MultiSelection)
widget.setColumnCount(5)
for row in range(7):
    item = QTreeWidgetItem(widget)
    for col in range(5):
        item.setText(col, 'Column %s' % col)
widget.show()
qApp.exec_()

必须覆盖 mouseMoveEventmousePressEvent 方法,并在其中决定是否采取任何行动。

class TreeWidget(QTreeWidget):
    def mouseMoveEvent(self, event):
        if QApplication.keyboardModifiers()&(Qt.ShiftModifier|Qt.ControlModifier):
            QTreeWidget.mouseMoveEvent(self, event)

    def mousePressEvent(self, event):
        if QApplication.keyboardModifiers()&(Qt.ShiftModifier|Qt.ControlModifier):
            QTreeWidget.mousePressEvent(self, event)

if __name__ == '__main__':
    import sys

    app = QApplication(sys.argv)
    widget = TreeWidget()
    widget.setSelectionMode(QAbstractItemView.MultiSelection)
    widget.setColumnCount(5)
    for row in range(7):
        item = QTreeWidgetItem(widget)
        for col in range(5):
            item.setText(col, 'Column %s' % col)
    widget.show()
    sys.exit(app.exec_())

仅通过 ExtendedSelection 更改多选。将会: widget.setSelectionMode(QAbstractItemView.ExtendedSelection)

qt5 文档(5.13 版)https://doc.qt.io/qt-5/qabstractitemview.html#SelectionMode-enum