【QT】C#中System.Timers.Timer定时触发事件的计时器类,qt与之对应的QTimer类的使用举例

一个桌面应用程序,该应用程序需要定期更新一些数据,以确保用户始终看到最新的信息。
.h

#ifndef TIMEREXAMPLE_H
#define TIMEREXAMPLE_H

#include <QObject>
#include <QTimer>
#include <QDateTime>

class TimerExample : public QObject
{
   
    Q_OBJECT

public:
    explicit TimerExample(QObject *parent = nullptr);
    ~TimerExample();

signals:
    void dataUpdated(QString newData);

public slots:
    void updateData();

private:
    QTimer *timer;
    QString currentData;
};

#endif // TIMEREXAMPLE_H

cpp

#include "timerexample.h"
#include <QDebug>

TimerExample::TimerExample(QObject *parent) : QObject(parent)
{
   
    // 创建定时器对象
    timer = new QTimer(this);

    // 连接定时器的timeout()信号到槽函数
    connect(timer, SIGNAL(timeout()), this, SLOT(updateData()));

    // 设置定时器的时间间隔,单位是毫秒
    timer->start(5000); // 每隔5秒触发一次timeout()信号

    // 初始化数据
    currentData = "Initial data";
}

TimerExample::~TimerExample()
{
   
    // 在对象销毁时,停止定时器并释放资源
    timer->stop();
    delete timer;
}

void TimerExample::updateData()
{
   
    // 模拟从服务器或其他来源获取新数据的操作
    QDateTime currentTime = QDateTime::currentDateTime();
    currentData = "Updated data at " + currentTime.toString("hh:mm:ss");

    // 发送信号,通知数据已经更新
    emit dataUpdated(currentData);
    qDebug() << "Data updated:" << currentData;
}

相关推荐

  1. Qt | QTimer (计时器)

    2023-12-31 01:36:01       39 阅读
  2. Qt定时器QTimer

    2023-12-31 01:36:01       41 阅读
  3. QtQTimer使用简介

    2023-12-31 01:36:01       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-31 01:36:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-31 01:36:01       100 阅读
  3. 在Django里面运行非项目文件

    2023-12-31 01:36:01       82 阅读
  4. Python语言-面向对象

    2023-12-31 01:36:01       91 阅读

热门阅读

  1. 【STL】std::map使用小结

    2023-12-31 01:36:01       67 阅读
  2. TypeScript 类方法装饰器

    2023-12-31 01:36:01       59 阅读
  3. 什么是redis雪崩

    2023-12-31 01:36:01       56 阅读
  4. ELF Strip

    2023-12-31 01:36:01       43 阅读
  5. RabbitMQ消息队列常见面试题

    2023-12-31 01:36:01       56 阅读
  6. Git 命令

    2023-12-31 01:36:01       44 阅读
  7. 【Linux】修复 Linux 错误 - 地址已在使用中

    2023-12-31 01:36:01       51 阅读
  8. ❀My排序算法学习之选择排序❀

    2023-12-31 01:36:01       53 阅读
  9. CAPL解析DBC文件

    2023-12-31 01:36:01       68 阅读
  10. OpenFeign相关面试题及答案

    2023-12-31 01:36:01       43 阅读
  11. linux安装nginx

    2023-12-31 01:36:01       48 阅读
  12. asset模块在Github的含义

    2023-12-31 01:36:01       56 阅读
  13. 离线服务器中python包的安装

    2023-12-31 01:36:01       50 阅读