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();
}
相关推荐
QuantumStack43 分钟前
【C++ 真题】P1104 生日
开发语言·c++·算法
天若有情6731 小时前
01_软件卓越之道:功能性与需求满足
c++·软件工程·软件
whoarethenext1 小时前
使用 C++/OpenCV 和 MFCC 构建双重认证智能门禁系统
开发语言·c++·opencv·mfcc
Jay_5152 小时前
C++多态与虚函数详解:从入门到精通
开发语言·c++
xiaolang_8616_wjl3 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
FrostedLotus·霜莲3 小时前
C++主流编辑器特点比较
开发语言·c++·编辑器
liulilittle8 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
十年编程老舅9 小时前
跨越十年的C++演进:C++20新特性全解析
c++·c++11·c++20·c++14·c++23·c++17·c++新特性
小刘同学32110 小时前
C++11 特性
c++·c11新特性