Python / pyside using custom widget in qtreewidget

Using Python3 and pyside. I have a python dictionary that I want to display as a tree using Qt. I want the values โ€‹โ€‹to be editable, but not keys. I 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 contradicts what the documentation advises (static content) and makes it impossible to pre-create a widget (for example, in a separate thread) and then add it to the tree. Is there a better way to achieve what I want? The documentation mentions QTreeView, but I have not found a single example / tutorial that would allow me to understand how this will help me use my own widget in a column.

+1
python qt pyside qtreeview qtreewidget
source share
1 answer

There are two options you can consider:

  • You can create your own class, which is a subclass of QTreeWidget . This is simple because you simply use the method you have and put it inside the class. But this does not change much, except that it will look more โ€œnaturalโ€ when you call it in your custom widget.

  • Another method that most likely refers to documentation is the Model / View architecture.

In this case, you will have to use QTreeView and create your own QTreeModel . Here, the view absolutely does not know what data is, and the model is responsible for providing all the data and notifies the view when it is ready for display. Thus, you must make this object and emit a signal when the data is ready / modified in order to update the view.

For an idea of โ€‹โ€‹how you can implement something like this, you can take a look at the examples presented with PySide. Most likely you installed them, see site-packages/PySide/examples/itemviews/simpletreemodel .

Also, consider the indexWidget method so you can add a QEditLine where necessary and call the parent for the standard one.

+2
source share

All Articles