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

QTreeWidget点击任意层级子项如何优雅获取顶层节点文本

QTreeWidget任意深度子节点获取顶层节点文本方案

核心优化思路

  • 新增通用工具方法循环向上遍历父节点,直到找到无父节点的顶层item,兼容任意深度的子节点,无需手动逐层调用parent()
  • 移除冗余重复的文件写入逻辑和粗暴的全局异常捕获,提升代码可维护性

完整优化代码

import json

# 新增通用获取顶层节点的方法
def get_top_level_item(self, item):
    while item.parent() is not None:
        item = item.parent()
    return item

def treeItem(self):
    return self.treeWidget.selectedItems()[0]

def writeJson(self, data, filename="langJson/jsonFile.json"):
    # 先获取当前选中项对应的顶层节点
    selected_item = self.treeItem()
    top_item = self.get_top_level_item(selected_item)
    top_text = top_item.text(0)

    # 读写JSON优化:先读再用w模式写入,避免r+模式下内容变短产生的尾部残留问题
    with open(filename, "r", encoding="utf-8") as f:
        filedata = json.load(f)
    
    # 匹配顶层节点后写入数据,若要兼容动态数量的顶层节点可将range(2)改为range(self.treeWidget.topLevelItemCount())
    for x in range(2):
        if top_text == self.treeWidget.topLevelItem(x).text(0):
            filedata[top_text].append(data)
            break
    
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(filedata, f, sort_keys=True, indent=4)

优化点说明

  • 不管选中的子节点有多少层,get_top_level_item都能正确返回对应的顶层节点,后续树结构层级变化不需要修改逻辑
  • 原来的多处重复json.dump逻辑合并为一处,修改配置时只需调整一次
  • 拆分文件读写为读、写两个步骤,避免r+模式下新内容长度小于旧内容时,文件尾部残留旧内容的隐性bug
  • 移除了无差别捕获所有异常的逻辑,避免隐藏其他未知运行错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 04:15:00