Qt events: timer events

In addition to using QTimer for timers in qt, all objects that inherit QObject can use timer events.

1. Turn on the timer:

int QObject::startTimer(int interval, Qt::TimerType timerType = Qt::CoarseTimer)

The return value is the timer ID.

Parameter 1 is the time interval, which can be written in several ways:

  • The most commonly used is to write numbers directly, the unit is milliseconds
  • Standard library time:
    using namespace std::chrono;
    startTimer(milliseconds(50));//毫秒
    startTimer(seconds(1));//秒
    startTimer(minutes(1));//分钟
    using namespace std::chrono_literals;
    startTimer(100ms);
    startTimer(5s);
    startTimer(2min);
    startTimer(1h);

 Parameter 2 is the timer accuracy:

  • Qt::PreciseTimer tries to maintain the accuracy of milliseconds
  • Qt::CoarseTimer CoarseTimer tries to keep the accuracy within 5% of the required interval
  • Qt::VeryCoarseTimer very rough timer can only maintain full second precision

On UNIX (including Linux, macOS and iOS), Qt will maintain the millisecond precision of Qt::PreciseTimer. For Qt::CoarseTimer, the interval will be adjusted to 5% to align the timer with other timers that are expected to trigger at or about the same time. Its purpose is to wake up most timers at the same time, thereby reducing CPU wake-up and power consumption.

On Windows, Qt will use the Windows multimedia timer tool (if available) to implement Qt::PreciseTimer, and use ordinary Windows timers to implement Qt::groassetimer and Qt::VeryCoarseTimer.

On all platforms, the interval of Qt::VeryCoarseTimer is rounded to the nearest whole second (for example, an interval of 23500ms will be rounded to 24000ms, and 20300ms will be rounded to 20000ms).

2. Timer event

void timerEvent(QTimerEvent *event)
{
    int id = event->timerId();
    if(id == xx)
    {
        //do something
    }
}

3. Stop the timer

void QObject::killTimer(int id)

Guess you like

Origin blog.csdn.net/kenfan1647/article/details/114784386