Copy QStandardItemModel to another
Asked Answered
S

2

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?

Sagittate answered 17/9, 2014 at 6:6 Comment(1)
You should iterate over each item and COPY (not append) it to another model.Variegate
W
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.

Wordbook answered 17/9, 2014 at 7:42 Comment(3)
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.Heartless
@Heartless A model doesn't have such settings as resize mode. Do you mean that calling clear forces a view to reset column sizes?Wordbook
Do you mean, Yes, indeed!Heartless
V
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.

Variegate answered 17/9, 2014 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.