How to reproduce the same operations (Copy, Paste, ...) on different items of a Qt Model/View?

53 views Asked by At

I have a custom QTreeView and I fill it with custom QStandardItems. The model is a classic QStandardItemModel.

I would like to have the possibility to have the same item repeated in the Tree. This means that if I change some properties of the item (e.g.: text) or if I change some if its children, these changes are repeated to the corresponding items.

It would have been awesome to use the same QStandardItem more than once but I found out that it's not possible.

Maybe some pictures of what I would like could clarify what I mean:

  • Starting Point:

enter image description here

  • B1 item is renamed and the name is automatically changed also for the other B1 item:

enter image description here

  • B1's C1 item is moved and this move is automatically reproduced on the other B1 item:

enter image description here

My solution so far:

  • every time an item is changed, I check (by looking at a specific key stored in the item's data) if there is any other item equal to this
  • If so, I copy the data from the changed item. For what concerns the children, I remove all the children from the second item, copy every child from the changed one (creating new items) and appending them to the second item.

This solution works but there are 2 problems:

  • I don't like it
  • It is slow when there are too many children (they could be 2000-3000) and an item is repeated more than twice.
  • There are corner cases where there might be (strange) problems

There must be a better way but I didn't find it out.

1

There are 1 answers

0
mugiseyebrows On

You figured problem yourself: data in your model is duplicated, QStandardItemModel it not a good solution for this case.

You can solve your problem using custom model inherited from QAbstractItemModel. Take a look at editabletreemodel example for reference. You need to create items that point to same data so when you edit one, others changed automatically.