不使用alias
在使用组件的过程中在不同的使用场景中需要对组件中的某个属性进行不同的设置,比如下面的main.qml中有两个按钮,两个按钮显示的文字不同,图示如下:
两个button都是直接引用组件,那么则需要引用两个组件文件:
Button1.qml
import QtQuick 2.7
Rectangle {
width: 100; height: 30
Text { text: "button_1" }
}
Button2.qml
import QtQuick 2.7
Rectangle {
width: 100; height: 30
Text { text: "button_2" }
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.3
ApplicationWindow {
title: "Test App"
width: 300
height: 300
visible: true
Column {
anchors.centerIn: parent
spacing: 5
Button1 {}
Button2 {}
}
}
使用alias
关键字property alias将一个属性设置一个别名,属性别名是保存对另一个属性的引用的属性。与为属性分配新的唯一存储空间的普通属性定义不同,属性别名将新声明的属性(称为别名属性)连接为直接引用现有属性(别名属性)。
性别名声明类似于普通属性定义,但它需要alias关键字而不是属性类型,并且属性声明的右侧必须是有效的别名引用。
与普通属性不同,别名具有以下限制:
- 它只能引用在声明别名的类型范围内的对象或对象的属性。
- 它不能包含任意的javascript表达式
- 它不能引用其类型范围之外声明的对象。
- 与普通属性的可选默认值不同,别名引用不是可选的;首次声明别名时必须提供别名引用。
- 它不能引用附加的属性。
- 它不能引用分组属性。
将上面的两个组件文件修改为单个组件文件:
AButton.qml
import QtQuick 2.7
Rectangle {
property alias text: textItem.text
width: 100; height: 30
color: "yellow"
Text { id: textItem }
}
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.3
ApplicationWindow {
title: "Test App"
width: 300
height: 300
visible: true
Column {
anchors.centerIn: parent
spacing: 5
AButton { text: "button_1" }
AButton { text: "button_2" }
}
}
可以看到运行效果相同,代码量却能够有效减少: