使用 Python3 和 pyside。我有一个 python 字典,我想使用 Qt 将其显示为树。我希望值是可编辑的,但不是键。我已经设法使用setItemWidget实现了这一点,如下例所示:
#!/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_())
这可行,但它违背了文档的建议(静态内容),并且无法事先创建小部件(例如在单独的线程中)然后将其添加到树中。有没有更好的方法来实现我想要的?文档中提到了 QTreeView,但我没有找到任何示例/教程让我了解它如何帮助我在列中使用我自己的小部件。