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();
}
相关推荐
Watermelon Y1 小时前
【C++】多肽
开发语言·c++
碧海蓝天20221 小时前
C++ 线性表、内存操作、 迭代器,数据与算法分离。
开发语言·数据结构·c++·算法
single5942 小时前
【优选算法】(第十七篇)
java·数据结构·c++·vscode·算法·leetcode
Silent starry sky2 小时前
C++初学者指南-5.标准库(第二部分)–随机数生成
c++·算法
C++忠实粉丝2 小时前
C++IO流
开发语言·c++
朔北之忘 Clancy4 小时前
2021 年 12 月青少年软编等考 C 语言二级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
乱打一通4 小时前
C++里的随机数
开发语言·c++
zty郑桐羽呀4 小时前
[C++] 小游戏 征伐 SLG DNF 0.0.1 版本 zty出品
开发语言·数据结构·c++·算法·开源·zty郑桐羽呀·zty
Noric!7 小时前
240 搜索二维矩阵 II
c++·leetcode
chian-ocean7 小时前
【C++】BitSet和Bloom_Filter
java·开发语言·c++