Warm tip: This article is reproduced from serverfault.com, please click

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

发布于 2010-05-03 21:18:16

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.

Questioner
Skilldrick
Viewed
0
Skilldrick 2010-05-05 04:59:12

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