You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyQt中将QTreeWidget转换为嵌套字典的实现问题求助

问题修复方案

错误原因

你的现有代码核心问题出在两点:

  • 递归全程操作全局self.scheme对象,没有区分当前赋值的父级字典,深层递归结束后后续同级节点会错误插入到上一个子节点的字典里
  • 循环内部直接修改传入的key参数,导致同一层级后续节点的父级定位错误

修正后的实现

调整递归逻辑为每次返回当前层级的字典,不需要额外传key参数,逻辑简单无额外依赖,完全适配你的需求:

def tree_to_dict(self, parent):
    current_dict = {}
    for i in range(parent.childCount()):
        cur_item = parent.child(i)
        item_text = cur_item.text(0)
        if cur_item.childCount() == 0:
            # 叶子节点标记为E
            current_dict[item_text] = 'E'
        else:
            # 非叶子节点递归生成子字典
            current_dict[item_text] = self.tree_to_dict(cur_item)
    return current_dict

# 调用方式示例,root取QTreeWidget的不可见根节点即可
self.scheme = self.tree_to_dict(self.treeWidget.invisibleRootItem())

用你给出的测试结构运行,输出结果和你预期的{'a':'E', 'b':{'a':'E'}, 'c':'E'}完全一致。

小提示:如果你的工具仅面向个人使用,txt+eval的方案实现成本很低完全可用;如果涉及外部用户上传方案,建议替换为json序列化存储更安全。

补充:dict转回QTreeWidget实现

你后续编辑方案需要用到的反向转换逻辑,同样用递归实现即可:

def dict_to_tree(self, parent_item, data_dict):
    for key, value in data_dict.items():
        # 创建当前层级节点
        cur_item = QTreeWidgetItem(parent_item)
        cur_item.setText(0, key)
        if value != 'E':
            # 非叶子节点递归插入子节点
            self.dict_to_tree(cur_item, value)

# 调用方式示例,加载前先清空原有树内容
self.treeWidget.clear()
self.dict_to_tree(self.treeWidget.invisibleRootItem(), self.scheme)

内容的提问来源于stack exchange,提问作者Christopher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 08:15:07