欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > QML布局

QML布局

2025/4/15 9:15:34 来源:https://blog.csdn.net/byxdaz/article/details/147063531  浏览:    关键词:QML布局

一、‌锚点布局(Anchors)

  1.  通过定义元素与其他元素或父容器的锚点关系实现定位,支持动态调整和边距控制‌。

    Rectangle {anchors.left: parent.left   // 左对齐父容器anchors.top: parent.top     // 顶部对齐父容器anchors.margins: 10        // 统一设置四周边距width: 100; height: 50
    }
    
    • 关键属性‌:anchors.leftanchors.rightanchors.fill(填充父容器)、anchors.centerIn(居中)‌。
    • 边距控制‌:anchors.margins(统一边距)或单独设置anchors.leftMargin等‌。

二、水平布局(Row)

Row定位器将子元素水平排列。你可以通过spacing属性来设置子元素之间的间距。主要属性:

基本属性

属性类型默认值描述
spacingreal0子元素之间的间距(像素)
layoutDirectionenumerationQt.LeftToRight布局方向(LeftToRight/RightToLeft)
addTransition-添加子项时应用的过渡动画
moveTransition-移动子项时应用的过渡动画
populateTransition-初始创建子项时应用的过渡动画

对齐属性

属性类型默认值描述
topPaddingreal0顶部内边距
bottomPaddingreal0底部内边距
leftPaddingreal0左侧内边距
rightPaddingreal0右侧内边距
paddingreal0统一设置所有内边距
verticalAlignmentenumerationRow.AlignTop垂直对齐方式(AlignTop/AlignVCenter/AlignBottom)
horizontalAlignmentenumerationRow.AlignLeft水平对齐方式(AlignLeft/AlignHCenter/AlignRight)

布局控制属性

属性类型默认值描述
widthreal隐含宽度行宽度(若未设置则为子项总宽度)
heightreal隐含高度行高度(若未设置则为最高子项高度)
clipboolfalse是否裁剪超出边界的内容

枚举值说明

layoutDirection:

  • Qt.LeftToRight - 从左到右排列(默认)

  • Qt.RightToLeft - 从右到左排列

verticalAlignment:

  • Row.AlignTop - 顶部对齐

  • Row.AlignVCenter - 垂直居中

  • Row.AlignBottom - 底部对齐

horizontalAlignment:

  • Row.AlignLeft - 左对齐

  • Row.AlignHCenter - 水平居中

  • Row.AlignRight - 右对齐

 示例代码:

    Row {spacing: 10Rectangle { width: 100; height: 50; color: "red" }Rectangle { width: 100; height: 50; color: "green" }Rectangle { width: 100; height: 50; color: "blue" }}

Row 是创建水平排列布局的基础组件,适合简单的水平排列需求,对于更复杂的响应式布局,建议使用 RowLayout 或 GridLayout

三、RowLayout

RowLayout 是 Qt Quick Layouts 模块提供的布局组件,用于创建灵活的水平布局。相比基础的 Row,它提供了更强大的布局控制能力。

基本用法

qml

import QtQuick 2.15
import QtQuick.Layouts 1.15RowLayout {id: layoutanchors.fill: parentspacing: 10  // 子项之间的间距Rectangle {color: "red"Layout.preferredWidth: 100Layout.fillHeight: true}Rectangle {color: "green"Layout.fillWidth: true  // 填充可用宽度Layout.minimumWidth: 50Layout.maximumWidth: 200}Rectangle {color: "blue"Layout.preferredWidth: 150Layout.preferredHeight: 80}
}

主要特性

RowLayout 容器属性

属性类型默认值说明
spacingreal5子项之间的统一间距(像素)
layoutDirectionenumQt.LeftToRight排列方向(Qt.LeftToRight 或 Qt.RightToLeft
enabledbooltrue是否启用布局(禁用时子项不可见/不响应)

子项布局属性(需在子元素内使用)

1. 尺寸控制
<
属性类型说明
Layout.fillWidthbool是否水平填充剩余空间
Layout.fillHeightbool是否垂直填充剩余空间
Layout.preferredWidthreal首选宽度(优先级高于隐式宽度)
Layout.preferredHeightreal首选高度
Layout.minimumWidthreal最小宽度限制

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词