Use the QDeadlineTimer class to implement the timer function

Use the QDeadlineTimer class to implement the timer function

The QDeadlineTimer class is a class used to implement timer functions in Qt. It allows us to set a timestamp, and when this timestamp arrives, a signal will be triggered automatically. Compared with other timer classes in Qt, QDeadlineTimer can provide higher precision and accuracy because it is based on the system clock for timing.

Below we will demonstrate how to use the QDeadlineTimer class to implement a simple timer.

First, include the header file of the QDeadlineTimer class in the header file:

#include <QDeadlineTimer>

Then, define a QDeadlineTimer object in the class:

private:
    QDeadlineTimer m_deadlineTimer;

Next, set the timer's timestamp and connect signals and slots in the class constructor:

MyClass::MyClass(QObject *parent) : QObject(parent)
{
    // 设置定时器时间戳为2秒后
    m_deadlineTimer.setDueTime(QDeadlineTimer::currentMSecsSinceEpoch() + 2000);

    // 连接信号和槽
    connect(&m_deadlineTimer, &QDeadlineTimer::timeout, this, &MyClass::onTimeout);
}

In the slot function onTimeout(), we can perform operations that need to be performed when the timer fires, such as outputting a message:

Guess you like

Origin blog.csdn.net/update7/article/details/132703510