Search code examples
c++qtpthreadsqt4

C++ Qt preserve order of operation: update QLabel before moving on


In a part of the code (as shown below), the label updates with the text after the generate function in next line has finished working. I need the label to update before starting the generate begins working.

void myDialog::my_custom_slot()
{
   emit someLabel->setVisible(true);
   emit someLabel->setText("Some Text...");

   string result = func.generate_str(); // operation takes 5 to 10 second
}

I'm still learning the basics of Qt. My program is quit straight forward with no additional threaded activities. My guess so far has been that the Qt's threading are doing some interesting things, but I'm not sure how to get the desired outcome.

Using Qt 4.8, Ubuntu 16.04, compile process: qmake -project, qmake, make. Using .ui file generated with Qt designer, someLabel comes from the generated ui_...h file and myDialog has a is-a relationship with the generated .h file and QDialog. func.generate_str() comes from a local #include "..." and instance func. Every other parts of the program works successfully.


Solution

  • You have two problems:

    1. Your label is not updated as the main thread can't get back to the event loop before it enters the generate_str() function.

    You could hack around this by using QApplication::processEvents() after changing the label

    1. You have a function call that takes between 5 and 10 seconds running on the main thread in a GUI program, meaning your application will be "frozen" for that duration.

    For that problem you can either consider running the function concurrently, e.g. with a thread, or spitting it in many smaller steps, letting the main thread do its main work (event processing) while it walks through the steps one-by-one