I already managed to properly create this treewidget from a dictionary, but now I want to reverse engineer it, and I want to create a dictionary from this qtreewidget. I am quite lost on how to do that, it seems straight forward but I fail.
The idea is to get the parent items
for index in range(self.treeWidget.topLevelItemCount()):
parent = self.treeWidget.topLevelItem(index)
from there on I need to recursively go through each sublevel with parent.childCount(), if childCount is valid, then iterate over child.
But I dont know how to create a dictionary from that. Please someone help me out.. Ideally I get something like this
"core.global_vars.arrunner_qmenu_object_name"
"core.global_vars.metadata_label"
"core.logger.console_verbosity"
Or in the best case {"core:{"global_vars:{"arrunner_qmenu_object_name":None}}, ...}
UPDATE
replaceJson is the main functions which gets the root parents,
from there on I gather all the childrens and add them to global children list.
After that, I generate a string from that "root.child.child.child" which I can expand to a dict {"root":"{"child":...}}
Then back in replace Json I add the string to the config.. There is probably a way easier way.. Any help is appreciated.
so this is what I came up with:
def children(self, parent):
global children
childCount = parent.childCount()
if childCount:
for index in range(childCount):
self.children(parent.child(index))
elif not parent.parent() and not parent.text(1): # top levels without children
children.append(parent)
if parent.text(1):
children.append(parent)
def generateString(self, treeItem):
def getParent(item):
if item.parent():
global parents
parents.append(str(item.parent().text(0)))
getParent(item.parent())
global parents
parents = [str(treeItem.text(0))]
getParent(treeItem)
attribute, value = '.'.join(parents[::-1]), treeItem.text(1)
return attribute, value
def _replaceJson(self):
super(JsonEditor, self)._replaceJson()
writeToFile(self.configFile, "{}")
# Getting children
global children
children = []
for index in range(self.treeWidget.topLevelItemCount()):
parent = self.treeWidget.topLevelItem(index)
self.children(parent)
# Generating config string
for child in children:
attribute, value = self.generateString(child)
self._addToConfig(attribute, value)
self.log.info("Updated config file: {}".format(os.path.basename(self.configFile)))
self.close()