PyQt4 : Determine click on blank area of QTreeWidg

2019-02-27 21:15发布

问题:

I made a tree structure with QTreeWidget, and it works well. But, I have a problem with that. Commonly, with tree structure if I want to deselect all, I click on blank area of tree area. QTreeWidget does not support that work.(or I can't find the tip?)

Sub-classing? or something else can solve the problem? determining the clicking on blank area seems that key of the solution, but I can't find SIGNAL or anything.

Thank you for any help :)

回答1:

A sub-class is probably the simplest choice (although the same thing could be achieved with an event filter).

This example code will clear the selection when clicking on a blank area, or when pressing the Escape key when the tree widget has the keyboard focus:

class TreeWidget(QTreeWidget):
    ...

    def keyPressEvent(self, event):
        if (event.key() == Qt.Key_Escape and
            event.modifiers() == Qt.NoModifier):
            self.clearSelection()
        else:
            QTreeWidget.keyPressEvent(self, event)

    def mousePressEvent(self, event):
        if self.itemAt(event.pos()) is None:
            self.clearSelection()
        QTreeWidget.mousePressEvent(self, event)