~/Blog

Brandon Rozek

Photo of Brandon Rozek

PhD Student @ RPI studying Automated Reasoning in AI and Linux Enthusiast.

Qt Timers

Published on

Updated on

Warning: This post has not been modified for over 2 years. For technical posts, make sure that it is still relevant.

Qt has two great timers, one that repeats an action after a certain interval, and one that is meant for one-off operations. They call these QTimer and QTimer::singleShot respectively. This post is going to assume that we’re working with a class named Test that inherits QObject.

Let us first look at the one that repeats. This code needs to be inside a class that inherits QObject.

void Test::callbackRepeat(void) {
    // Code that executes when the timer times out
}

// ......
int interval = 1000; // Units: milliseconds
QTimer* timer = new QTimer(this);
timer->start(interval);
connect(timer, &QTimer::timeout, this, &Test::callbackRepeat);

Now for the one-off…

void Test::callback(void) {
	// Code that executes when the timer times out
}

// ......
int timeout = 1000; // Units: milliseconds
QTimer::singleShot(timeout, this, &Test::callback)
Reply via Email Buy me a Coffee
Was this useful? Feel free to share: Hacker News Reddit Twitter

Published a response to this? :