Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

qt

pyqt

qtreeview

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.

like image 372
Skilldrick Avatar asked May 03 '10 21:05

Skilldrick


1 Answers

Based on @Eric's solution, and as it only deselects if the clicked item was selected, here is what I came up with. This solution also works when you click the blank area of the QTreeView

#ifndef DESELECTABLETREEVIEW_H
#define DESELECTABLETREEVIEW_H
#include "QTreeView"
#include "QMouseEvent"
#include "QDebug"
class DeselectableTreeView : public QTreeView
{
public:
    DeselectableTreeView(QWidget *parent) : QTreeView(parent) {}
    virtual ~DeselectableTreeView() {}

private:
    virtual void mousePressEvent(QMouseEvent *event)
    {
        QModelIndex item = indexAt(event->pos());
        bool selected = selectionModel()->isSelected(indexAt(event->pos()));
        QTreeView::mousePressEvent(event);
        if ((item.row() == -1 && item.column() == -1) || selected)
        {
            clearSelection();
            const QModelIndex index;
            selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select);
        }
    }
};
#endif // DESELECTABLETREEVIEW_H

Yassir

like image 144
Yassir Ennazk Avatar answered Oct 04 '22 00:10

Yassir Ennazk