var QML Value Type
一个通用属性类型。更多...
详细描述
var 类型是一种泛型属性类型,可以引用任何数据类型。
它等同于普通的 JavaScript 变量。例如,`var properties` 可以存储数字、字符串、对象、数组和函数:
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 对象的常规属性发生变化时,并不会触发访问该属性的绑定的更新。下面的示例将显示“这辆车有 4 个车轮”,因为 `wheels` 属性的变化不会导致分配给 `"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})" `,则文本将更新为“这辆车有 6 个轮子”,因为 `car` 属性本身发生了变化,从而触发了变更通知。
属性值初始化语义
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 属性绑定到一个空表达式,其结果为 undefined。而second 属性绑定到一个包含单个空表达式块("{}")的表达式,其结果同样为 undefined。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 值类型。
© 2026 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.