1

Background

In my model I have to keep in one item's data, a reference to another item.

The documentation of QPersistentModelIndex says:

A QPersistentModelIndex is a model index that can be stored by an application, and later used to access information in a model.

QStandardItemModel::setData accepts QVariant as a value, which in turn can be constructed from QPersistentModelIndex, so I am able to write something like this:

...
auto *model = new QStandardItemModel();
auto *referencedItem = new QStandardItem("Test");
auto *item = new QStandardItem();

model->appendRow(referencedItem);
item->setData(QPersistentModelIndex(referencedItem->index()), Qt::UserRole);

// the next line prints "Test"
qDebug() << item->data(Qt::UserRole).toPersistentModelIndex().data().toString();
...

The code compiles and prints:

Test

The accepted answers to another topics, e.g. Storing persistent information about items in view and How to update a QTableView cell with a QCombobox selection?, also suggest the use of QPersistentModelIndex.

Problem

The documentation of QPersistentModelIndex also says:

Note: You cannot store a QStandardItemModel's QPersistentModelIndex in one of the model's items.

Does this mean, that using QPersistentModelIndex like in the code above, i.e.:

item->setData(QPersistentModelIndex(referencedItem->index()), Qt::UserRole);

is wrong and why this should not be done?

scopchanov
  • 7,966
  • 10
  • 40
  • 68
  • I'm guessing it has something to do with removing rows and trying to update things in those rows which were being removed. – Patrick Parker Sep 25 '20 at 04:36
  • OK, but how should this affect the persistent index, stored in the data? It could have been any `QVariant` afterall. Why should this matter? – scopchanov Sep 25 '20 at 07:20
  • The difference is, normal QVariants don't have a special update mechanism that is tied internally to the way Qt handles model row removals. The memory address of every QPersistentModelIndex has to be maintained somewhere and invoked during the row removal process to update its row numbers. So, if it were to be deleted at an unexpected time, that could cause a crash. Again, I am just speculating. It is entirely possible that comment is outdated. Check the source. – Patrick Parker Sep 25 '20 at 16:22
  • @PatrickParker, I have tried moving items around in the model and deleting items from the model. It didn't crashed yet and the indices are updated correctly. So, I am looking further for a possible reason. – scopchanov Sep 25 '20 at 21:03
  • did you try simultaneously deleting a range of several rows that contain self-referencing persistent model index? if that works then I am stumped as well. I have not digged into the source. – Patrick Parker Sep 26 '20 at 01:33
  • In my model there are not any self referencing persistent model indices. An item may only store the index of another item. – scopchanov Sep 26 '20 at 09:10

0 Answers0