前言

在 Qt Widget中我们经常使用水平布局或者垂直布局。在 QML 中也有对应的 RowLayout 和 ColumnLayout 提供给我们使用。它们被统称为布局管理器,QML布局管理器不仅进行布局,而且会改变项目的大小,所以更适合需要改变用户界面大小的应用。因为布局管理器也是继承自Item,所以它们可以进行嵌套

注意

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
}

这样的代码 宽度高度指的是不包含标题栏的高度如下 image.png

代码

import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
import QtQuick.Layouts 1.3

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    //在window上面在套一个Item布局起来更加方便,要布局的内容的整体边距都可以用Item来实现
    Item{
        anchors.fill: parent
        anchors.leftMargin: 10
        anchors.rightMargin: 10
        anchors.bottomMargin: 10
        ColumnLayout{
            id: columLayout
            anchors.fill: parent // 将最外层的 ColumnLayout 布满整个 窗口非常重要,这样里面的控件设置后才能跟随窗体进行变换
            spacing: 10 //每个RowLayout之间的间距是 10
            RowLayout{
                id: rowLayout
                Rectangle{
                    Layout.preferredWidth: 620
                    Layout.fillWidth: true
                    Layout.preferredHeight: 210
                    Layout.fillHeight: true
                    border.color: "black"
                    border.width: 1
                    color: "blue"
                    Text{
                        anchors.centerIn: parent
                        color: "white"
                        text: parent.width + "x" + parent.height
                    }
                }
            }
            RowLayout{
                id: rowLayout_1
                Rectangle{
                    Layout.preferredWidth: 620
                    Layout.fillWidth: true
                    Layout.preferredHeight: 210
                    Layout.fillHeight: true
                    border.color: "black"
                    border.width: 1
                    color: "pink"
                    Text{
                        anchors.centerIn: parent
                        color: "white"
                        text: parent.width + "x" + parent.height
                    }
                }
            }
            RowLayout{
                id: rowLayout_2
                spacing: 10
                Rectangle{
                    //不想要改变高度 不设置 Layout.fillHeight 即可
                    Layout.preferredHeight: 30
                    Layout.preferredWidth: 570
                    Layout.fillWidth: true
                    border.color: "black"
                    border.width: 1
                    TextEdit{
                        id: textEdit
                        anchors.fill: parent
                    }
                }
                Button{
                    //在布局中不想要这个控件改变大小 不设置 Layout.fillWidth 或者 Layout.fillHeight 即可
                    Layout.preferredHeight: 30
                    Layout.preferredWidth: 40
                    text: "按钮"
                }
            }
        }
    }
}

效果展示

3.gif