qt定时器

定时器也就是每个一定的时间就调用一个特定的函数:

第一步添加头文件:

#include<QTimer>

第二步定义一个定时器对象并且设定时间:

QTimer  *timcr=new QTimer(this);//new 一个定时器
timcr->start(500);//设置500时间发送一个信号
timcr->stop();//关闭发送信号

第三步自定义信号和槽函数来处理要实现的东西:

在头文件中声明一个槽函数:
private slots:
    void TimcrEvent();//定义一个槽函数专门处理定时器槽函数


在头文件中定义一个槽函数:
void MainWindow::TimcrEvent()
{
   qDebug()<<"你好呀";
}


然后就可以写自定义信号和槽:
 connect(timcr,&QTimer::timeout,this, &MainWindow::TimcrEvent);



### QT 定时器使用方法 #### 基础版实现 通过 `QTimer` 类创建并连接信号槽来实现定时功能。以下是具体代码示例: ```cpp #include <QCoreApplication> #include <QTimer> #include <QDebug> void timerCallback() { qDebug() << "Timer triggered!"; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTimer timer; QObject::connect(&timer, &QTimer::timeout, timerCallback); timer.start(1000); // 设置间隔时间为 1 秒 return app.exec(); } ``` 此代码展示了如何利用 `QTimer` 的 `timeout()` 信号触发回调函数[^1]。 --- #### Lambda 版本实现 借助 C++11 中的 Lambda 表达式简化代码结构,无需单独定义全局函数或成员函数作为回调处理逻辑: ```cpp #include <QCoreApplication> #include <QTimer> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTimer timer; QObject::connect(&timer, &QTimer::timeout, [](){ qDebug() << "Lambda Timer Triggered!"; }); timer.start(2000); // 每隔 2 秒触发一次 return app.exec(); } ``` 这种方式更加简洁明了,并且减少了额外命名的需求[^2]。 --- #### 一次性版本实现 如果只需要执行单次操作,则可以通过设置 `QTimer` 的 `singleShot` 属性或者直接调用静态方法完成任务: ```cpp #include <QCoreApplication> #include <QTimer> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTimer::singleShot(3000, [&]() { // 3秒后触发 qDebug() << "Single Shot Timer Triggered!"; QCoreApplication::quit(); // 结束程序运行 }); return app.exec(); } ``` 上述例子演示了一次性计时器的功能,在指定时间之后仅触发一次动作。 --- #### 重写定时器事件版实现 对于更复杂的场景,可能需要继承自 `QObject` 并覆盖其虚函数 `timerEvent(QTimerEvent *)` 来响应多个独立的定时器请求: ```cpp #include <QObject> #include <QTimerEvent> #include <QDebug> class MyObject : public QObject { protected: void timerEvent(QTimerEvent *event) override { if (event->timerId() == m_timerId1) { qDebug() << "First Timer Event"; } else if (event->timerId() == m_timerId2) { qDebug() << "Second Timer Event"; } } public: explicit MyObject(QObject *parent = nullptr): QObject(parent), m_timerId1(-1), m_timerId2(-1){} void startTimers() { m_timerId1 = startTimer(1000); // 启动第一个每秒触发的计时器 m_timerId2 = startTimer(2000); // 启动第二个每隔两秒触发的计时器 } private: int m_timerId1; // 记录第一个计时器ID int m_timerId2; // 记录第二个计时器ID }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); MyObject myObj; myObj.startTimers(); return app.exec(); } ``` 这里实现了多路定时机制,适合于复杂业务需求下的灵活控制[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值