topic logo
Qt ⇢ Unit 5

Trigger Delayed Actions

make things happen after a timeout


Introduces the QTimer class, that emits one-time or repeated signals.


Some applications need delayed events. For example a demo reel that needs to progress every few seconds.

New Classes

  • QTimer: A timer class that emits a signal after a set timeout. This can be a repetitive pulse or a single shot signal.

Timer Application

Wait, this was different a moment ago!
Wait, this was different a moment ago!

The timer application creates a timer, sets it to three seconds and then starts it. When it times out, a signal is emitted that is connected to a slot which makes the face label change.

The skeleton of the application is the same as in the first unit. The application window is a QLabel with an added slot called onTimeout(), which contains the following code:

setText("Time's up!");

It changes the text that is displayed on the label.

Creating and Priming a Timer

    setText("Wait a moment..");

    auto timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, &Timer::onTimeout);

The constructor does most of the work here:

auto timer = new QTimer(this);

First it creates a new timer. It passes this as parent parameter to make sure the timer is properly cleaned up when the application terminates (more on that in a later unit).


By default, a timer is set to pulse, i.e. it emits the timeout signal over and over again in the interval that it is started with. With the “QTimer::setSingleShot()” method it’s instructed to fire the event only once.

connect(timer, &QTimer::timeout, this, &Timer::onTimeout);

The QTimer::timeout() signal is connected to the Timer::onTimeout() slot.


Finally the timer is started with a 3000 millisecond interval (3 seconds).


Timers are not part of most applications, but sometimes they are very useful. The following units will use them to demonstrate differences between application states.