Search code examples
pythonpyqtqtreewidgetitem

Copy QTreeWidgetItem from QPushButton item widget


I'd like to copy a QTreeWidgetItem, if a push-button is pushed within it.

So far I've got:

def Copy(self):
    obj = self.sender()

self.Tree = qt.QTreeWidget(self)
self.Tree.setHeaderLabels(["Name"])  

item = qt.QTreeWidgetItem("Name") 
self.Tree.addTopLevelItem(item)

childItem = qt.QTreeWidgetItem("Name") #<------- This I'd like to copy

item.addChild(childItem)

bttn = qt.QPushButton("Copy This Widget", self)
bttn.clicked.connect(self.Copy)

self.Tree.setItemWidget(childItem, 1, bttn)

I'd like to be able to copy childItem, so that I may place it in a QTreeWidget.


Solution

  • There's no direct way to get the QTreeWidgetItem from its item-widget, so you will have to explicitly store the index somewhere so that it can be accessed later.

    One way to do this is to add the index to the item-widget as a property:

    bttn = qt.QPushButton("Copy This Widget", self)
    index = QtCore.QPersistentModelIndex(self.Tree.indexFromItem(childItem))
    bttn.setProperty('index', index)    
    
    ...
    
    def Copy(self):
        index = self.sender().property('index')
        if index.isValid():
            copyItem = qt.QTreeWidgetItem(self.Tree.itemFromIndex(index))