QTreeWidget 镜像 python 字典 [英] QTreeWidget to Mirror python Dictionary
问题描述
有没有办法让 QTreeWidget
反映对内部数据结构(例如字典)所做的更改?似乎他们会在 api 中创建此功能,因为有许多程序可能会与来自多个 GUI 区域的 QTreeWidget
进行交互,但是 QTreeWidget
是在任何时间点显示数据结构.QtGui
项目的文档对我来说不是那么简单,因为它通常指的是 C 文档,我不确定它是如何转移到 python 的.
Is there a way to make a QTreeWidget
mirror the changes made to an internal data structure such as dictionary? It seems like they would have created this functionality within the api, because there are many programs which may interact with QTreeWidget
s from multiple GUI areas, but the main purpose required of the QTreeWidget
is to show a data structure at any point in time. The documentation for QtGui
items is not that simple for me to grasp as it usually refers to C documentation, and I'm not certain how it transfers to python.
所以基本上我想要的是使 QTreeWidget
显示嵌套字典的最简单方式,其中顶级对应于键,子级对应于值.此外,如果值是字典,请使用该级别中的键并为值等创建子级别.
So essentially what I would like is the simplest manner to make a QTreeWidget
show a nested dictionary, where the top level corresponds to the keys and the sub level corresponds to the values. Also, if the values are dictionaries, use the keys in that level and make sub levels for the values, etc.
这容易实现吗?我还没有找到任何东西可以对这样的数据结构进行简单的镜像.
Is this easily doable? I have not been able to find anything to do simple mirroring of data structres like this yet.
推荐答案
这是一个简单的实现:
def fill_item(item, value):
item.setExpanded(True)
if type(value) is dict:
for key, val in sorted(value.iteritems()):
child = QTreeWidgetItem()
child.setText(0, unicode(key))
item.addChild(child)
fill_item(child, val)
elif type(value) is list:
for val in value:
child = QTreeWidgetItem()
item.addChild(child)
if type(val) is dict:
child.setText(0, '[dict]')
fill_item(child, val)
elif type(val) is list:
child.setText(0, '[list]')
fill_item(child, val)
else:
child.setText(0, unicode(val))
child.setExpanded(True)
else:
child = QTreeWidgetItem()
child.setText(0, unicode(value))
item.addChild(child)
def fill_widget(widget, value):
widget.clear()
fill_item(widget.invisibleRootItem(), value)
我添加了列表支持,以防万一有人需要它.
I added list support just in case anyone needs it.
用法:
d = { 'key1': 'value1',
'key2': 'value2',
'key3': [1,2,3, { 1: 3, 7 : 9}],
'key4': object(),
'key5': { 'another key1' : 'another value1',
'another key2' : 'another value2'} }
widget = QTreeWidget()
fill_widget(widget, d)
widget.show()
结果:
这篇关于QTreeWidget 镜像 python 字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!