如何动态地向QML元素添加属性?

Kal*_*ain 6 qml

我想动态地向QML元素添加属性:

Item {
 id: dynamicProperty;
 property int first;


 Component.onCompleted: {
  /* once this block of code is executed, i want to add
     property int second; property bool third; property variant fourth;
  */
 }

}
Run Code Online (Sandbox Code Playgroud)

有没有办法完成上述任务.

der*_*erM 7

一方面:我没有看到,为什么有人会想这样做,因为它完全不是声明性的.但是,由于QML扩展了JavaScript,后者是原型语言,是的,你可以做到.

关于操作方法,我建议阅读有关如何定义属性的JS-Documentation .不过我写了一个简短的例子来证明它的用法.

MouseArea {
    anchors.fill: parent
    onClicked: console.log(rect.newProp)
}

Rectangle {
    id: rect
    width: 50
    height: 50
    x: 50
    y: 50
    color: 'green'

    MouseArea {
        anchors.fill: parent
        onClicked: { var obj = Object.defineProperty(rect, 'newProp',
                                                     {
                                                         enumerable: false,
                                                         configurable: false,
                                                         writable: false,
                                                         value: '50'
                                                     })}
    }
}
Run Code Online (Sandbox Code Playgroud)

在第一次单击背景时,将打印"undefined".单击矩形后,这将更改为"50".

  • 不,该功能并未在 QML 中完全实现。如果你想改变这个值,你总是需要通过“defineProperty”函数来设置它。需要明确的是:此属性不等同于 QML 属性。我认为这是部分原因,因为“描述符”没有被完全评估。似乎“enumerable”、“writable”、“setter”和“getter”被忽略了。因此,我通常会在我的对象中添加一个小函数“setDynProp(prop, value)”——在极少数情况下我确实需要这个函数。 (2认同)

ser*_*rgk 5

我不认为QML旨在支持动态属性创建。

根据您的用例,可以使用“脚本实例”解决这个问题(我组成了这个术语)。基本上,每个没有.pragma library声明的导入脚本的QML Component实例都将使用在脚本中声明的自己的全局变量副本。

例如,您可以看一下PageStack(qt-components)代码

import "PageStack.js" as Engine一条语句,后来它引用使用全局变量的调用函数,例如它是否是实例变量。

如果您正在寻找一种将成员添加到QML组件中并且不需要属性更改通知的方法,那么“脚本实例”就可以了。