QT Object定时器使用

本文介绍了如何在Qt中使用QWidget的定时器功能,包括重写timerEvent函数以处理定时器事件,以及startTimer和killTimer方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);

    // 需要对timerEvent函数进行重写
    virtual void timerEvent(QTimerEvent* event);

    ~Widget();

private slots:
    void on_startTimer_clicked();



    void on_killTimer_clicked();

private:
    Ui::Widget *ui;
    int eventId; // 定时器返回的唯一id,用于区分不同定时器
    int pictureId=1; // 不同图片的编号
};
#endif // WIDGET_H

#include "widget.h"
#include "ui_widget.h"

#define TIME_OUT 1 * 1000

/**
QObject中有定时器,可以直接进行使用startTimer和killTimer操作
但需要对timerEvent进行重新定义,以自己的方式处理定时器
*/
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    QString path("D:\\workspace\\qt\\Timer\\");
    path += QString::number(this->pictureId)+".jpg";

    QPixmap pix(path);
    ui->label->setPixmap(pix);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_startTimer_clicked()
{
    // 开启定时器
    // QObject中有定时器,直接使用,Widget->QWidget->QObject
    this->eventId = this->startTimer(TIME_OUT);

}


void Widget::timerEvent(QTimerEvent* event) {

    // 获取timerId是否为开启定时器所操作的
    if (event->timerId() == this->eventId) {
        QString path("D:\\workspace\\qt\\Timer\\");
        path += QString::number(this->pictureId)+".jpg";

        QPixmap pix(path);
        ui->label->setPixmap(pix);
		this->pictureId++;

        if (this->pictureId == 5) {
            this->pictureId = 1;
        }
    }
}

void Widget::on_killTimer_clicked()
{
    this->killTimer(this->eventId);
}


### QT 定时器使用方法概述 在 Qt 中,`QTimer` 是一种强大的工具,用于实现周期性的任务调度。以下是几种常见的 `QTimer` 使用方法及其示例。 --- #### 方法一:基础版实现 通过创建一个 `QTimer` 对象并连接其信号到槽函数来完成定时操作[^1]。 ```cpp #include <QApplication> #include <QTimer> #include <QDebug> void onTimeout() { qDebug() << "Timeout!"; } int main(int argc, char *argv[]) { QApplication app(argc, argv); QTimer timer; QObject::connect(&timer, &QTimer::timeout, onTimeout); timer.start(1000); // 每隔 1 秒触发一次 timeout() return app.exec(); } ``` 此方法适用于需要频繁调用某个固定时间间隔的任务场景[^4]。 --- #### 方法二:便捷版实现(基于 Lambda 函数) 利用 C++11 的 Lambda 表达式简化代码结构[^3]。 ```cpp #include <QCoreApplication> #include <QTimer> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTimer::singleShot(2000, [](){ qDebug() << "This will be executed after 2 seconds."; }); QTimer timer; QObject::connect(&timer, &QTimer::timeout, [](){ static int count = 0; qDebug() << "Timeout called:" << ++count; }); timer.start(1000); // 每秒触发一次 return app.exec(); } ``` 这种方法更加简洁明了,尤其适合简单的回调逻辑。 --- #### 方法三:一次性版实现 如果只需要执行一次延迟任务,则可以使用 `QTimer::singleShot()` 静态方法。 ```cpp #include <QCoreApplication> #include <QTimer> #include <QDebug> int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QTimer::singleShot(5000, [&]() { qDebug() << "Executed once after 5 seconds."; QCoreApplication::quit(); }); return app.exec(); } ``` 上述代码会在 5 秒钟后打印消息并退出程序。 --- #### 方法四:重写定时器事件版实现(QObject 内部定时器) 对于更复杂的自定义需求,可以通过继承 `QObject` 并重载 `timerEvent` 来处理定时器事件[^2]。 ```cpp #include <QObject> #include <QDebug> class MyObject : public QObject { public: explicit MyObject(QObject *parent = nullptr) : QObject(parent), m_timerId(-1) {} protected: void timerEvent(QTimerEvent *event) override { if (event->timerId() == m_timerId) { qDebug() << "Custom Timer Event Triggered"; } else { QObject::timerEvent(event); } } public slots: void startCustomTimer() { m_timerId = startTimer(2000); // 设置每两秒钟触发一次 } private: int m_timerId; }; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); MyObject obj; QObject::connect(&app, &QCoreApplication::aboutToQuit, [&obj]() { obj.killTimer(obj.m_timerId); // 清理资源 }); obj.startCustomTimer(); return app.exec(); } ``` 这种方式提供了更大的灵活性,允许开发者完全控制如何响应计时器事件。 --- ### 总结 以上介绍了四种不同的 `QTimer` 使用方式,分别对应不同复杂度的需求。无论是基本的重复任务还是单次延时操作,都可以找到合适的解决方案[^1]. ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值