在拖放中保留 QStandardItem 子类 [英] Preserve QStandardItem subclasses in drag and drop

查看:44
本文介绍了在拖放中保留 QStandardItem 子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

self.treeView = QTreeView()
self.treeView.setObjectName("testView")
self.treeView.setDragDropMode(QAbstractItemView.InternalMove)
self.treeView.setSelectionMode(QAbstractItemView.ExtendedSelection)

itemA = SubclassQStandardItemA(self)
itemB = SubcalssQStandardItemB(self)

self.model = QStandardItemModel()
self.treeView.setModel(self.model)

self.model.appendRow(itemA)
self.model.appendRow(itemB)

当我将 itemB 移动到 itemA 并检查它的类时,ItemB 不再是 SubclassQStandardItemB 而是 QStandardItem.

When I move itemB to itemA and check its class, ItemB is no longer a SubclassQStandardItemB but a QStandardItem.

如何在拖放时保持项目的原始类?

How can I keep the original class of the item when I drag and drop?

推荐答案

这个答案中所述,您可以使用setItemPrototype 为模型提供项目工厂.但是,正如答案中所述,在拖放操作期间仅传输某些类型的信息.对于QStandardItem,这意味着只有项目标志项目数据.如果使用多个子类,则无法保留项目的特定子类.一个模型只能有一个原型,用于 Qt 内部创建的所有项目.

As explained in this answer, you can use setItemPrototype to provide an item factory for a model. However, as also stated in the answer, only certain kinds of information are transferred during a drag and drop operation. For a QStandardItem, this means only the item flags and item data. There is no way to preserve the specific subclass of the item if there are multiple subclasses being used. A model can have only one prototype, and that is used for all items that are created internally by Qt.

这意味着如果您需要区分不同的项目类型,则不应使用多个 QStandardItem 子类.相反,您应该使用单个子类并重新实现 QStandardItem.type 区分它们:

This means you should not use multiple QStandardItem subclasses if you need to distinguish between different item types. Instead, you should use a single subclass and reimplement QStandardItem.type to distinguish between them:

class MyItem(QtGui.QStandardItem):
    TypeItemA = QtGui.QStandardItem.UserType
    TypeItemB = QtGui.QStandardItem.UserType + 1
    TypeItemC = QtGui.QStandardItem.UserType + 2

    def clone(self):
        return MyItem()

    def type(self):
        return self.data(QtCore.Qt.UserRole + 1000)

    def setType(self, value):
        self.setData(QtCore.Qt.UserRole + 1000, value)

...

itemA = MyItem(self)
itemA.setType(MyItem.TypeItemA)
itemB = MyItem(self)
itemB.setType(MyItem.TypeItemB)

这篇关于在拖放中保留 QStandardItem 子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆