QT界面刷新问题---对控件进行操作后没有实时更新显示

void MatchModel::btnTrainClicked(){
    UI2MatchParam();
    ui.setWidget->setVisible(false);//隐藏 
    ui.statusWidget->setVisible(true);//显示
    //qApp->processEvents();//加上这条语句后达到预期目的,解决问题
    bool flag = match->CreateShapeModel(matchParam);
    QMessageBox message(QMessageBox::NoIcon, "状态", flag ? "    建模完成      " : "    建模失败!      ");
    message.exec();
    ui.setWidget->setVisible(true);//显示
    ui.statusWidget->setVisible(false);//隐藏
}

源程序代码所要实现的功能,当主操作界面点击按钮“训练”时,执行该槽函数,最终的效果为,将原本界面其中一个显示的QWidget隐藏,而把原本隐藏的一个QWidget显示在界面上,如下图所示:

点击“训练”按钮前:

点击“训练”按钮但还未训练完成:

点击“训练”按钮并且训练完成后:

而未加函数qApp->processEvents();前,在训练过程中并未显示第二个图中的效果,即原本界面其中一个显示的QWidget隐藏,而把原本隐藏的一个QWidget显示在界面上。等到训练完成后调用了message.exec();才会显示隐藏对应的QWidget。说明程序执行以下两条语句时,并不能直接实时更新界面,

    ui.setWidget->setVisible(false);//隐藏 
    ui.statusWidget->setVisible(true);//显示

而在调用

message.exec();
便可刷新一次界面。

问题解决:https://jingyan.baidu.com/article/d5a880eb6d5f7f13f147ccff.html
在对控件进行操作后,然接着 qApp->processEvents(),这句代码便能及时刷新界面,至于程序中执行message
.exec()后便能书信界面,那是由于message.exec()函数本身就有调用到
qApp->processEvents()。

对于

qApp->processEvents()的英文解释

Processes all pending events for the calling thread according
to the specified flags until there are no more events to process.
You can call this function occasionally when your program is busy
performing a long operation(e.g.copying a file).In event you are
running a local loop which calls this function continuously, without
an event loop, the DeferredDelete events will not be processed.This
can affect the behaviour of widgets, e.g.QToolTip, that rely on DeferredDelete
events to function properly.An alternative would be to call sendPostedEvents()
from within that local loop.

 
One day,I will say "I did it"
原文地址:https://www.cnblogs.com/Vince-Wu/p/10395370.html