简体   繁体   English

如何在 Qt 模型/视图的不同项目上重现相同的操作(复制、粘贴等)?

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

I have a custom QTreeView and I fill it with custom QStandardItems .我有一个自定义QTreeView并用自定义QStandardItems填充它。 The model is a classic QStandardItemModel . model 是一个经典的QStandardItemModel

I would like to have the possibility to have the same item repeated in the Tree .我希望有可能在 Tree 中重复相同的项目 This means that if I change some properties of the item (eg: 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.多次使用同一个 QStandardItem 会很棒,但我发现这是不可能的。

Maybe some pictures of what I would like could clarify what I mean:也许我想要的一些图片可以澄清我的意思:

  • Starting Point:初始点:

在此处输入图像描述

  • B1 item is renamed and the name is automatically changed also for the other B1 item: B1 项已重命名,其他 B1 项的名称也会自动更改:

在此处输入图像描述

  • B1's C1 item is moved and this move is automatically reproduced on the other B1 item: B1 的 C1 物品被移动并且这个移动会自动复制到另一个 B1 物品上:

在此处输入图像描述

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:此解决方案有效,但存在 2 个问题:

  • 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.当有太多孩子(他们可能是 2000-3000)并且一个项目重复两次以上时,它会很慢。
  • There are corner cases where there might be (strange) problems有些极端情况可能会出现(奇怪的)问题

There must be a better way but I didn't find it out.一定有更好的方法,但我没有找到。

You figured problem yourself: data in your model is duplicated , QStandardItemModel it not a good solution for this case.您自己发现了问题:您的 model 中的数据是重复的,对于这种情况, QStandardItemModel不是一个好的解决方案。

You can solve your problem using custom model inherited from QAbstractItemModel .您可以使用从QAbstractItemModel继承的自定义 model 解决您的问题。 Take a look at editabletreemodel example for reference.查看editabletreemodel示例以供参考。 You need to create items that point to same data so when you edit one, others changed automatically.您需要创建指向相同数据的项目,以便在您编辑一个时,其他项目会自动更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM