Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QTreeView disable selection on some rows

Tags:

c++

qt

qt5

I Have a JSON model, and I populate it with QTreeView:

*-group1
| |  
| *-item1     value1
| |
| *-item2     value2
|
*-group2
  |
  *-item4     value3

Now I want to disable selection for groups, so that user can select only rows with items. And I want to achive it without modification of model.

like image 224
Jeka Avatar asked Jan 27 '16 14:01

Jeka


2 Answers

Use a proxy model such as QIdentityProxyModel and reimplement QAbstractItemModel::flags(), removing the Qt::ItemIsSelectable flag for the group items:

Qt::ItemFlags DisableGroupProxyModel::flags(const QModelIndex& index) const {
   const auto flags = QIdentityProxyModel::flags(index);
   if (index is group) {
       return flags & ~Qt::ItemIsSelectable;
   }

   return flags;
}

Then set the original (unmodified) model as source model of this proxy model and the proxy model instance as the tree view’s model:

DisableGroupProxyModel* proxy = new DisableGroupProxyModel(this);
proxy->setSourceModel(originalModel);
treeView->setModel(proxy);
like image 90
Frank Osterfeld Avatar answered Oct 09 '22 06:10

Frank Osterfeld


This can be done with QItemSelectionModel. You can get selection model with

treeView->selectionModel();

Then connect to model's signal

void currentRowChanged(const QModelIndex &current, const QModelIndex &previous)

and inside the connected slot check if new index is group or not and if group just select previous model index.

like image 28
Evgeny Avatar answered Oct 09 '22 06:10

Evgeny