
Qt 25 布局管理器4 - 栈式布局管理器QStackedLayout,QTimer计时器
发布日期:2021-05-07 13:26:12
浏览次数:29
分类:精选文章
本文共 2071 字,大约阅读时间需要 6 分钟。
QStackedLayout是Qt中常用的栈式布局管理器,广泛应用于嵌入式设备和桌面系统的布局管理。其核心特性为支持多个组件以栈式方式显示,通过切换下标来改变当前显示的组件。
栈式布局管理器的基本操作
- addWidget():用于向栈式布局管理器添加需要管理的组件。
- currentWidget():返回当前显示在屏幕上的组件,即获取栈式布局管理器最顶层的组件。
- setCurrentIndex():通过组件下标设置当前应显示的组件。
- currentIndex():获取当前显示的组件下标。
实验与实现
本文通过Widget类的实现展示了QStackedLayout的应用场景。Widget类通过继承QWidget并嵌套多个布局管理器,实现了栈式布局的动态切换。
Widget类的结构
class Widget : public QWidget { Q_OBJECTprivate: QPushButton TestBtn1; QPushButton TestBtn2; QPushButton TestBtn3; QPushButton TestBtn4; void initControl();private slots: void timerTimeout();public: Widget(QWidget *parent = 0); ~Widget(); void initControl();}
初始化逻辑
Widget::Widget(QWidget *parent) : QWidget(parent) { 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"); TestBtn2.setText("2nd Button"); TestBtn3.setText("3rd Button"); TestBtn4.setText("Test Button 4: D.T.Software"); TestBtn2.setParent(widget); TestBtn3.setParent(widget); hLayout->addWidget(TestBtn2); hLayout->addWidget(TestBtn3); widget->setLayout(hLayout); sLayout->addWidget(TestBtn1); sLayout->addWidget(widget); sLayout->addWidget(TestBtn4); sLayout->setCurrentIndex(1); setLayout(sLayout); connect(timer, SIGNAL(timeout()), this, SLOT(timerTimeout())); timer->start(2000);}
计时器消息处理
void Widget::timerTimeout() { QStackedLayout* sLayout = dynamic_cast(layout()); if (sLayout && sLayout->count()) { int index = (sLayout->currentIndex() + 1) % sLayout->count(); sLayout->setCurrentIndex(index); }}
代码整合与运行
#include "Widget.h"#include#include #include #include #include int main(int argc, char *argv) { QApplication a(argc, argv); Widget w; w.show(); return a.exec();}
通过上述实现,开发者可以轻松管理多个组件的显示顺序,实现栈式布局的动态切换。
发表评论
最新留言
很好
[***.229.124.182]2025年03月23日 22时47分52秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
大白话说Java反射:入门、使用、原理
2019-03-06
集合系列 Set(八):TreeSet
2019-03-06
JVM基础系列第11讲:JVM参数之堆栈空间配置
2019-03-06
MySQL用户管理:添加用户、授权、删除用户
2019-03-06
比技术还重要的事
2019-03-06
linux线程调度策略
2019-03-06
软中断和实时性
2019-03-06
Linux探测工具BCC(可观测性)
2019-03-06
Opentelemetry Metrics SDK
2019-03-06
流量控制--2.传统的流量控制元素
2019-03-06
SNMP介绍及使用,超有用,建议收藏!
2019-03-06
SDUT2161:Simple Game(NIM博弈+巴什博弈)
2019-03-06
51nod 1596 搬货物(二进制处理)
2019-03-06
来自星星的祝福(容斥+排列组合)
2019-03-06
Hmz 的女装(递推)
2019-03-06
HDU5589:Tree(莫队+01字典树)
2019-03-06
不停机替换线上代码? 你没听错,Arthas它能做到
2019-03-06
sharding-jdbc 分库分表的 4种分片策略,还蛮简单的
2019-03-06
分库分表的 9种分布式主键ID 生成方案,挺全乎的
2019-03-06