gpt4 book ai didi

python - QTreeWidget 镜像 python 字典

转载 作者:太空狗 更新时间:2023-10-29 21:17:28 26 4
gpt4 key购买 nike

有没有办法使 QTreeWidget 反射(reflect)对内部数据结构(如字典)所做的更改?看起来他们会在 api 中创建此功能,因为有许多程序可能与来自多个 GUI 区域的 QTreeWidget 交互,但 QTreeWidget 所需的主要目的> 是展示任意时间点的数据结构。 QtGui 项的文档对我来说不是那么容易掌握,因为它通常指的是 C 文档,而且我不确定它如何转移到 python。

所以基本上我想要的是使 QTreeWidget 显示嵌套字典的最简单方法,其中顶级对应于键,子级对应于值。此外,如果值是字典,则使用该级别中的键并为值创建子级别等。

这很容易做到吗?我还没有找到任何东西来做像这样的数据结构的简单镜像。

最佳答案

这是一个简单的实现:

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)

我添加了列表支持以防万一有人需要它。

用法:

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()

结果:

screenshot

关于python - QTreeWidget 镜像 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21805047/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com