How to drop a custom QStandardItem into a QListView

后端 未结 1 1941
抹茶落季
抹茶落季 2020-12-11 07:30

I am trying to get drag&drop to work between two QListViews using a custom QStandardItem. I can\'t find the info I need online other than this document which helped a li

相关标签:
1条回答
  • 2020-12-11 08:25

    It looks like you want setItemPrototype. This provides an item factory for the model, so that it will implicitly use your custom class whenever necessary.

    All you need to do is reimplement clone() in your item class:

    class MyItem(QtGui.QStandardItem):
        '''This is the item I'd like to drop into the view'''
    
        def __init__(self, parent=None):
            super(MyItem, self).__init__(parent)
            self.testAttr = 'test attribute value'
    
        def clone(self):
            return MyItem()
    

    An then set an instance of that class as the prototype on the receiving model:

        # models
        model1 = QtGui.QStandardItemModel()
        model2 = QtGui.QStandardItemModel()
        model2.setItemPrototype(MyItem())
    

    You can forget about all the datastream stuff.

    PS:

    I suppose I should point out that Qt obviously knows nothing about any python data attributes that may have been set during the item's lifetime, and so those won't get serialized when the item is transferred during a drag and drop operation. If you want to persist data like that, use setData() with a custom role:

    class MyItem(QtGui.QStandardItem):
        _TestAttrRole = QtCore.Qt.UserRole + 2
    
        def clone(self):
            item = MyItem()
            item.testArr = 'test attribute value'
            return item
    
        @property
        def testAttr(self):
            return self.data(self._TestAttrRole)
    
        @testAttr.setter
        def testAttr(self, value):
            self.setData(value, self._TestAttrRole)
    
    0 讨论(0)
提交回复
热议问题