我想动态地向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)
有没有办法完成上述任务.
一方面:我没有看到,为什么有人会想这样做,因为它完全不是声明性的.但是,由于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".