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.
views:
208answers:
3QTreeView
inherits from QAbstractView
(http://doc.trolltech.com/4.6/qtreeview.html) which has a clicked
signal. The problem is that the signal is emitted only when index is valid so you can not achieve what you want with this signal.
Try to intercept the mousePressEvent
instead. In the function you can find where the user has clicked and deselect selected item if needed.
You could try setting a different selection mode for your widget. I don't know if any of them quite covers what it appears you want (single selection, but deselectable).
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 :)