var QML Value Type
通用属性类型。更多
详细说明
var
类型是一种通用属性类型,可以引用任何数据类型。
它相当于普通的 JavaScript 变量。例如,var 属性可以存储数字、字符串、对象、数组和函数:
Item { property var aNumber: 100 property var aBool: false property var aString: "Hello world!" property var anotherString: String("#FF008800") property var aColor: Qt.rgba(0.2, 0.3, 0.4, 0.5) property var aRect: Qt.rect(10, 10, 10, 10) property var aPoint: Qt.point(10, 10) property var aSize: Qt.size(10, 10) property var aVector3d: Qt.vector3d(100, 100, 100) property var anArray: [1, 2, 3, "four", "five", (function() { return "six"; })] property var anObject: { "foo": 10, "bar": 20 } property var aFunction: (function() { return "one"; }) }
更改通知语义
需要注意的是,分配给 var 属性的 JavaScript 对象的常规属性发生变化时,不会触发访问这些属性的绑定的更新。下面的示例将显示 "The car has 4 wheels"(汽车有 4 个轮子),因为轮子属性的变化不会导致重新评估分配给 "text "属性的绑定:
Item { property var car: new Object({wheels: 4}) Text { text: "The car has " + car.wheels + " wheels"; } Component.onCompleted: { car.wheels = 6; } }
如果在 onCompleted 处理程序中使用"car = new Object({wheels: 6})"
,那么文本就会更新为 "The car has 6 wheels",因为汽车属性本身会发生变化,从而导致变更通知的发出。
属性值初始化语义
QML 语法规定,属性值初始化赋值右侧的大括号表示绑定赋值。这在初始化var
属性时可能会引起混淆,因为 JavaScript 中空的大括号既可表示表达式块,也可表示空对象声明。如果希望将var
属性初始化为空对象值,则应将大括号包在括号内。
var
类型的属性默认为undefined
。
例如
Item { property var first: {} // nothing = undefined property var second: {{}} // empty expression block = undefined property var third: ({}) // empty object }
在前面的示例中,first
属性绑定到一个空表达式,其结果是未定义的。second
属性绑定到一个表达式,该表达式包含一个单独的空表达式块("{}"),其结果同样是未定义的。third
属性绑定到一个表达式上,该表达式的评估结果是一个空对象声明,因此该属性将以该空对象值初始化。
同样,JavaScript 中的冒号既可以是对象属性值赋值,也可以是代码标签。因此,用对象声明初始化 var 属性也需要括号:
Item { property var first: { example: 'true' } // example is interpreted as a label property var second: ({ example: 'true' }) // example is interpreted as a property property var third: { 'example': 'true' } // example is interpreted as a property Component.onCompleted: { console.log(first.example) // prints 'undefined', as "first" was assigned a string console.log(second.example) // prints 'true' console.log(third.example) // prints 'true' } }
另请参阅 QML 值类型。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.