Solved How to set data for the new row when override QAbstractItemModel::insertRows
-
override
virtual QAbstractItemModel::insertRows(int row, int count, const QModelIndex &parent = QModelIndex())
, no data in parameters, how to set data for the new row? -
@jronald
call setData() after the row(s) have been successfully inserted -
@raven-worx said in How to set data for the new row when override QAbstractItemModel::insertRows:
@jronald
call setData() after the row(s) have been successfully insertedIs this the formal way?
Thanks -
@jronald
It depends what you have as model. For example, if you store your data in QList<myType>myList you can do like this:bool myModel::insertRows(int position, int rows, const QModelIndex &parentIndex) { Q_ASSERT(checkIndex(parentIndex)); if(position<0 || position>rowCount(parentIndex) || rows<=0) return false; beginInsertRows(parentIndex, position, position+rows-1); while (rows--) myList.insert(position, new myType("arg1", "arg2", "arg3")); endInsertRows(); return true; }
[VRonin] edited indexes in
beginInsertRows
to be correct and added input checks -
@JoZCaVaLLo
this wont work.
without the necessary beginInsertRows()/endInsertRows() calls the view wont update.
Also in your code where are the arg variables coming from? -
@JoZCaVaLLo said in How to set data for the new row when override QAbstractItemModel::insertRows:
@jronald
It depends what you have as model. For example, if you store your data in QList<myType>myList you can do like this:myList.insert(position, new myType(arg1, arg2, arg3));
Where do
arg1
arg2
arg3
come from? -
@raven-worx
You are right... I edited the code! -
@jronald
it's an example... the model depends up to you... arg1 arg2 arg3 can be anything... -
@JoZCaVaLLo said in How to set data for the new row when override QAbstractItemModel::insertRows:
@jronald
it's an example... the model depends up to you... arg1 arg2 arg3 can be anything...so
arg1
arg2
arg3
are member variables? -
To clarify:
@raven-worx's answer is the only way sticking only to theQAbtsractItemModel
interface.call setData() after the row(s) have been successfully inserted
You are free, of course, to implement your own custom interface that allows for insertion with data either by creating something like
bool insertRowData(int row, const QVector<QVariant>& dataColumns);
or by having a constant or a member variable define what the default data should be