Search code examples
pythonpyqt5pyside6

QTableWidgetIem, how to get TopLevel text when I click on different childs in different dephts


I have a question about the QTreeWidgetItems. I try when I eg. Have 5 different branched childs and click on the bottom (or last) to get the object name of the topLevelItem. I get it too, but the code for it becomes confusing.

So I would like to ask if there is a more moderate way to get the topLevelItem than with this code:

    def treeItem(self):
        return self.treeWidget.selectedItems()[0]

    def writeJson(self, data, filename="langJson/jsonFile.json"):
        with open(filename, "r+") as f:
            filedata = json.load(f)
            #if data not in filedata:
            for x in range(2):
                try:
                    if self.treeItem().parent().parent().text(0) == self.treeWidget.topLevelItem(x).text(0) or \
                            self.treeItem().parent().parent().parent().text(0) == self.treeWidget.topLevelItem(x).text(0):

                        filedata[self.treeWidget.topLevelItem(x).text(0)].append(data)
                        f.seek(0)
                        json.dump(filedata, f, sort_keys=True,indent=4)
                except:
                    if self.treeItem().parent().text(0) == self.treeWidget.topLevelItem(x).text(0):
                        filedata[self.treeWidget.topLevelItem(x).text(0)].append(data)
                        f.seek(0)
                        json.dump(filedata, f, sort_keys=True, indent=4)

enter image description here

I click on this picture, for example. to gg and want to display Python without the repetitions of parent (). parent () ...

Note: I created the program with the Qt designer, so I didn't post all of the code. But if necessary I edit something about it.


Solution

  • Tree structures require implementing recursive functions.

    To get the top level item of a child, use a while loop to get the parent until a valid parent is found:

        def topLevelParent(self, item):
            while item.parent():
                item = item.parent()
            return item
    

    Then you just call topLevelParent with whatever item you get and the top level will always be returned, even if the given item is a top level one.