QML嵌套ColumnLayout与RowLayout时无法将绿色矩形定位到右侧
QML布局问题:ColumnLayout嵌套RowLayout时将元素定位到右侧
要让绿色矩形靠右,核心是让RowLayout内部的剩余空间被占位元素填充,这样Layout.alignment: Qt.AlignRight才能生效。修改后的代码如下:
import QtQuick 2.9 import QtQuick.Window 2.2 import QtQuick.Layouts 1.3 Window { visible: true width: 800 height: 480 title: qsTr("Hello World") ColumnLayout{ anchors.fill: parent spacing: 10 RowLayout{ Layout.fillWidth: true Layout.fillHeight: true Rectangle{ width: 50 height: 50 color: "orange" } Rectangle{ width: 50 height: 50 color: "blue" } // 添加占位元素,填充剩余宽度 Item { Layout.fillWidth: true } Rectangle{ width: 50 height: 50 color: "green" Layout.alignment: Qt.AlignVCenter | Qt.AlignRight } } RowLayout { Rectangle{ width: 370 height: 800 color: "cyan" } Rectangle{ width: 370 height: 800 color: "pink" } } } }
关键修改说明
- 在蓝色矩形和绿色矩形之间添加一个
Item,设置Layout.fillWidth: true,它会占据RowLayout中橙色、蓝色矩形之外的所有剩余宽度,从而把绿色矩形推到右侧。 - 你的代码中已经给RowLayout设置了
Layout.fillWidth: true,这是让RowLayout填满父容器宽度的前提,必须保留。
内容的提问来源于stack exchange,提问作者user19012733
相关产品推荐
相关产品推荐

