Search code examples
c++qtqthread

QT cpp delay in for loop


i have a loop that fill my textBrowser widget. Now i want to have an 1sec delay in my loop. I want that he append one row and wait 1 sec before fill another row. I tried it with sleep in my loop but it doesnt work. He fill my textbrowser without any delay.

*#include <QThread>*
..
sleep(1);

my code looks like that:

 for(int i = 0; i < array.count(); i++)

   {     
     QString br = "ID-->"+array[i];
     ui->textBrowser->append(br);
   }

How can i delay my loop?


Solution

  • It is best to use events form a QTimer instead of using a loop. For an example, you can use a slot like following.

    int i = 0;
    
    void MainWindow::OnTimer()
    {
        QString br = "ID-->" + array[i++];
        ui->textBrowser->append(br);
        if (i < array.count())
        {
            QTimer::singleShot(1000, this, SLOT(OnTimer()));
        }
    }
    

    You will have to keep array and i as a class variables.

    But if you just want to get this done somehow, you can use following code in your loop instead of a sleep. This will block the for loop but continue to process events so the UI will get updated while iterating. But it is kind of a hack.

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