Qt Quick 04|QML 四大布局:Row、Column、Grid、Anchor 锚点布局
正文QML 放弃固定坐标定位提供四类主流布局实现界面自适应窗口缩放自动适配。一、Column 列布局垂直排列自上而下子元素垂直排布对应 QWidget 的QVBoxLayout。qmlColumn { anchors.centerIn: parent spacing: 8 // 元素之间间距 Button { text: 按钮1; width: 100 } Button { text: 按钮2; width: 100 } Button { text: 按钮3; width: 100 } }二、Row 行布局水平排列从左到右子元素水平排布对应 QWidget 的QHBoxLayout。qmlRow { anchors.top: parent.top anchors.left: parent.left spacing: 10 Text { text: 账号 } TextField { width: 120 } }三、Grid 网格布局多行多列表格排布适合表单、九宫格布局对应 QWidget 的QGridLayout。核心属性columns指定列数。qmlGrid { anchors.centerIn: parent columns: 2 // 固定2列 spacing: 15 Text { text: 姓名 } TextField { width: 120 } Text { text: 年龄 } TextField { width: 120 } }四、Anchor 锚点布局QML 最强布局万能定位锚点是 QML 特有布局方式通过上下左右、居中、边距描述元素相对位置灵活度最高。1. 基础锚点用法qmlRectangle { width: 300 height: 200 color: #f5f5f5 // 子元素水平居中、垂直居中 Rectangle { width: 100 height: 60 color: lightblue anchors.centerIn: parent } }2. 单侧锚点 边距qmlRectangle { // 贴父容器左侧、顶部距离边距20px anchors.left: parent.left anchors.top: parent.top anchors.leftMargin: 20 anchors.topMargin: 20 }3. 左右拉伸填满父容器qmlRectangle { anchors.left: parent.left anchors.right: parent.right anchors.top: parent.top height: 40 }五、布局选型建议简单水平排列 →Row简单垂直排列 →Column表单、九宫格 →Grid复杂不规则界面、精准相对定位 →Anchor 锚点首选小结Row/Column/Grid 上手简单适合规整界面Anchor 灵活强大是 QML 布局的核心复杂界面优先使用锚点。