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_OBJECT
private:
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();
}

通过上述实现,开发者可以轻松管理多个组件的显示顺序,实现栈式布局的动态切换。

上一篇:Qt 26 布局管理器5 -布局管理器实验,实现向导用户界面及切换
下一篇:Qt 24 布局管理器3 - QFormLayout 表单布局管理器

发表评论

最新留言

很好
[***.229.124.182]2025年03月23日 22时47分52秒