Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy QStandardItemModel to another

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?

like image 806
Matthias Avatar asked Sep 17 '14 06:09

Matthias


People also ask

Does qstandarditemmodel support both copy and move?

: QAbstractItemModel::headerData(section, orientation, role); 2886 2887 2888 2889 eimp 2890 2891 QStandardItemModel supports both copy and move. 2892

How do I insert a row in qstandarditemmodel?

QStandardItemModel.insertRow (self, int row, list-of-QStandardItem items) The itemsargument has it's ownership transferred to Qt. Inserts a row at rowcontaining items. If necessary, the column count is increased to the size of items. This function was introduced in Qt 4.2. See alsotakeRow(), appendRow(), and insertColumn().

What does qstandarditemqstandarditemmodel itemprototype () return?

QStandardItemQStandardItemModel.itemPrototype (self) Returns the item prototype used by the model. The model uses the item prototype as an item factory when it needs to construct new items on demand (for instance, when a view or item delegate calls setData()). This function was introduced in Qt 4.2. See alsosetItemPrototype().

How to copy an item from one model to another?

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. void copy (QStandardItemModel* from, QStandardItemModel* to) { to->clear (); for (int i = 0 ; i < from->rowCount () ; i++) { to->appendRow (from->item (i)->clone ()); } }


2 Answers

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.

like image 135
Ezee Avatar answered Sep 22 '22 04:09

Ezee


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.

like image 32
Dmitry Sazonov Avatar answered Sep 22 '22 04:09

Dmitry Sazonov