setCurrentWidget applied after the end of a clicked signal

592 views Asked by At

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?

1

There are 1 answers

0
JustWe On

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.