简体   繁体   English

C ++ Qt保留操作顺序:在继续之前更新QLabel

[英]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. 在代码的一部分中(如下所示),在下一行的generate函数完成工作之后 ,标签会用文本更新。 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. 我仍在学习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. 到目前为止,我的猜测一直是Qt的线程正在做一些有趣的事情,但是我不确定如何获得期望的结果。

Using Qt 4.8, Ubuntu 16.04, compile process: qmake -project , qmake , make . 使用Qt 4.8,Ubuntu 16.04编译过程: qmake -projectqmakemake 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. 使用Qt designer生成的.ui文件,someLabel来自生成的ui _... h文件,而myDialog与生成的.h文件和QDialog具有is-a关系。 func.generate_str() comes from a local #include "..." and instance func. func.generate_str()来自本地#include“ ...”和实例func。 Every other parts of the program works successfully. 该程序的所有其他部分都可以成功运行。

UI operations usually aren't completed synchronously. UI操作通常不会同步完成。 Try scheduling func.generate_str() in the next iteration of the event loop or even a little later. 尝试在事件循环的下一次迭代中甚至稍后进行调度func.generate_str() Something like this might work: 这样的事情可能会起作用:

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

0 is 0 milliseconds which just means next run loop iteration. 0为0毫秒,仅表示下一次运行循环迭代。 The funny syntax of the second argument is a C++ lambda (since C++11). 第二个参数的有趣语法是C ++ lambda(自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. 您的标签未更新,因为主线程在进入generate_str()函数之前无法返回事件循环。

You could hack around this by using QApplication::processEvents() after changing the label 您可以在更改标签后使用QApplication::processEvents()来解决此问题

  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. 在GUI程序的主线程上运行的函数调用需要5到10秒钟,这意味着该应用程序将在此期间被“冻结”。

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 对于该问题,您可以考虑同时运行该函数(例如,使用线程),也可以分步进行一些较小的步骤,让主线程在其逐步执行步骤的同时完成其主要工作(事件处理)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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