1

I have a problem with updating QLabel text two times serially in the following function:

void MainWindow::on_button_clicked(){ 
   ui->label->setText("Training");
   object->training();
   ui->label->setText("Training finished");
}

The first call of setText() never changes label's text. What's wrong with this example?

Mat
  • 202,337
  • 40
  • 393
  • 406
qloq
  • 689
  • 1
  • 5
  • 15
  • 1
    See also: http://stackoverflow.com/questions/1386043/how-to-make-qt-work-when-main-thread-is-busy – Mat Jan 11 '15 at 06:54

1 Answers1

3

This slot call is running on the GUI thread. And when you get to the end of the function, is when the GUI has a chance to do updates.

You can force an update with:

ui->label->update();  // queues up an update event
qApp->processEvents(); // processes the update event

// start some longer code snippet
// ...

And also note that qApp is short for QApplication::instance(). Include <QApplication> to be able to use it.

UPDATE: QtConcurrent and QThread stuff

But like it says in @Mat's comment and referenced answer... this may be bandaid solution for something that really should be launched in a QThread or with a QFuture or some other QtConcurrent class. Thread Synchronization and related topics have a learning curve, so be careful when starting it, if you haven't done that before.

I liked how it was done here: http://qt-project.org/wiki/Progress-bar

Hope that helps.

phyatt
  • 18,472
  • 5
  • 61
  • 80