首页 > 解决方案 > 小部件仅在 for 循环结束时更新。我需要在 for 循环中逐步更新它

问题描述

如何使用下面的“for循环”来立即更新窗口。sleep(5) 只是查看物品是否立即被填满

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

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);
}

标签: c++qtqt5

解决方案


您不应该在 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();
}

推荐阅读