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.
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);
This can be done with QItemSelectionModel
. You can get selection model with
treeView->selectionModel();
Then connect to model's signal
void currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
and inside the connected slot check if new index is group or not and if group just select previous
model index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With