Search code examples
c++qtc++11timedelay

Run a function with a delay in QT


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.


Solution

  • 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