Qt Quick 响应式布局

布局是制作可调整大小的用户界面的好方法。然而,这种方法也有其局限性,因为我们无法在不影响可用性和美观的情况下无限缩小和扩展项目。在某些时候,重组、移除或添加某些元素更有意义。适应不同设备(如手机和桌子)和屏幕方向(横向或纵向)的方法也是类似的。这就是我们通常理解的响应式布局,Qt Quick Layouts提供了各种应用程序接口来实现它们。

静态层次结构,自适应布局

布局有一个层次结构,通常由声明式 QML 代码定义。对于一些简单的响应式布局,只需保持层次结构不变,而只需调整一些影响布局的属性即可。

声明式描述

改变布局的最简单方法是用小表达式修改布局属性和Layout 附加属性。例如,您可以使用三元运算符来根据宽度修改布局。Item 属性,如Item.visible 、隐藏或显示界面的各个部分,也可以用同样的方法修改。

在下面的代码段中,如果窗口宽度小于某个值,就可以使用这一概念将双栏布局改为单栏布局。

GridLayout {
    columns: width < 300 ? 1 : 2
    anchors.fill: parent

    Rectangle {
        id: rectangle1
        color: "tomato"
        Layout.fillHeight: true
        Layout.fillWidth: true
    }

    Rectangle {
        id: rectangle2
        color: "lightskyblue"
        Layout.fillHeight: true
        Layout.fillWidth: true
    }
}

根据窗口的宽度,最终的布局如下所示。

不同层次的布局和项目可以嵌套,但Items 只能在其Item.parent 内移动。

状态

使用Qt Quick 状态可以达到同样的效果。使用状态的好处是,特定布局的Layout 属性都收集在 QML 文件的一个点上(至少是变化的属性)。前面显示的示例可按如下方式实现,结果看起来和表现完全一样。

GridLayout {
    anchors.fill: parent

    Rectangle {
        id: rectangle1
        color: "tomato"
        Layout.fillHeight: true
        Layout.fillWidth: true
    }

    Rectangle {
        id: rectangle2
        color: "lightskyblue"
        Layout.fillHeight: true
        Layout.fillWidth: true
    }

    states: [
        State {
            when: width < 300
            PropertyChanges { target: rectangle2; Layout.row: 1 }
            PropertyChanges { target: rectangle2; Layout.column: 0 }
        },
        State {
            when: width >= 300
            PropertyChanges { target: rectangle2; Layout.row: 0 }
            PropertyChanges { target: rectangle2; Layout.column: 1 }
        }
    ]
}

布局项目代理

第三种方法是应用LayoutItemProxy 。前面展示的简约示例的实现可以在类型文档中找到。与之前展示的解决方案不同的是,LayoutItemProxy 可以为不同的外形尺寸声明完全独立的布局。特别是在布局比较复杂的情况下,这可能有助于改进和维护合理的源代码结构。

请注意,LayoutItemProxy API 只是一个技术预览版,在未来的 Qt 版本中可能会更改或删除。

自适应层次结构、自适应布局

更复杂的布局重构可能需要更改层次结构。一个小布局中的独立小按钮可能会与其他按钮组合在一起,并放入一个大布局的方框中。在一个布局中完全可见的项目,在另一个较小的布局中可能需要Flickable 。在这种情况下,最好使用LayoutItemProxy 。通过LayoutItemProxy ,可以在不同层次和不同Item.parent 之间移动Items

Qt Quick 布局--响应式布局示例显示了在不同层次之间移动项目的情况,在一种情况下,项目被放入Flickable ,而在另一种布局中,项目被放在顶层。两个布局的结果如下。

许多设计指南都为创建响应式布局提供了帮助和技巧。使用上述应用程序接口可以实现相应的技术。如需了解更多信息,我们推荐使用以下链接:

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.