QML对象属性
每个QML对象类型都有一些属性。当创建对象类型的实例时,这些属性就会被自动创建出来。您甚至可以定义一些自己的属性。除枚举属性外,所有属性都以小写字母或下划线开头,并且不能包含字母,数字和下划线以外的字符。
id属性
每个QML对象类型有且仅有一个id
属性,它由QML语言默认提供,用于标识和引用该对象。
import QtQuick Column { width: 200; height: 200 TextInput { id: myTextInput; text: "Hello World" } Text { text: myTextInput.text } }
上面的代码中,定义了TextInput
对象的id
属性值为"myTextInput"。这样就可以在Text
对象里通过"myTextInput"来引用TextInput
对象的属性值。
property
属性
property
属性是用于分配静态值或绑定到动态表达式的对象属性。在QML中定义property
属性语法如下:
[default] [required] [readonly] property <propertyType> <propertyName>
其中default
,required
和readonly
是可选关键字。
定义property
属性
以下示例定义了几种property
属性:
Item { property int someNumber property string someString property url someUrl property Item someItem property Rectangle someRectangle property var someVal property var someList: [1, 2, "three", "four"] property color nextColor onNextColorChanged: console.log("The next color will be: " + nextColor.toString()) }
除枚举类型外,属性类型支持其他所有的基本类型(枚举类型可以用int
替代)。另外,属性类型还可以是QML对象类型,如Item
,Rectangle
等,甚至可以是自定义的QML对象类型。var
用于类型占位符,可以保存任何类型的值。
定义property
属性时,QML会自动创建一个与该属性关联的信号处理程序。命名规则为on<PropertyName>Changed
,其中<PropertyName>
是属性的名称,首字母变为大写。如上面示例中的nextColor
属性和onNextColorChanged
信号处理程序。
property
属性赋值
属性赋值有两种方式:
- 初始化时赋值,语法
<propertyName> : <value>
。
import QtQuick Rectangle { color: "red" // 初始化时赋值 property color nextColor: "blue" // 属性声明同时进行初始化 }
- 使用赋值运算符赋值,语法
[<objectId>.]<propertyName> = value
。
import QtQuick Re