6

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?

Matthias
  • 461
  • 7
  • 24

2 Answers2

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
  • `Do you mean`, Yes, indeed! – Gluttton Nov 12 '14 at 07:28
1

You could do copy of an existing item with next steps:

  1. Get existing item.
  2. Create new item.
  3. Set necessary data roles from existing item to a new one.
  4. Do the same with flags.

Or simply use QStandardItem::clone() method. And reimplement it, if necessary.

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