qtimer动态更新GUI数据

前言

QTimer

  • QTimer 是一个事件驱动的定时器,它在 Qt 的事件循环中触发。
  • 它适用于需要周期性更新 UI 的场景,例如实时监控、动画等。
  • QTimer 可以在主线程中使用,也可以安全地用于跨线程更新 UI,因为它的 timeout() 信号可以在主线程中处理。
  • 使用 QTimer 时,你不需要担心线程安全问题,因为所有的更新都会通过 Qt 的事件系统进行。
  • QTimer 不会创建新的线程,因此它不会增加额外的资源消耗。

一、 创建QTimer

复制代码
        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &MyWidget::updateData);
        timer->start(1000); // 每隔1000毫秒更新一次

二、连接信号跟槽

复制代码
private slots:
    void updateData() {
        // 获取新数据
        static int count = 0;
        QString newData = QString("Updated Data %1").arg(++count);
        // 更新 QLabel
        uiLabel->setText(newData);
    }

三、更新GUI

复制代码
int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}

四、测试代码示例

复制代码
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QTimer>

class MyWidget : public QWidget {
    Q_OBJECT
public:
    MyWidget(QWidget *parent = nullptr) : QWidget(parent) {
        QVBoxLayout *layout = new QVBoxLayout(this);
        auto *label = new QLabel("Initial Data", this);
        layout->addWidget(label);
        uiLabel = label;

        QTimer *timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &MyWidget::updateData);
        timer->start(1000); // 每隔1000毫秒更新一次
    }

private slots:
    void updateData() {
        // 获取新数据
        static int count = 0;
        QString newData = QString("Updated Data %1").arg(++count);
        // 更新 QLabel
        uiLabel->setText(newData);
    }

private:
    QLabel *uiLabel;
};

#include "main.moc"

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);
    MyWidget widget;
    widget.show();
    return app.exec();
}
相关推荐
快乐的划水a4 小时前
组合模式及优化
c++·设计模式·组合模式
星星火柴9365 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑6 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
阿巴~阿巴~8 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
旺小仔.9 小时前
双指针和codetop复习
数据结构·c++·算法
jingfeng51410 小时前
C++ STL-string类底层实现
前端·c++·算法
郝学胜-神的一滴10 小时前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl
努力努力再努力wz11 小时前
【c++深入系列】:万字详解模版(下)
java·c++·redis
瓦特what?12 小时前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘
祁同伟.13 小时前
【C++】动态内存管理
开发语言·c++