Is there some way to Copy a QStandardItemModel to another QStandardItemModel? Or must I iterate over each tem and append it to the other Model?
Asked
Active
Viewed 4,857 times
6
-
You should iterate over each item and COPY (not append) it to another model. – Dmitry Sazonov Sep 17 '14 at 06:44
2 Answers
9
An item can be owned by one model only. That is why you need to create a copy of each item and place it to another model. You can do it using method QStandardItem::clone
.
This is an example for single column models:
void copy(QStandardItemModel* from, QStandardItemModel* to)
{
to->clear();
for (int i = 0 ; i < from->rowCount() ; i++)
{
to->appendRow(from->item(i)->clone());
}
}
EDIT:
Use to->removeRows(0, to->rowCount ());
instead of to->clear();
if you want to keep header data and column sizes in linked views.

Ezee
- 4,214
- 1
- 14
- 29
-
In my opinion `to->removeRows (0, to->rowCount () )` should be better then `to->clear ()`, because it doesn't remove general settings of model like headers, resize mode, etc. – Gluttton Nov 12 '14 at 07:04
-
@Gluttton A model doesn't have such settings as `resize mode`. Do you mean that calling `clear` forces a view to reset column sizes? – Ezee Nov 12 '14 at 07:21
-
1
You could do copy of an existing item with next steps:
- Get existing item.
- Create new item.
- Set necessary data roles from existing item to a new one.
- Do the same with flags.
Or simply use QStandardItem::clone()
method. And reimplement it, if necessary.

Dmitry Sazonov
- 8,801
- 1
- 35
- 61