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

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

.h

cpp 复制代码
#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

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;
}
相关推荐
2301_800256112 分钟前
数据库设计中的 “数据依赖→设计异常→关系分解(范式)” 核心逻辑
数据库·postgresql
冰冰菜的扣jio2 分钟前
Redis基础数据结构
数据结构·数据库·redis
汽车仪器仪表相关领域18 分钟前
光轴精准测量,安全照明保障——NHD-8101/8000型远近光检测仪项目实战分享
数据库·人工智能·安全·压力测试·可用性测试
大爱编程♡27 分钟前
Spring IoC&DI
数据库·mysql·spring
king_harry36 分钟前
金仓数据库KingbaseES中WalMiner接口使用
数据库·kingbase·walminer
爱潜水的小L40 分钟前
自学嵌入式day43,商城网页
数据库·oracle
IvorySQL1 小时前
PostgreSQL 的 SQL 查询之旅
数据库·人工智能·postgresql·开源
musenh1 小时前
redis和jedis
数据库·redis·缓存
莳花微语1 小时前
磐维数据库的权限使用
数据库
win x2 小时前
Redis 主从复制
java·数据库·redis