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

发布于:2023-01-04 ⋅ 阅读:(300) ⋅ 点赞:(0)

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'矩形是可见的。

  StackLayout {
      id: layout
      anchors.fill: parent
      currentIndex: 1
      Rectangle {
          color: 'teal'
          implicitWidth: 200
          implicitHeight: 200
      }
      Rectangle {
          color: 'plum'
          implicitWidth: 300
          implicitHeight: 200
      }
  }

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

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

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

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


    StackLayout {
        id: layout
        anchors.fill: parent
        currentIndex: 0
        Rectangle {
            color: 'teal'
            implicitWidth: 200
            implicitHeight: 200
            MouseArea{
                anchors.fill: parent
                onClicked: {
                    layout.currentIndex = 1;
                }
            }
        }
        Rectangle {
            color: 'plum'
            implicitWidth: 300
            implicitHeight: 200

            MouseArea{
                anchors.fill: parent
                onClicked: {
                    layout.currentIndex = 0;
                }
            }
        }
    }
}


 

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


网站公告

今日签到

点亮在社区的每一天
去签到