Search code examples
pythonpyqt5qtreewidgetitem

PyQt5 QtreeWidget : How can i access a custom widget's methods in a QtreeWidgetItem?


I have a simple QTreeWidget :

self.treeWidget = QTreeWidget(self)
col = ("Status", "Name")
self.treeWidget.setColumnCount(2)
self.treeWidget.setHeaderLabels(col)

witch I populate using :

wid = Custom_Widget()
item = QTreeWidgetItem(self.treeWidget)
item.setText(1, "some string")
item.treeWidget().setItemWidget(item, 0, wid)

I can easly acces the text column by using :

root = self.treeWidget.invisibleRootItem()
it = root.child(2) # for example the third item
it.setText(1, "Edited")

what i need is to edit the costum_widget in column 0, so how can i access it or invoke his methods ?


Solution

  • I resolved the issue by keeping a list of all the costum_widgets that i create, my code would be :

    from CustomWidgets import Custom_Widget
    from PyQt5.QtWidgets import *
    import sys
    
    
    class MyExample(QWidget):
    
        def __init__(self):
            super().__init__()
    
            self.treeWidget = QTreeWidget(self)
            self.group_wid = []  # my list of widgets
            col = ("Status", "Name")
            self.treeWidget.setColumnCount(2)
            self.treeWidget.setHeaderLabels(col)
    
            self.populate_tree()
            self.edit_tree()
            self.show()
    
        def populate_tree(self):
            for i in range(10):
                wid = Custom_Widget()
                self.group_wid.append(wid)  # each time i instantiate a Custom_Widget i'll add it to my list of widgets
                item = QTreeWidgetItem(self.treeWidget)
                item.setText(1, "some string")
                item.treeWidget().setItemWidget(item, 0, wid)
    
        def edit_tree(self):
            root = self.treeWidget.invisibleRootItem()
            it = root.child(2)  # for example the third item
            it.setText(1, "Edited")
            self.group_wid[2].my_method()  # i can easily edit my widgets that are in the QTreeWidget
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = MyExample()
        app.exec_()
    

    Guess the QtreeWidgetItem only hold a reference to the widgets that are contained.