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

QML中如何在ListElement中使用属性变量?

QML中ListModel绑定外部属性的错误解决方法

问题说明

在QML中尝试用预定义属性变量构建包含ListElement的ListModel时,出现两个错误:

  • QQmlComponent: Component is not ready
  • cannot use script for property value

相关代码如下:
定义的外部属性:

property string cellTemperature: "0"

尝试使用该属性的ListModel:

ListModel {
    id: mainValuesList
    ListElement { name: "CELL"; listValue: cellTemperature ; sdValue: "_ _SD"}
}

对应的GridView实现:

GridView {
    id: mainValuesGrid
    anchors.fill: parent
    model: mainValuesList
    delegate: Rectangle {

        width: 120
        height: 80
        color: "transparent"

        Text{
            color: "#4A4A4A"
            text: name
        }

        Text{
            color: "#4A4A4A"
            text: listValue
        }

        Text{
            color: "#4A4A4A"
            text: sdValue
        }
    }
}

曾尝试QT_TR_NOOP(cellTemperature)和qsTr(cellTemperature),均无效。

错误根源

ListElement是静态元素,它的属性值必须是常量字面量,无法直接绑定外部QML属性变量(这属于脚本表达式,不符合ListElement的语法要求),这是触发"cannot use script for property value"的原因;而"QQmlComponent: Component is not ready"是组件初始化时,ListModel中的无效表达式导致加载失败引发的连锁问题。

解决方法

方法1:动态添加ListElement并监听属性变化

不在ListModel中直接编写ListElement,而是在组件加载完成后,通过append()方法动态添加数据,同时监听外部属性的变化以更新模型:

property string cellTemperature: "0"

ListModel {
    id: mainValuesList
}

Component.onCompleted: {
    // 初始化添加数据
    mainValuesList.append({
        name: "CELL",
        listValue: cellTemperature,
        sdValue: "_ _SD"
    })
    // 监听属性变化,实时更新模型
    cellTemperature.onChanged: {
        mainValuesList.set(0, {listValue: cellTemperature})
    }
}

方法2:在Delegate中直接绑定外部属性

如果不需要将外部属性存入ListModel,可以直接在delegate中引用该属性,简化结构:

property string cellTemperature: "0"

ListModel {
    id: mainValuesList
    ListElement { name: "CELL"; sdValue: "_ _SD"}
}

GridView {
    id: mainValuesGrid
    anchors.fill: parent
    model: mainValuesList
    delegate: Rectangle {
        width: 120
        height: 80
        color: "transparent"

        Text{ color: "#4A4A4A"; text: name }
        Text{ color: "#4A4A4A"; text: cellTemperature } // 直接绑定外部属性
        Text{ color: "#4A4A4A"; text: sdValue }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:01:52