• Roson的Qt之旅 #113 QML布局之StackLayout(堆栈布局)


    1.StackLayout(堆栈布局)概述

    StackLayout类提供了一个项目的堆栈,其中一次只有一个项目是可见的

    导入声明:
    import QtQuick.Layouts 1.3

    继承自:Item 


    当前可见的项目可以通过设置currentIndex属性来修改。该索引与StackLayout的子项的顺序相对应。


    与大多数其他布局相比,子项的Layout.fillWidth和Layout.fillHeight属性默认为真。因此,只要它们的Layout.maximumWidth或Layout.maximumHeight没有阻止,子项就会被默认填充到与StackLayout的大小一致。


    项目被添加到布局中,是通过将项目重新parent到布局中。同样地,移除也是通过从布局中重新parent该项目来完成的。这两种操作都会影响布局的计数属性。

    StackLayout中的项目支持这些附加属性:

    • Layout.minimumWidth(最小宽度)
    • Layout.minimumHeight(最小高度)
    • Layout.preferredWidth(首选宽度)
    • Layout.preferredHeight(首选高度)
    • Layout.maximumWidth(最大宽度)
    • Layout.maximumHeight(最大高度)
    • Layout.fillWidth(填充宽度)
    • Layout.fillHeight(填充高度)

    另请参见ColumnLayout、GridLayout、RowLayout和StackView

    2.属性介绍

    count : int
    该属性持有属于该布局的项目数量。
    只有属于StackLayout的子项才是布局的候选项。

    currentIndex : int
    该属性持有当前在StackLayout中可见的子项的索引。默认情况下,对于一个空的布局,它将是-1,否则默认为0(指的是第一个项目)。

    3.代码示例

    下面的代码将创建一个StackLayout,其中只有'plum'矩形是可见的。

    1.   StackLayout {
    2.       id: layout
    3.       anchors.fill: parent
    4.       currentIndex: 1
    5.       Rectangle {
    6.           color: 'teal'
    7.           implicitWidth: 200
    8.           implicitHeight: 200
    9.       }
    10.       Rectangle {
    11.           color: 'plum'
    12.           implicitWidth: 300
    13.           implicitHeight: 200
    14.       }
    15.   }

    由于currentIndex的值为1,所以只能看到第2个矩形,也就是color值为'plum'的矩形。

    下面的代码,通过鼠标点击,可以切换显示出来的矩形。

    1. import QtQuick 2.9
    2. import QtQuick.Window 2.2
    3. import QtQuick.Layouts 1.3
    4. Window {
    5. id: myWindow
    6. visible: true
    7. width: 640
    8. height: 480
    9. title: qsTr("Hello World")
    10. StackLayout {
    11. id: layout
    12. anchors.fill: parent
    13. currentIndex: 0
    14. Rectangle {
    15. color: 'teal'
    16. implicitWidth: 200
    17. implicitHeight: 200
    18. MouseArea{
    19. anchors.fill: parent
    20. onClicked: {
    21. layout.currentIndex = 1;
    22. }
    23. }
    24. }
    25. Rectangle {
    26. color: 'plum'
    27. implicitWidth: 300
    28. implicitHeight: 200
    29. MouseArea{
    30. anchors.fill: parent
    31. onClicked: {
    32. layout.currentIndex = 0;
    33. }
    34. }
    35. }
    36. }
    37. }


     

     可以看到,当鼠标点击时,通过修改layout.currentIndex的值,可以控制堆栈布局显示布局中的哪一个项目。

  • 相关阅读:
    前端实现界面切换主题
    软件测试3年以为的躺平了,没想到还得内卷,这题太难了...
    BEVCar:用于BEV地图和目标分割的相机-雷达融合
    python+pytest接口自动化测试之接口测试基础
    OneDrive打不开了,怎么办?使用管理员身份也无效,分享解决办法如下
    无人机运营合格证及无人机服务资质认证详解
    【Spring Boot】常用参数与注解
    图像压缩之NVJPEG
    对话ChatGPT:AIGC时代下,分布式存储的应用与前景
    服务器硬件基础知识:新手完全指南
  • 原文地址:https://blog.csdn.net/jolin678/article/details/126580818