Preserve QStandardItem subclasses in drag and drop(在拖放中保留 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 子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在拖放中保留 QStandardItem 子类
基础教程推荐
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
