【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;
}
相关推荐
win x19 分钟前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
迷枫7121 小时前
DM8 数据库安装实战:从零搭建达梦数据库环境(附全套工具链接)
数据库
XDHCOM2 小时前
PostgreSQL 25001: active_sql_transaction 报错原因分析,故障修复步骤详解,远程处理解决方案
数据库·sql·postgresql
卤炖阑尾炎2 小时前
PostgreSQL 日常运维全指南:从基础操作到备份恢复
运维·数据库·postgresql
daad7773 小时前
wifi_note
运维·服务器·数据库
hhh3u3u3u3 小时前
Visual C++ 6.0中文版安装包下载教程及win11安装教程
java·c语言·开发语言·c++·python·c#·vc-1
加号33 小时前
【C#】实现沃德普线光控制器通信控制(附完整源码)
开发语言·c#
xixingzhe24 小时前
Mysql统计空间增量
数据库·mysql
程序员萌萌4 小时前
Redis的缓存机制和淘汰策略详解
数据库·redis·缓存机制·淘汰策略
freshman_y5 小时前
Qtcreator怎么新建安卓项目?编写一个五子棋游戏APP?
android·qt