QTimer Class

The QTimer class provides repetitive and single-shot timers. More...

Header: #include <QTimer>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core
Inherits: QObject

Properties

Public Functions

QTimer(QObject *parent = nullptr)
virtual ~QTimer()
QBindable<bool> bindableActive()
QBindable<int> bindableInterval()
QBindable<bool> bindableSingleShot()
QBindable<Qt::TimerType> bindableTimerType()
QMetaObject::Connection callOnTimeout(Functor &&slot)
QMetaObject::Connection callOnTimeout(const QObject *context, Functor &&slot, Qt::ConnectionType connectionType = Qt::AutoConnection)
(since 6.8) Qt::TimerId id() const
int interval() const
std::chrono::milliseconds intervalAsDuration() const
bool isActive() const
bool isSingleShot() const
int remainingTime() const
std::chrono::milliseconds remainingTimeAsDuration() const
void setInterval(int msec)
void setInterval(std::chrono::milliseconds value)
void setSingleShot(bool singleShot)
void setTimerType(Qt::TimerType atype)
void start(std::chrono::milliseconds msec)
int timerId() const
Qt::TimerType timerType() const

Public Slots

void start(int msec)
void start()
void stop()

Signals

void timeout()

Static Public Members

void singleShot(Duration interval, Functor &&functor)
void singleShot(Duration interval, Qt::TimerType timerType, Functor &&functor)
void singleShot(Duration interval, const QObject *context, Functor &&functor)
void singleShot(Duration interval, Qt::TimerType timerType, const QObject *context, Functor &&functor)
void singleShot(std::chrono::nanoseconds nsec, const QObject *receiver, const char *member)
void singleShot(std::chrono::nanoseconds nsec, Qt::TimerType timerType, const QObject *receiver, const char *member)

Reimplemented Protected Functions

virtual void timerEvent(QTimerEvent *e) override

Detailed Description

The QTimer class provides a high-level programming interface for timers. To use it, create a QTimer, connect its timeout() signal to the appropriate slots, and call start(). From then on, it will emit the timeout() signal at constant intervals.

Example for a one second (1000 millisecond) timer (from the Analog Clock example):

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, QOverload<>::of(&AnalogClock::update));
    timer->start(1000);

From then on, the update() slot is called every second.

You can set a timer to time out only once by calling setSingleShot(true). You can also use the static QTimer::singleShot() function to call a slot after a specified interval:

    QTimer::singleShot(200, this, &Foo::updateCaption);

In multithreaded applications, you can use QTimer in any thread that has an event loop. To start an event loop from a non-GUI thread, use QThread::exec(). Qt uses the timer's thread affinity to determine which thread will emit the timeout() signal. Because of this, you must start and stop the timer in its thread; it is not possible to start a timer from another thread.

As a special case, a QTimer with a timeout of 0 will time out as soon as possible, though the ordering between zero timers and other sources of events is unspecified. Zero timers can be used to do some work while still providing a snappy user interface:

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Foo::processOneThing);
    timer->start();

From then on, processOneThing() will be called repeatedly. It should be written in such a way that it always returns quickly (typically after processing one data item) so that Qt can deliver events to the user interface and stop the timer as soon as it has done all its work. This is the traditional way of implementing heavy work in GUI applications, but as multithreading is nowadays becoming available on more and more platforms, we expect that zero-millisecond QTimer objects will gradually be replaced by QThreads.

Accuracy and Timer Resolution

The accuracy of timers depends on the underlying operating system and hardware. Most platforms support a resolution of 1 millisecond, though the accuracy of the timer will not equal this resolution in many real-world situations.

The accuracy also depends on the timer type. For Qt::PreciseTimer, QTimer will try to keep the accuracy at 1 millisecond. Precise timers will also never time out earlier than expected.

For Qt::CoarseTimer and Qt::VeryCoarseTimer types, QTimer may wake up earlier than expected, within the margins for those types: 5% of the interval for Qt::CoarseTimer and 500 ms for Qt::VeryCoarseTimer.

All timer types may time out later than expected if the system is busy or unable to provide the requested accuracy. In such a case of timeout overrun, Qt will emit timeout() only once, even if multiple timeouts have expired, and then will resume the original interval.

Alternatives to QTimer

Qt 6.8 introduced QChronoTimer. The main difference between the two classes, is that QChronoTimer supports a larger interval range and a higher precision (std::chrono::nanoseconds). For QTimer the maximum supported interval is ±24 days, whereas for QChronoTimer it is ±292 years (less chances of interger overflow with intervals longer than std::numeric_limits<int>::max()). If you only need millisecond resolution and ±24 days range, you can continue to use QTimer.

Another alternative is reimplementing the QObject::timerEvent() method in your class (which must be a sub-class of QObject), and using one of the following approaches:

  • Using QBasicTimer, a lightweight value-class wrapping a timer ID. You can start the timer with QBasicTimer::start() and stop it with QBasicTimer::stop(). You can handle the event in your reimplemneted timerEvent().
  • A more low-level method is manipulating the timer IDs directly. To start the timer call QObject::startTimer(), storing the returned ID. To stop the timer call QObject::killTimer(). You can handle the event in your reimplemented timerEvent(). This approach is typically more cumbersome than using QBasicTimer.

A disadvantage of using timerEvent() is that some high-level features, such as single-shot timers and signals, aren't supported.

Some operating systems limit the number of timers that may be used; Qt tries to work around these limitations.

See also QBasicTimer, QTimerEvent, QObject::timerEvent(), Timers, and Analog Clock.

Property Documentation

[bindable read-only] active : bool

Note: This property supports QProperty bindings.

This boolean property is true if the timer is running; otherwise false.

[bindable] interval : int

Note: This property supports QProperty bindings.

This property holds the timeout interval in milliseconds

The default value for this property is 0. A QTimer with a timeout interval of 0 will time out as soon as all the events in the window system's event queue have been processed.

Setting the interval of a running timer will change the interval, stop() and then start() the timer, and acquire a new id(). If the timer is not running, only the interval is changed.

See also singleShot.

[read-only] remainingTime : const int

This property holds the remaining time in milliseconds

Returns the timer's remaining value in milliseconds left until the timeout. If the timer is inactive, the returned value will be -1. If the timer is overdue, the returned value will be 0.

Access functions:

int remainingTime() const

See also interval.

[bindable] singleShot : bool

Note: This property supports QProperty bindings.

This property holds whether the timer is a single-shot timer

A single-shot timer fires only once, non-single-shot timers fire every interval milliseconds.

The default value for this property is false.

See also interval and singleShot().

[bindable] timerType : Qt::TimerType

Note: This property supports QProperty bindings.

controls the accuracy of the timer

The default value for this property is Qt::CoarseTimer.

See also Qt::TimerType.

Member Function Documentation

[static] template <typename Duration, typename Functor> void QTimer::singleShot(Duration interval, Functor &&functor)

[static] template <typename Duration, typename Functor> void QTimer::singleShot(Duration interval, Qt::TimerType timerType, Functor &&functor)

[static] template <typename Duration, typename Functor> void QTimer::singleShot(Duration interval, Qt::TimerType timerType, const QObject *context, Functor &&functor)

[static] template <typename Duration, typename Functor> void QTimer::singleShot(Duration interval, const QObject *context, Functor &&functor)

This static function calls functor after interval.

It is very convenient to use this function because you do not need to bother with a timerEvent or create a local QTimer object.

If context is specified, then the functor will be called only if the context object has not been destroyed before the interval occurs. The functor will then be run the thread of context. The context's thread must have a running Qt event loop.

If functor is a member function of context, then the function will be called on the object.

The interval parameter can be an int (interpreted as a millisecond count) or a std::chrono type that implicitly converts to nanoseconds.

Note: In Qt versions prior to 6.8, the chrono overloads took chrono::milliseconds, not chrono::nanoseconds. The compiler will automatically convert for you, but the conversion may overflow for extremely large milliseconds counts.

Note: This function is reentrant.

See also start().

[explicit] QTimer::QTimer(QObject *parent = nullptr)

Constructs a timer with the given parent.

[virtual noexcept] QTimer::~QTimer()

Destroys the timer.

template <typename Functor> QMetaObject::Connection QTimer::callOnTimeout(Functor &&slot)

Creates a connection from the timer's timeout() signal to slot. Returns a handle to the connection.

This method is provided for convenience. It's equivalent to calling:

QObject::connect(timer, &QTimer::timeout, timer, slot, Qt::DirectConnection);

Note: This overload is not available when QT_NO_CONTEXTLESS_CONNECT is defined, instead use the callOnTimeout() overload that takes a context object.

See also QObject::connect() and timeout().

template <typename Functor> QMetaObject::Connection QTimer::callOnTimeout(const QObject *context, Functor &&slot, Qt::ConnectionType connectionType = Qt::AutoConnection)

This function overloads callOnTimeout().

Creates a connection from the timeout() signal to slot to be placed in a specific event loop of context, and returns a handle to the connection.

This method is provided for convenience. It's equivalent to calling:

QObject::connect(timer, &QTimer::timeout, context, slot, connectionType);

See also QObject::connect() and timeout().

[since 6.8] Qt::TimerId QTimer::id() const

Returns a Qt::TimerId representing the timer ID if the timer is running; otherwise returns Qt::TimerId::Invalid.

This function was introduced in Qt 6.8.

See also Qt::TimerId.

std::chrono::milliseconds QTimer::intervalAsDuration() const

Returns the interval of this timer as a std::chrono::milliseconds object.

See also interval.

bool QTimer::isActive() const

Returns true if the timer is running; otherwise returns false.

Note: Getter function for property active.

std::chrono::milliseconds QTimer::remainingTimeAsDuration() const

Returns the time remaining in this timer object as a std::chrono::milliseconds object. If this timer is due or overdue, the returned value is std::chrono::milliseconds::zero(). If the remaining time could not be found or the timer is not running, this function returns a negative duration.

See also remainingTime().

[static] void QTimer::singleShot(std::chrono::nanoseconds nsec, const QObject *receiver, const char *member)

This is an overloaded function.

This static function calls a slot after a given time interval.

It is very convenient to use this function because you do not need to bother with a timerEvent or create a local QTimer object.

The receiver is the receiving object and the member is the slot. The time interval is given in the duration object nsec.

Note: In Qt versions prior to 6.8, this function took chrono::milliseconds, not chrono::nanoseconds. The compiler will automatically convert for you, but the conversion may overflow for extremely large milliseconds counts.

Note: This function is reentrant.

See also start().

[static] void QTimer::singleShot(std::chrono::nanoseconds nsec, Qt::TimerType timerType, const QObject *receiver, const char *member)

This is an overloaded function.

This static function calls a slot after a given time interval.

It is very convenient to use this function because you do not need to bother with a timerEvent or create a local QTimer object.

The receiver is the receiving object and the member is the slot. The time interval is given in the duration object nsec. The timerType affects the accuracy of the timer.

Note: In Qt versions prior to 6.8, this function took chrono::milliseconds, not chrono::nanoseconds. The compiler will automatically convert for you, but the conversion may overflow for extremely large milliseconds counts.

Note: This function is reentrant.

See also start().

[slot] void QTimer::start(int msec)

Starts or restarts the timer with a timeout interval of msec milliseconds.

If the timer is already running, it will be stopped and restarted. This will also change its id().

If singleShot is true, the timer will be activated only once. This is equivalent to:

timer.setInterval(msec);
timer.start();

Note: Keeping the event loop busy with a zero-timer is bound to cause trouble and highly erratic behavior of the UI.

[slot] void QTimer::start()

This function overloads start().

Starts or restarts the timer with the timeout specified in interval.

If the timer is already running, it will be stopped and restarted. This will also change its id().

If singleShot is true, the timer will be activated only once.

void QTimer::start(std::chrono::milliseconds msec)

This is an overloaded function.

Starts or restarts the timer with a timeout of duration msec milliseconds.

If the timer is already running, it will be stopped and restarted. This will also change its id().

If singleShot is true, the timer will be activated only once. This is equivalent to:

timer.setInterval(msec);
timer.start();

[slot] void QTimer::stop()

Stops the timer.

See also start().

[private signal] void QTimer::timeout()

This signal is emitted when the timer times out.

Note: This is a private signal. It can be used in signal connections but cannot be emitted by the user.

See also interval, start(), and stop().

[override virtual protected] void QTimer::timerEvent(QTimerEvent *e)

Reimplements: QObject::timerEvent(QTimerEvent *event).

int QTimer::timerId() const

Returns the ID of the timer if the timer is running; otherwise returns -1.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.