How can I set text of label when a function is running?

user2362956 picture user2362956 · Mar 28, 2014 · Viewed 16.7k times · Source

I want to set the text of a label on main window when a function in code is running. But the label does not change until the function ends.

for (int i = 0; i < files.size(); ++i) {

    ui->label->setText(files[i]);
    myfoo();

}

Answer

TheDarkKnight picture TheDarkKnight · Mar 28, 2014

The reason the label isn't seen to update is that the main thread, which updates the GUI, is busy in your for loop and not getting time to process events which, amongst other things, causes the GUI widgets to be redrawn.

While you could use QApplication::processEvents, this is not ideal, especially if many events are received during the processing of your function.

The proper way to handle this is to create a separate thread (QThread) and an object, derived from QObject, which will do work while sending messages to the main (GUI) thread to update the label.

Rather than repeating the code, I suggest you read this article on how to use QThread properly. It's not that difficult.

Then you would change your function, which is now in the object on the 2nd thread, to something like this: -

for (int i = 0; i < files.size(); ++i) 
{
    // calling UpdateLabel signal, which connects to an object on the main thread
    UpdateLabel(files[i]);        
    myfoo();  
}

Assuming the signal from the Worker class has been connected to a slot in an object on the main thread, such as QMainWindow, you'd receive the text in the slot and update the label: -

void QMainWindow::UpdateLabel(const QString text)
{
    ui->label->setText(text);
}