2

When I create slots by name with this kind of syntax:

on_<widgetname>_clicked();

If I want to display a particular widget Inside this function it won't display until it reaches the end of the function.

That is, when I create the following function:

void MyWindow::on_myWidget_clicked()
{
    // the stackedWidget is composed of:
    // page_1 with myWidget
    // page_2 

    ui->stackedWidget->setCurrentWidget(ui->page_2);
    waitSomeTime();
}

whith

void MyWindow::waitSomeTime()
{
    QThread t;
    t.sleep(2); // Wait 2 seconds to see which line is going to be executed first.
}

When the code is launched, the 2 seconds elapsed first and only then the page_2 is displayed.

Why the line

ui->stackedWidget->setCurrentWidget(ui->page_2);

is not executed first?

scopchanov
  • 7,966
  • 10
  • 40
  • 68
Sebastien
  • 21
  • 1
  • The events are processed once the execution returns to the main event loop. Try adding `QApplication::processEvents();` between `ui->stackedWidget->setCurrentWidget(ui->page_2);` and `waitSomeTime();`. – scopchanov Sep 27 '18 at 16:48
  • 1
    Thank you, this works perfectly. Also the answer below is very interesting since I used the QThread class in my program. – Sebastien Sep 28 '18 at 08:15

1 Answers1

1

void QThread::sleep(unsigned long secs) [static]
Forces the current thread to sleep for secs seconds.

the waitSomeTime function make the main (current) thread sleep, so it will block everything, even GUI processing. As @scopchanov commented, you could use QApplication::processEvents(), which will process the event of setCurrentWidget. However, the whole GUI will still be blocked until the sleep is done, which means, that the widget will be shown, but won't be able to handle any operation.

So it would be better to use QTimer::singleShot if you want to delay the work, or start another new QThread to do it.

scopchanov
  • 7,966
  • 10
  • 40
  • 68
JustWe
  • 4,250
  • 3
  • 39
  • 90