窗口小部件仅在for循环结束时更新。我需要它在for循环内逐步更新

时间:2019-04-17 15:50:59

标签: c++ qt qt5

如何使用此“ for循环”对话框立即更新窗口。 Sleep(5)只是查看项目是否立即填充

我在带有一个按钮,一个plainTextEdit和一个textEdit的简单“类MainWindow:public QMainWindow”中使用Qt

for (int i=0; i < 10 ; i++ )
{
    sentFrame = "toto"+i;
    ui->alarmSent->addItem(sentFrame.toHex()); // filled at the end of for loop
    ui->sentTest->insertPlainText(sentFrame.toHex()); // filled at the end of for loop
    sleep(5);
}

1 个答案:

答案 0 :(得分:2)

您不应在GUI中使用sleep方法,因为它会长时间阻塞GUI所在的事件循环,一种解决方法是使用QTimer::singleShot() + QEventLoop

for (int i=0; i < 10 ; i++ )
{
    sentFrame = "toto"+i;
    ui->alarmSent->addItem(sentFrame.toHex()); 
    ui->sentTest->insertPlainText(sentFrame.toHex()); 
    QEventLoop loop;
    QTimer::singleShot(5*1000, &loop, &QEventLoop::quit);
    loop.exec();
}