目录
一、计算x y z布局
1.x、y、z是相对于父物体布局;
2.默认值都为0;
3.z代表layer,具有较高值的项目绘制在具有较低顺序的同级项目的顶部。
Rectangle{
x:100
y:100
width: 200
height: 180
border.width: 1
border.color: "red"
Button{
x:0
y:0
z:0
text: "btn0"
}
Button{
x:0
y:0
z:-1
text: "btn1"
}
Button{
x:0
y:100
text:"btn2"
}
}
二、锚点布局
除了通过算x、y的值来确定元素的位置,我们还可以通过anchors来布局。
anchors.alignWhenCentered : bool
anchors.baseline : AnchorLine
anchors.baselineOffset : real
anchors.bottom : AnchorLine
anchors.bottomMargin : real
anchors.centerIn : Item
anchors.fill : Item
anchors.horizontalCenter : AnchorLine
anchors.horizontalCenterOffset : real
anchors.left : AnchorLine
anchors.leftMargin : real
anchors.margins : real
anchors.right : AnchorLine
anchors.rightMargin : real
anchors.top : AnchorLine
anchors.topMargin : real
anchors.verticalCenter : AnchorLine
anchors.verticalCenterOffset : real
- 在QML中,所有的可视化元素都继承自Item,它们对应C++中的QQuickItem类;
- 通过上述anchors group所支持的布局,我们可以看到:
- anchors.fill是基于Item(元素)填充的;
- anchors.left是基于AnchorLine布局的;
- 而当我们使用anchors.margins时,需要赋予其真实的值。
Rectangle{
color: "blue"
anchors.fill: parent //parent即window
//垂直居中 anchors.verticalCenter
Rectangle{
id:grayRect
color: "gray"
width: 100
height: 100
anchors.verticalCenter: parent.verticalCenter
}
//通过top、bottom来确定矩形的高
Rectangle{
anchors.top: parent.top
anchors.bottom: parent.bottom
anchors.left: grayRect.right
width:20
color: "purple"
}
//通过left、right确定矩形宽度
Rectangle{
anchors.bottomMargin: 100
anchors.bottom: parent.bottom
anchors.right: parent.right
anchors.left: parent.left
height:20
color: "purple"
}
//水平居中 anchors.horizontalCenter
Rectangle{
color: "orange"
width: 100
height: 100
anchors.horizontalCenter: parent.horizontalCenter
anchors.bottom: parent.bottom
}
//上下左右居中 anchors.centerIn
Rectangle{
color: "pink"
width: 100
height: 100
radius: 40
anchors.centerIn: parent
}
Rectangle{
id:yellowRect
color: "yellow"
width: 100
height: 100
anchors.right: parent.right
}
//上边距 anchors.topMargin
Button{
text:"btn"
anchors.top: yellowRect.bottom
anchors.right: parent.right
anchors.topMargin: 5
}
}