Using Python3 and pyside. I have a python dictionary which I want to display as a tree using Qt. I want the values to be editable but not the keys. I have managed to achieve this using setItemWidget as shown in the following example:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui
def data_to_tree(parent, data):
if isinstance(data, dict):
parent.setFirstColumnSpanned(True)
for key,value in data.items():
child = QtGui.QTreeWidgetItem(parent)
child.setText(0, key)
data_to_tree(child, value)
elif isinstance(data, list):
parent.setFirstColumnSpanned(True)
for index,value in enumerate(data):
child = QtGui.QTreeWidgetItem(parent)
child.setText(0, str(index))
data_to_tree(child, value)
else:
widget = QtGui.QLineEdit(parent.treeWidget())
widget.setText(str(data))
parent.treeWidget().setItemWidget(parent, 1, widget)
app = QtGui.QApplication(sys.argv)
wid = QtGui.QTreeWidget()
wid.setColumnCount(2)
wid.show()
data = {
'foo':'bar',
'bar': ['f', 'o', 'o'],
'foobar':0,
}
data_to_tree(wid.invisibleRootItem(), data)
sys.exit(app.exec_())
This works, but it goes against what the documentation advises (static content) and makes it impossible to create the widget beforehand (in a separate thread for example) and then add it to the tree. Is there any better way to achieve what I want? Documentation mention QTreeView but I haven't found any example/tutorial that let me understand how it would help me use my own widget in a column.