tags:

views:

208

answers:

3

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.

+5  A: 

QTreeView 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.

Patrice Bernassola
Thanks. I've added my own answer but +1 because you helped me get there!
Skilldrick
You're welcome Skilldrick
Patrice Bernassola
A: 

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).

Caleb Huitt - cjhuitt
I couldn't see anything in there that would achieve what I wanted, but thanks anyway.
Skilldrick
+2  A: 

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 :)

Skilldrick