Clear selection when clicking on blank area of Item View

后端 未结 1 1101
暗喜
暗喜 2021-01-21 23:08

I made a tree structure with QTreeWidget, and it works well. But I have a problem with that. Commonly, with a tree structure, if I want to deselect all, I click on

相关标签:
1条回答
  • 2021-01-21 23:57

    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)
    
    0 讨论(0)
提交回复
热议问题