【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;
}
相关推荐
咖啡の猫19 小时前
Python字典的查询操作
数据库·python·c#
这儿有一堆花20 小时前
2025 年免费指纹浏览器清单
数据库
淼淼76320 小时前
QT表格与数据
开发语言·qt
小灰灰搞电子21 小时前
Qt 实现炫酷锁屏源码分享
开发语言·qt·命令模式
czhc114007566321 小时前
c# 1213
开发语言·数据库·c#
voltina21 小时前
【SQL】【事务】
数据库·sql
古渡蓝按21 小时前
PostgreSQL数据库在Windows上实现异地自动备份指南-喂饭图文教程
数据库
她说..21 小时前
MySQL数据处理(增删改)
java·开发语言·数据库·mysql·java-ee
xiaoid21 小时前
C#向jave平台的API接口推送
c#·post·webapi
E***U9451 天前
从新手到入门:如何判断自己是否真的学会了 Spring Boot
数据库·spring boot·后端