简体   繁体   中英

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.

UI operations usually aren't completed synchronously. Try scheduling func.generate_str() in the next iteration of the event loop or even a little later. Something like this might work:

QTimer::singleShot(0, [&]{ func.generate_str(); });

0 is 0 milliseconds which just means next run loop iteration. The funny syntax of the second argument is a C++ lambda (since C++11).

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, eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM