第25课 布局管理器(四)

栈式布局管理器(QStackedLayout

-- 所有组件在垂直于屏幕的方向上被管理;

-- 每次只有一个组件会显示在屏幕上;

-- 只有最顶层的组件会被最终显示;

特点:

-- 组件大小一致且充满父组件的显示区;

-- 不能直接嵌套其他布局管理器;

-- 能自由切换需要显示的组件;

-- 每次能且仅能显示一个组件;

QTimer 这个类是 Qt 中的计时器组件;

QTimer  能够在指定的时间间隔触发消息;

#include "Widget.h"
#include <QStackedLayout>  //栈式布局管理器
#include <QHBoxLayout>     //水平布局管理器
#include <QtCore>  //计时器
#include <QDebug>  //打印

Widget::Widget(QWidget *parent) : QWidget(parent),
    TestBtn1(this), TestBtn2(this), TestBtn3(this), TestBtn4(this)
{
    initControl();
}

void Widget::initControl()
{
    QStackedLayout* sLayout = new QStackedLayout();   //创建栈式布局管理器的对象
    QHBoxLayout* hLayout = new QHBoxLayout();          //创建水平布局管理器的对象
    QWidget* widget = new QWidget();    //创建组件对象
    QTimer* timer = new QTimer(this);   //生成一个计时器对象

    TestBtn1.setText("1st Button");  //sLayout->setCurrentIndex(0);   //初始显示第1个按钮
    TestBtn2.setText("2rd Button");
    TestBtn3.setText("3th Button");
    TestBtn4.setText("Test Button 4: D.T.Software");

    TestBtn2.setParent(widget);   //改变第2、3个按钮的父组件
    TestBtn3.setParent(widget);

    hLayout->addWidget(&TestBtn2);  //将按钮加入布局管理器
    hLayout->addWidget(&TestBtn3);

    widget->setLayout(hLayout);     //将水平布局管理器设置到widget组件上去

    sLayout->addWidget(&TestBtn1); // 0   //将按钮加入布局管理器
    sLayout->addWidget(widget);    // 1   //需要显示下标为1的组件
    sLayout->addWidget(&TestBtn4); // 2

    sLayout->setCurrentIndex(0);   //初始显示第1个按钮

    setLayout(sLayout);   //将布局管理器设置到窗口

    connect(timer, SIGNAL(timeout()), this, SLOT(timerTimeout()));  //通过信号与槽的机制,调用timeout()成员函数,连接计时器消息与消息处理函数

    timer->start(2000);  //每个多长时间触发一次消息,处理一次函数
}

void Widget::timerTimeout()
{
    QStackedLayout* sLayout = dynamic_cast<QStackedLayout*>(layout());  //调用layout()成员函数,获取栈式布局管理器的对象

    if( sLayout != NULL )  //强制类型转换成功
    {
        int index = (sLayout->currentIndex() + 1) % sLayout->count(); //循环在屏幕前显示,

        sLayout->setCurrentIndex(index);
    }
}

Widget::~Widget()
{

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值