栈式布局管理器(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()
{
}