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.
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 :)
It should be noted that this emits the relevant signals from the selection model, so if you're listening to them, this will usually lead to unwanted behaviour (i.e. if you always open/close a view for the selected item, this would lead to the page being closed and opened rapidly). You can circumnavigate this by blocking the selection model's signals