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();
}
相关推荐
张张努力变强41 分钟前
C++ Date日期类的设计与实现全解析
java·开发语言·c++·算法
沉默-_-1 小时前
力扣hot100滑动窗口(C++)
数据结构·c++·学习·算法·滑动窗口
斐夷所非2 小时前
C++ 继承、多态与类型转换 | 函数重载 / 隐藏 / 覆盖实现与基派生类指针转换
c++
gfdhy2 小时前
【C++实战】多态版商品库存管理系统:从设计到实现,吃透面向对象核心
开发语言·数据库·c++·microsoft·毕业设计·毕设
清酒难咽3 小时前
算法案例之分治法
c++·经验分享·算法
小屁猪qAq3 小时前
强符号和弱符号及应用场景
c++·弱符号·链接·编译
头发还没掉光光3 小时前
HTTP协议从基础到实战全解析
linux·服务器·网络·c++·网络协议·http
jojo_zjx4 小时前
GESP 24年12月2级 数位和
c++
自由的好好干活4 小时前
PCI9x5x驱动移植支持PCI9054在win7下使用3
c++·驱动开发
WBluuue6 小时前
数据结构与算法:dp优化——优化尝试和状态设计
c++·算法·leetcode·动态规划