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

如何在QML中使用JSON数据替换Text组件的文本内容

问题描述

需要将QML中Text组件的文本替换为JSON文件里truecurrent数组中对应的数据(原Text文本是J1-25,对应JSON里truecurrent数组中id: "5"的pin值)。

原QML代码:

Text
{
    text: qsTr("J1-25")
    anchors.right: tc1.left
    anchors.rightMargin: 20
    anchors.verticalCenter: tc1.verticalCenter
    color: "white"
    font.pointSize: 10
}

JSON文件内容:

{
  "pwm":
    [
      {"id": "1", "pin": "J2-21"},
      {"id": "2", "pin": "J2-22"},
      {"id": "3", "pin": "J2-23"},
      {"id": "4", "pin": "J2-24"},
      {"id": "5", "pin": "J2-25"},
      {"id": "6", "pin": "J2-26"}
    ],
"truecurrent":
    [
      {"id": "1", "pin": "J1-21"},
      {"id": "2", "pin": "J1-22"},
      {"id": "3", "pin": "J1-23"},
      {"id": "4", "pin": "J1-24"},
      {"id": "5", "pin": "J1-25"},
      {"id": "6", "pin": "J1-26"}
  ]
}

用户尝试的代码:

JsonLoader {
    id: jsonLoader

    filePath: ":/example.json"

}

Text
{
    text: jsonLoader.jsonObject["truecurrent"]["5"]  //原text: qsTr("J1-25")
    anchors.right: tc1.left
    anchors.rightMargin: 20
    anchors.verticalCenter: tc1.verticalCenter
    color: "white"
    font.pointSize: 10
}
正确实现方式

你当前的代码存在问题:truecurrent是数组类型,不是键值对对象,无法直接用["5"]访问对应元素。以下是几种可行的实现方法:

方法1:使用数组find方法查找匹配项

利用JS数组的find方法,直接定位id为"5"的对象并获取pin值:

JsonLoader {
    id: jsonLoader
    filePath: ":/example.json"
}

Text
{
    // 先判断JSON是否加载完成,避免空指针错误
    text: jsonLoader.jsonObject ? 
          jsonLoader.jsonObject.truecurrent.find(item => item.id === "5")?.pin 
          : qsTr("J1-25") // 加载前的默认文本
    anchors.right: tc1.left
    anchors.rightMargin: 20
    anchors.verticalCenter: tc1.verticalCenter
    color: "white"
    font.pointSize: 10
}
  • find(item => item.id === "5"):遍历数组筛选出id匹配的对象
  • ?.pin:可选链操作符,确保对象存在时才读取pin值,防止报错
  • 三元表达式处理JSON未加载完成的情况,保留原文本作为默认值

方法2:转换为键值对对象(适合多次访问场景)

如果需要频繁根据id查找pin值,可以在JSON加载完成后,将truecurrent数组转换为以id为键的对象,后续直接通过键名访问:

JsonLoader {
    id: jsonLoader
    filePath: ":/example.json"
    onJsonObjectChanged: {
        truecurrentMap = {}
        jsonObject.truecurrent.forEach(item => {
            truecurrentMap[item.id] = item.pin
        })
    }
}

property var truecurrentMap: {}

Text
{
    text: truecurrentMap["5"] || qsTr("J1-25")
    anchors.right: tc1.left
    anchors.rightMargin: 20
    anchors.verticalCenter: tc1.verticalCenter
    color: "white"
    font.pointSize: 10
}

方法3:C++辅助解析(可选)

如果项目包含C层,也可以在C中加载并解析JSON,将truecurrent数据整理为QVariantMap暴露给QML,这种方式适合复杂JSON的处理场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 11:53:13