unexplained delay after QProgressBar finish loading

后端 未结 2 905
渐次进展
渐次进展 2021-01-24 10:47

I have emit signal from a loop (which make some calculations) that triggers progress bar update which located on the main GUI, after the loop ends the progress bar updated to 10

2条回答
  •  执念已碎
    2021-01-24 11:08

    Try the following:

    #include 
    ...
    
    processMethod(...)
    {
        Loop(...)
        {
            emit processBarSignle(value);
            QCoreApplication::processEvents();
            ...some calculations...
        }
        emit processBarSignle(100);
        QCoreApplication::processEvents();
    }
    

    processEvents() is a static method of QCoreApplication, like that it is sufficient to include only QCoreApplication which is part of the QtCore library.

    In addition, you should add processEvents() after the progress bar has been updated, not before that.

    Note that processEvents() does not return until every event in Qt's Event Queue has been processed. If there is e.g. a Cancel button, you will have to check if the user actually cancelled the operation each time you called processEvents().
    You can exclude user-specific events like mouse clicks / key presses by using

    QCoreApplication::processEvents( QEventLoop::ExcludeUserInputEvents )
    

    but that will not allow clicking anything (e.g. a Cancel Button) while the loop is active.

    As a further note: It should be called "processBarSi ng le" ;-)


    Clarification on threads etc:

    Your whole loop, and any mouse clicks etc are executed in only one thread. If you call emit(), the slot which is connected to that signal is executed instantly (unless the slot was actually in a different thread). In the meantime, the loop does not continue!

    When the slot has finished, your loop will continue. In my example this means processEvents() will get called. Now if your slot updated the progress bar or did anything else which caused a repaint, there will be a repaint event in the Event Queue and this repaint will now happen.
    If you execute processEvents() before calling your slot, there would be no repaint event which could be processed at this point.

    Once again, the loop does not continue until processEvents() is completely done. When all pending events were processed, the loop continues with your calculations.

提交回复
热议问题