Run a function with a delay in QT

Viewed 4024

I want to create a function, let's say (qDebug() << "result" ;). I want to display the result 2 secs later, the delay must be in this function implemented. In other words :

void MainWindow::my_function()
{
     // Here I need something to make a delay of 2 secs
      qDebug() << "result";
}

Is there a method or something that allows to wait 2 secs and then executes the next line ? I m looking for the easiest method on QT.

2 Answers

Do NOT (mis)use sleep functions

Sleep functions are a specialized tool which is incredibly easy to misuse, and Qt gives you a lot of better options. So do not use sleep functions unless you know what you are doing (if only to avoid starting a bad habit).

So, what are your options?

If you only want the 2 second delay (e.g. after the user presses a button) you could use a QTimer::singleShot() which will call the function after the timer expires e.g.

QTimer::singleShot(2000, this, &MainWindow::printResultFunction)

Or you might use a local QEventLoop which you you will exec and then quit (again) using a timer e.g.

QEventLoop loop;
QTimer::singleShot(2000, &loop, &QEventLoop::quit);
loop.exec();

Or you might start a separate thread, which executes your function and in this function use (gasp) QThread::msleep() As I said before sleep functions are a specialized tool - here you know what you are doing. You are not stalling your GUI thread and qt events. You are pausing the execution of a thread designed to do one thing: doing stuff, waiting 2 seconds, doing some more stuff and terminating.

my suggestion is to read first why sleep are a bad idea, specially when GUIS are involved.. anyways, you can since qt5

Functions of QThread

void msleep(unsigned long msecs);
void sleep(unsigned long secs);
void usleep(unsigned long usecs);

using this in your code, you can do

void MainWindow::my_function(){
     // Here I need something to make a delay of 2 secs
     sleep(2);
     qDebug() << "result";
}

but as I said before, read 1st, because this will work, but will freeze the main window too, which is a not so nice idea when considering User Experience etc

Related