我想动态地向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;
*/
}
}
有没有办法完成上述任务。
答案 0 :(得分:6)
一方面:我不明白,为什么有人会想这样做,因为它完全不是声明性的。但是,由于QML扩展了JavaScript,而后者是原型语言,是的,你可以来做。
关于操作方法,我建议阅读how to define properties上的JS文档。但是我写了一个简短的例子来证明它的使用。
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'
})}
}
}
首次点击背景时,' undefined'将被打印。点击矩形后,这将变为' 50'。
答案 1 :(得分:4)
我不认为QML旨在支持动态属性创建。
根据您的用例,可以使用“脚本实例”(我编写术语)。基本上每个导入没有.pragma library
语句的脚本的QML组件实例都可以使用脚本中声明的自己的全局变量副本。
例如,您可以查看PageStack(qt-components)code。
有import "PageStack.js" as Engine
语句,后来引用了使用全局变量的调用函数,如果它是实例变量。
如果您正在寻找一种向QML组件添加成员并且不需要更改属性通知的方法,那么“脚本实例”就可以了。
答案 2 :(得分:0)
可能你可以这样做:
Item {
id: dynamicProperty;
property int first;
property var extraData;
Component.onCompleted: {
/* once this block of code is executed, i want to add
property int second; property bool third; property variant fourth;
*/
var data;
data["second"] = 0;
data["third"] = false;
...
extraData = data;
}
}
答案 3 :(得分:-2)
我不确定是否可以向qml对象添加动态属性,购买一个最简单的表单是禁用,隐藏或更改属性,例如:
if(manual==true)
{
icon.visible=true
}
else {
icon.visible=false
}
或者您可以创建项目的动态组件或使用loader元素更改视图。