【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;
}
相关推荐
VX:Fegn08954 小时前
计算机毕业设计|基于ssm + vue超市管理系统(源码+数据库+文档)
前端·数据库·vue.js·spring boot·后端·课程设计
chipsense4 小时前
电流传感器型号从数据库查询并排序输出到网页的方法
数据库·php·传感器·霍尔电流传感器
踢足球09294 小时前
寒假打卡:2026-01-28
数据库·oracle
麦聪聊数据4 小时前
智慧医疗数据互联互通:使用 QuickAPI 构建实时诊疗数据交换层
数据库·sql·安全
风吹落叶花飘荡4 小时前
2026年mysql数据库迁移(全流程)
数据库·mysql
2301_822382765 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
m0_748229995 小时前
Laravel8.X核心功能全解析
开发语言·数据库·php
液态不合群5 小时前
【面试题】MySQL 的索引下推是什么?
数据库·mysql
2301_790300965 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python
qq_401700416 小时前
Qt 中文乱码的根源:QString::fromLocal8Bit 和 fromUtf8 区别在哪?
开发语言·qt