• 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的值,可以控制堆栈布局显示布局中的哪一个项目。

  • 相关阅读:
    Visual Studio 调试时加载符号慢
    Java ArrayList类详解
    我要写整个中文互联网界最牛逼的JVM系列教程 | 「类加载子系统」章节:几种类加载器的使用体会
    06.封装为组件库
    SpringBoot的自动配置
    从上升边和带宽关系的两种公式说起
    【深度学习】UniControl 一个统一的扩散模型用于可控的野外视觉生成
    【论文解析】笔触渲染生成 前沿工作梳理
    Java继承 学习资料
    VR数字政务为我们带来了哪些便捷之处?
  • 原文地址:https://blog.csdn.net/jolin678/article/details/126580818