对象
import QtQuick 2.2
Rectangle {
width: 320; // 属性初始化
height: 480;
Image {
source: "images/IMG_001.jpg";
anchors.centerIn: parent;
}
}
引入模块:import QtQuick 2.2 (引入 QtQuick2.2 模块)。
定义对象:对象要用一对花括号来描述, 花括号前要写上对象的类型名字(类名)。Rectangle {}语句, 定义了一个类型为 Rectangle 的对象。
属性初始化:在花括号之间,是对象的属性初始化语句,形如 “ property: value “。
- 分行书写
Rectangle {
width: 320; // 分号可以省略(建议C++程序员都加上)
height: 480;
}
- 写在一行
Rectangle {
width: 320; height: 480; color: "#121212"; // 分号不可省略(不建议这种写法)
}
表达式
QML支持ECMAScript表达式。
Button {
text: "Quit";
style: ButtonStyle {
background: Rectangle { // 指定一个Rectangle作为按钮的背景
implicitWidth :70;
implicitHeight: 25;
border.width: control.activeFocus ? 2 : 1; // 使用ECMAScript的三元运算符
}
}
}
通过对象的id值来引用一个对象。
Rectangle {
width: 320;
height: 480;
Button {
id: openFile;
text: "打开";
anchors.left: parent.left;
anchors.leftMargin: 6;
anchors.top: parent.top;
anchors.topMargin: 6;
}
Button {
id: quit;
text: "退出";
anchors.left: openFile.right; // 设置当前button在另一个button的右边
anchors.leftMargin: 4;
anchors.bottom: openFile.bottom;
}
}
注释
在QML中,注释与C++一样,单行以“/”开始,多行以“/*”开始、以“*/”结束。
属性
属性命名
属性名的首字母一般以小写字母开始,使用驼峰命名法。比如Rectangle从Item继承而来的属性implicitWidth。
属性类型
可以在 QML 文档中使用的类型大概有三类:
- 由QML 语言本身提供的基本类型
- 由 QML 模块(比如 Qt Quick )提供的类型
- 导出到 QML 环境中的 C++类型
(1)基本类型
QML 支持的基本类型包括 int、 real、 double、 bool、 string、 color、 list、 font 等。
Rectangle {
width: 320; // int
height: 480;
Button {
id: quit;
text: "退出"; // string
anchors.left: openFile.right;
anchors.leftMargin: 4;
anchors.bottom: openFile.bottom;
z: 1.5; // real
visible: false; // bool
}
}
值得注意的是,QML中对象的属性是有类型安全检测的,也就是说,如果值与属性类型不匹配,会报错。
(2)id属性
一个对象的id属性是唯一的。在同一个QML文件中不同对象的id属性的值不能重复。另外,id属性的值,首字符必须是小写字母或下画线,并且不能包含字母、数字、下画线以外的字符。
(2)列表属性
QML 对象的列表属性(类型是list)类似于:
Item {
children: [
Image{},
Text{}
]
}