QML中Rectangle的anchors.horizontalCenter失效问题求助
解决按钮水平居中问题
你的问题出在RowLayout的锚点设置上:
- 给RowLayout添加
anchors.fill: parent会让布局容器占满整个footer的宽度,而RowLayout默认子项左对齐,所以按钮都挤在左侧。 - 此时
anchors.horizontalCenter: parent.horizontalCenter不会生效,因为容器已经占满父组件宽度。
修改方案
把Footer.qml里的RowLayout设置调整为:
RowLayout{ anchors.top: parent.top anchors.bottom: parent.bottom anchors.horizontalCenter: parent.horizontalCenter spacing: 10 // 可选,设置按钮间的间距,提升美观度 FooterButton{ p_identity: "FB1"; height: p_buttonHeight; width: p_buttonWidth; color: p_buttonColor } FooterButton{ p_identity: "FB2"; height: p_buttonHeight; width: p_buttonWidth; color: p_buttonColor } FooterButton{ p_identity: "FB3"; height: p_buttonHeight; width: p_buttonWidth; color: p_buttonColor } FooterButton{ p_identity: "FB4"; height: p_buttonHeight; width: p_buttonWidth; color: p_buttonColor } FooterButton{ p_identity: "FB5"; height: p_buttonHeight; width: p_buttonWidth; color: p_buttonColor } }
额外优化
FooterButton里的anchors { top: parent.top; topMargin: 10; }会让按钮在布局内顶部偏移10px,若想让按钮在footer中垂直居中,可以把FooterButton的锚点改为:
anchors.centerIn: parent
这样按钮会在RowLayout的单元格内垂直居中,配合RowLayout的上下锚点,整个按钮组就能在footer中实现水平+垂直双居中。
内容的提问来源于stack exchange,提问作者user2377283
相关产品推荐
相关产品推荐

