Search code examples
qtpyqtqtreeview

Is it possible to deselect in a QTreeView by clicking off an item?


I'd like to be able to deselect items in my QTreeView by clicking in a part of the QTreeView with no items in, but I can't seem to find anyway of doing this. I'd intercept a click that's not on an item, but the QTreeView doesn't have a clicked signal, so I can't work out how to do this.


Solution

  • This is actually quite simple (in PyQt):

    class DeselectableTreeView(QtGui.QTreeView):
        def mousePressEvent(self, event):
            self.clearSelection()
            QtGui.QTreeView.mousePressEvent(self, event)
    

    Qt uses mousePressEvent to emit clicked. If you clear the selection before sending on the event, then if an item is clicked it will be selected, otherwise nothing will be selected. Many thanks to Patrice for helping me out with this one :)