How to change item editable / not-editable in QAbstractItemModel?
-
Hi,
We want to make our table columns editable or not-editable with user input. Therefore, we write a function to do that.
- Qt Version : 5.9.7
- We are allowed to use only
QAbstractItemModel
. this
pointer isQTableView
The function code block is below.
void setColumnEditable(const int &column, const bool is_editable) const { QAbstractItemModel *p_model = this->model(); if(Q_NULLPTR == p_model) return; if(0 <= column) { for(int row = 0; row < p_model->rowCount(); ++row) { p_model->flags(p_model->index(row,column)).setFlag(Qt::ItemIsEditable,is_editable); qDebug() << "is editable ?" << is_editable << p_model->flags(p_model->index(row,column)); } } }
qDebug result:
is editable ? true QFlags<Qt::ItemFlags>(ItemIsSelectable|ItemIsDragEnabled|ItemIsDropEnabled|ItemIsEnabled)
However,
ItemIsEditable
does not set.How can we change the
ItemFlags
? -
Hi,
You are changing the value of the temporary object returned by the flags method.
What model are you currently use ?
-
@Oktay-K said in How to change item editable / not-editable in QAbstractItemModel?:
p_model->flags(p_model->index(row,column)).setFlag(Qt::ItemIsEditable,is_editable);
https://doc.qt.io/qt-5/qabstractitemmodel.html#flags shows
Qt::ItemFlags QAbstractItemModel::flags(const QModelIndex &index) const
isconst
, and the flags it returns is just a copied value. CallingsetFlag()
on that does nothing to the model.I think you have to implement a
yourModelItem.setFlags()
, storing the value into the data. For example https://doc.qt.io/qt-5/qstandarditem.html#setFlags might be implemented via:void QStandardItem::setFlags(Qt::ItemFlags flags) { setData((int)flags, Qt::UserRole - 1); }
Or, if you want every item to be editable, or certain columns to be editable, without having to selectively store that against individual items, you might subclass
QAbstractItemModel
and override its virtualflags()
to return flags plus OR-inQt::ItemIsEditable
where appropriate, but I'm not sure that is what you want if you wish the user to be able to affect it. -
Then retrieve the item matching the index and set the new flags on it.
The method is:
- retrieve the flags from the item
- change them
- set the changed flags on the item