Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing the Qt GUI to update before entering a separate function

This seems like it should be automatic, but apparently it's not. I have the following code:

    ui.my_label->setText("Test 1...");
    ui.my_label->adjustSize();

    processThatTakesAbout30SecondsToFinish(files[0].toStdString());

    ui.my_label->setText("Finished.");
    ui.my_label->adjustSize();

What is happening is that I never see "Test1...", as the GUI seems to hang until the following function completes, and I eventaully only see "Finished.".

How can I make sure the GUI is updating before it enters that function?
Thanks.

like image 448
zebra Avatar asked Sep 13 '12 16:09

zebra


3 Answers

You shuld be able to process the event queue before entering your code if you;

#include <QApplication>

and, when you want to refresh your GUI, call;

qApp->processEvents();

Note that it may be a good idea to let your long running process call that function now and then, to make your GUI feel more responsive.

like image 164
Joachim Isaksson Avatar answered Nov 10 '22 17:11

Joachim Isaksson


If you don't care about your GUI being responsive during this time, then a call to my_label->repaint() would do the trick. Qt can't do anything automatically for you unless you yield to the event loop.

For maximimum responsiveness you might consider running your process in a separate thread and use signal/slot connections (which are thread-safe by default) to signal to your main GUI thread when your processing is complete.

like image 23
Chris Avatar answered Nov 10 '22 17:11

Chris


I just wanted to add that for me it took a combo of the two answers I saw here. So what worked for me was:

ui.my_label->setText("Test 1...");
ui.my_label->adjustSize();

//! Both of these lines needed
ui.my_label->repaint();
qApp->processEvents();

processThatTakesAbout30SecondsToFinish(files[0].toStdString());

ui.my_label->setText("Finished.");
ui.my_label->adjustSize();

Hope this helps someone.

like image 3
Chuck Claunch Avatar answered Nov 10 '22 16:11

Chuck Claunch