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

  • 相关阅读:
    北斗导航 | GNSS观测模型(公式推导)
    多子群改进的海洋捕食者算法-附代码
    跨模态神经搜索实践VCED Jina入门
    当苹果铅笔不能工作时,不一定都是苹果铅笔的问题!苹果铅笔不工作时如何修复
    NPDP产品经理证书是什么行业的证书?
    大数据:Flume安装部署和配置
    疫情物资储藏库建设规划问题,使用matlab+cplex+yalmib求解
    ImportError: cannot import name ‘TouchActions‘ from ‘selenium.webdriver‘
    在更一般意义上验算移位距离和假设
    APP备案公钥、证书MD5指纹/签名MD5值获取方法
  • 原文地址:https://blog.csdn.net/jolin678/article/details/126580818