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

235 篇文章 179 订阅

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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Allen Roson

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值