1. 元素的位置描述
一个元素的位置可以通过设定x
与y
的属性值来确定。
import QtQuick 2.0
Item {
width: 400
height: 320
Rectangle {
x: 100
y: 50
width: height*2
height: 100
color: "lightblue"
}
Rectangle {
x: 100
y: 170
width: height*2
height: 100
color: "yellow"
}
}
上述的代码描述了两个矩形,x
与y
的值是相对于其父元素的左上角而言的。
拓展:子元素可以显示在父元素之外吗?
可以,如以下案例,子元素的x为负值。
Window {
visible: true
width: big_rectangle.width + 60
height: big_rectangle.height + 60
title: qsTr("Hello World")
color: "gray"
Rectangle {
id: big_rectangle
x: 30
y: x
width: 400
height: width
color: "green"
Rectangle {
x: -20
y: big_rectangle.y + big_rectangle.height * 4 / 6
width: big_rectangle.width / 2
height: big_rectangle.height / 6
color: "blue"
}
}
}
但是也可以通过属性来规定不可在父元素之外显示。具体的属性为clip:true
(在父元素中声明):
Window {
visible: true
width: big_rectangle.width + 60
height: big_rectangle.height + 60
title: qsTr("Hello World")
color: "gray"
Rectangle {
id: big_rectangle
clip: true
x: 30
y: x
width: 400
height: width
color: "green"
Rectangle {
x: -20
y: big_rectangle.y + big_rectangle.height * 4 / 6
width: big_rectangle.width / 2
height: big_rectangle.height / 6
color: "blue"
}
}
}
2. 元素的重叠关系
默认后解析的元素(即在代码中靠后的元素)会覆盖之前的元素(如果它们在平面上重叠的话)
如下图的代码所示,黄色矩形会和青色矩形重叠,由于描述黄色矩形的代码在后,所以黄色矩形会覆盖青色矩形。
import QtQuick 2.0
Item {
width: 400
height: 320
Rectangle {
x: 100
y: 50
width: height*2
height: 100
color: "lightblue"
}
Rectangle {
x: 100
y: 120
z: 0
width: height*2
height: 100
color: "yellow"
}
}
但是除了可以用代码的先后次序来控制重叠关系,还可以引入z
属性来指定这种重叠关系。默认的z
值为0,z
值越小就在越底层。
0与-1:
import QtQuick 2.0
Item {
width: 400
height: 320
Rectangle {
x: 100
y: 50
width: height*2
height: 100
color: "lightblue"
}
Rectangle {
x: 100
y: 120
z: -1
width: height*2
height: 100
color: "yellow"
}
}
0与1:
import QtQuick 2.0
Item {
width: 400
height: 320
Rectangle {
x: 100
y: 50
width: height*2
height: 100
color: "lightblue"
}
Rectangle {
x: 100
y: 120
z: 1
width: height*2
height: 100
color: "yellow"
}
}
3. .qmlproject
工程
除了与c++
代码一起创建工程以外(.pro
来管理工程),还可以单独生成Qt Quick UI工程,可以在other Project
中选择Qt Quick UI Project
来创建。
此时可以在QT中Run
和Debug
了。
tips:
.qmlproject
和.pro
可以共存。
4. 快速查看帮助文件(F1)
在我们使用Qt Creator
来编辑qml
时,可以按F1快速在侧边打开帮助页面,可以很方便地查看元素有哪些属性。