First of all Im out of practice and Im trying to create a tree structure in Python 3.8 to feed my QTreeView.
I read the output of zfs (subprocess.check_output) and split the whole stuff to have a list with pool names:
Example list:
pools = ['deadpool','deadpool/Backup','deadpool/Photos','deadpool/Photos/Foobar']
Now I've to convert and sort the whole list by parent/child and it should look like this at the end so I can use it in a QTreeView:
{'deadpool':
{
'Backup': {},
'Photos': {'Foobar': {}},
}
}
I tried it with two for loops but Im just too stupid..
Can someone show me an easy example?
Or is there an easier way in QtTreeView/QTreeWidget itself?
If I understood your question, you want to build a treewidget from a dict ? If it is, this is a very quick example with Pyside2 (I think there is no problem with PyQt5 for the Treewidget).
data = {
'deadpool':{
'Backup': {},
'Photos': {
'Foobar': {}
}
}
}
def build_tree(data=None, parent=None):
for key, value in data.items():
item = QTreeWidgetItem(parent)
item.setText(0, key)
if isinstance(value, dict):
build_tree(data=value, parent=item)
window = QWidget()
layout = QVBoxLayout()
window.setLayout(layout)
treewidget = QTreeWidget()
build_tree(data=data, parent=treewidget)
layout.addWidget(treewidget)
window.show()
If you just want convert your list to the dict in order to use it in the treewidget you can try this:
data = ['deadpool','deadpool/Backup','deadpool/Photos','deadpool/Photos/Foobar']
tree = {}
for path in data: # for each path
node = tree # start from the very top
for level in path.split('/'): # split the path into a list
if level: # if a name is non-empty
node = node.setdefault(level, dict())
# move to the deeper level
# (or create it if unexistent)
print(tree)
This code above is from this topic : Stackoverflow
And now your have a dict to use with the fisrt bloc of code !
I hope it will help you !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.