Qt Quick与QML系列文章目录
第一章 qml中使用anchors布局及问题排查
文章目录
一、Anchors简单介绍
Anchors也就是锚点布局,通过将Item的一个或多个锚点(边界)附着到另一个Item的锚点,锚点布局允许将一个Item放置在另一个Item的附近或内部。即使其中一个Item的尺寸或位置发生变化,这些锚点也将保留,从而实现高度动态的用户界面。
QML中的视觉对象可以被认为天生具有各种锚点(或者更准确地说,锚线)。其他Item可以锚定到这些点,这意味着随着任何对象的更改,锚定到该点的其他Item将自动调整以保持锚定。
简单说就是,将自身的尺寸属性与自身父亲元素或者兄弟元素关联起来。
Anchors使用举例
import QtQuick 2.14
import QtQuick.Window 2.14
import QtQuick.Controls 2.14
Window {
id: window
visible: true
width: 100
height: 50
Rectangle {
id: rect1;
color: "red";
width:20;
height:20
}
Rectangle {
id: rect2;
color: "blue";
width:20;
height:20
anchors.left: rect1.right;
}
}
上述代码,效果如下:
二、锚点布局问题
之前,调研过一个项目Demo,在Item中使用锚点布局总是达不到UI设计的效果,大致的代码如下:
Item {
id: batteryItem
anchors.left: parent.left
Image {
id: batteryStatus
source: "qrc:/image/Battery50.png"
width: 39
height: 28
anchors.left: parent.left
}
Text {
id: batteryValue
text: "72%"
width: 72
height: 42
// content
font.pixelSize: 40
color: "#25292f"
anchors.left: batteryStatus.right
anchors.right: parent.right
}
}
上述代码,预期是为了实现一个显示电池电量的Item,UI设计效果如下:
上述代码中,使用1个Item(batteryItem)作为容器,预期将1个Image(batteryStatus)和1个Text(batteryValue)通过锚点布局组合在一起以达到上述UI设计效果。之后,再加上一个跟batteryItem为兄弟关系的Text,同样通过锚点布局在batteryItem右侧,新增那个代码与代码预期结果如下:
Text {
id: avgItem
width:148
text: "235km"
// content
font.pixelSize: 40
color: "#25292f"
anchors.left: batteryItem.right
}
但实际效果如下:
三、锚点布局问题分析与结论
在我的预期中,batteryItem中2个子元素分别设置了明确的width属性值,按照代码中布局,2个子Item在水平方向完全填充父Item,batteryItem也就不需要明确指定width属性值。然后avgItem通过锚点布局到batteryItem右侧,也就是顺其自然的结果,但实际效果与预期效果明显不相符。
后来通过反复测试和查帮助文档,确定了问题原因,即batteryItem没有明确设置width属性值,而与batteryItem是兄弟关系的avgItem通过锚点布局时,avgItem是不清楚batteryItem的尺寸的(avgItem无法识别到batteryItem中的子元素以及子元素的width属性值),那么batteryItem与avgItem重叠也就是必然的结果了。
四、问题解决办法
之前忘记写解决办法了,这里补充一下。
这个问题比较好的解决办法就是:batteryItem明确设置width属性值(子Item都设置了width值,父Item设置width也不多余),最终的代码如下:
Item {
id: batteryItem
anchors.left: parent.left
width:117
Image {
id: batteryStatus
source: "qrc:/image/Battery50.png"
width: 39
height: 28
anchors.left: parent.left
}
Text {
id: batteryValue
text: "72%"
width: 72
height: 42
// content
font.pixelSize: 40
color: "#25292f"
anchors.left: batteryStatus.right
anchors.right: parent.right
}
}
Text {
id: avgItem
width:148
text: "235km"
// content
font.pixelSize: 40
color: "#25292f"
anchors.left: batteryItem.right
}
最终效果如下图:
ps:上述最终效果图中,没有做水平居中对齐,所以表现为电池图片跟文字内容错位了