Clear selection when clicking on blank area of Item View

坚强是说给别人听的谎言 提交于 2019-11-28 14:28:50

The example code below will clear the selection (and current item) when clicking on a blank area, or when pressing Esc when the tree widget has the keyboard focus. It will work with any widget which inherits QAbstractItemView (not just QTreeWidget):

class MyWidget(QTreeWidget):
    def keyPressEvent(self, event):
        if (event.key() == Qt.Key_Escape and
            event.modifiers() == Qt.NoModifier):
            self.selectionModel().clear()
        else:
            super(MyWidget, self).keyPressEvent(event)

    def mousePressEvent(self, event):
        if not self.indexAt(event.pos()).isValid():
            self.selectionModel().clear()
        super(MyWidget, self).mousePressEvent(event)

To avoid subclassing, an event-filter can be used instead:

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.widget = QTreeWidget()
        self.widget.installEventFilter(self)
        self.widget.viewport().installEventFilter(self)
        ...

    def eventFilter(self, source, event):
        if ((source is self.widget and
             event.type() == QEvent.KeyPress and
             event.key() == Qt.Key_Escape and
             event.modifiers() == Qt.NoModifier) or
            (source is self.widget.viewport() and
             event.type() == QEvent.MouseButtonPress and
             not self.widget.indexAt(event.pos()).isValid())):
            self.widget.selectionModel().clear()
        return super(Window, self).eventFilter(source, event)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!