Accelerate reaction of GUI elements



  • Hi,

    I have a program of important calculations, with GUI including a label to display status of calculations, and a progress bar to update the progression. How ever, the reaction of content of the label and progress bar is slow. My code looks like (in simplified structure):
    @
    void testa::main_calc () {
    ui.label->setText("Preparing..."); // doesn't display
    // important calculations here
    ui.label->setText("Running..."); // display
    for(int i=0; i<100; i++) {
    // important calculations here
    ui.progressBar->setValue(i); // only displays to 40-50%
    }
    // important calculations
    ui.label->setText("Processing..."); // doesn't display
    // important calculations
    ui.progressBar->setValue(100); // display
    ui.label->setText("Finished."); // display
    }@
    It seems when the calculations are intense, the contents of elements of GUI are not reactive. However, when there is a @ui.progressBar->setValue()@ before @ui.label->setText()@ , the label can display normally.

    Could anyone please tell me how the fix it, and make it reactive? (before this code, I have made a simple one (no important calculations) with same structure, it worked perfectly.) Thanks in advance!


  • Moderators

    Hi,

    When the main thread is performing calculations, it is blocked from updated the GUI. If the calculation is very short, then the user won't notice the blockage. If the calculation is long, then the blockage will last a long time, and the program feels frozen.

    Also, some of your calls to label->setText() and progressBar->setValue() isn't visible because Qt detects that it has lots of calculations to do, so it tries to be efficient and stops updating the GUI.

    This can easily be solved -- There's a quick (but less scalable) way, and there's a longer (but more robust) way.

    The quick but less scalable way:
    Call "QCoreApplication::processEvents()":http://qt-project.org/doc/qt-5.0/qtcore/qcoreapplication.html#processEvents periodically during your calculation, to force the thread to process GUI events. Note: how frequently you should call this function depends on your hardware, and on the number of other tasks running in your OS; you might call processEvents() too frequently, or not frequently enough.

    This should be fine in your case, but complex programs should avoid this method, as there's a greater risk of infinite recursion.

    The longer but more robust way:
    Move your calculation to another thread (see "this example":http://qt-project.org/doc/qt-5.0/qtcore/qthread.html#details ). As the calculation progresses, emit signals that are connected to the ui.label->setText() and ui.progressBar->setValue() slots.



  • OK, thanks. I will check both two ways. I am pretty sure to find a good one to fix it. :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.