【问题标题】:widget is only updated at the end of the for loop. I need it to be updated inside the for loop incrementally小部件仅在 for 循环结束时更新。我需要在 for 循环中逐步更新它
【发布时间】:2019-04-17 15:50:59
【问题描述】:

如何使用下面的“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++ qt qt5


    【解决方案1】:

    您不应该在 GUI 中使用 sleep 方法,因为它会长时间阻塞 GUI 所在的 eventloop,解决方法是使用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();
    }
    

    【讨论】:

    • 谢谢大家!!!使用您的方法确实会等待 5 秒钟,我可以在 qDebug consol 中看到它,但它不会立即在 GUI 上显示它,因此它不能解决我的问题。我仍然不明白为什么 GUI 不会在每次增量时立即刷新。
    • @smawell 我认为您还有另一个错误,因为我已经测试了我的答案。另一方面,GUI 存在于事件循环中,也就是说,有一个循环允许 GUI 执行多个操作:读取用户事件,如鼠标、键盘等;读取 OS 事件,如最大化、最小化等;以及重绘但使用睡眠时不允许事件循环运行。
    • @smawell [cont.] 例如,要了解您在代码执行循环时尝试更改窗口的大小,您会看到它会冻结。另一方面,用我的解决方案,不,至少这是我测试过的。所以如果你需要更多帮助,那么你应该提供minimal reproducible example
    猜你喜欢
    • 2016-03-13
    • 2020-08-15
    • 2020-12-17
    • 2016-10-10
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多