当前位置: 首页 > article >正文

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

 

 

 


http://www.kler.cn/news/336276.html

相关文章:

  • java给word设置复选框
  • Springboo通过http请求下载文件到服务器
  • Github优质项目推荐-第三期
  • 软考鸭微信小程序:助力软考备考的便捷工具
  • 【Docker】配置文件
  • FlagVNE]——用于虚拟网络嵌入的灵活、可通用的强化学习框架
  • 6.1K Star,简简单单的看直播
  • 新手教学系列——用 VSCode 实现高效远程开发
  • 北交大研究突破:塑料光纤赋能低成本无摄像头AR/VR眼动追踪技术
  • AI大语言模型进阶应用及模型优化、本地化部署、从0-1搭建、智能体构建技术
  • 【笔记】微分方程
  • Spring Boot 进阶-详解Spring Boot整合数据库
  • 基于FPGA的ov5640摄像头图像采集(二)
  • Web常见的攻击方式及防御方法
  • 【黑马点评】 使用RabbitMQ实现消息队列——2.使用RabbitMQ监听秒杀下单
  • http 缓存
  • vSAN04:vSAN远程数据存储挂载、双节点集群介绍/安装/组件读写/高级配置/故障处理方式
  • 【Ubuntu】DNS设置不生效/重启被重置
  • 基于SpringBoot+Vue的科研课题项目管理系统源码
  • MQ 架构设计原理与消息中间件详解(三)