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