Schulp
Schulp

Reputation: 73

Qt show() executed after function

I would like to show a label and execute a function after displaying the label. Unfortunately, the label is always displayed after the function is executed.

void MainWindow::showLabel(){
    myLabel->show();
    doSomething();
}

void MainWindow::doSomething(){
    QThread::msleep(3000);
    myLabel->hide();
}

So, when i execute my code, the programm waits for three seconds and does show me an empty window afterwards (since it directly hides the label before even showing it; if I comment the hide function, the label is shown after waiting three seconds). What I've tried to do is modifying the showEvent like this:

void MainWindow::showEvent(QShowEvent *event) {
    QMainWindow::showEvent(event);
    doSomething();
}

Am I doing something wrong by modifying the method or is there any other way to show the label before executing the followed function?

Upvotes: 2

Views: 412

Answers (2)

Konstantin T.
Konstantin T.

Reputation: 1013

QThread::msleep(3000); is blocking the main thread where event loop is processed. So it prevent to show myLabel until sleep time is end. The solution is either to use QTimer as vahancho recomended or call event loop processing manualy by calling QEventLoop::exec() after myLabel->show();.

Upvotes: 0

vahancho
vahancho

Reputation: 21250

I would solve your problem in the following way:

void MainWindow::showLabel()
{
    myLabel->show();
    // Wait for 3sec. and hide the label.
    QTimer::singleShot(3000, myLabel, SLOT(hide()));;
}

i.e. you don't need the second function and to block the current thread with QThread::msleep(), which is the reason why your label appears after the timeout is fired.

Update

If you need to do more than just hiding a label, define a slot and call it like:

void MainWindow::showLabel()
{
    myLabel->show();
    // Wait for 3sec. and call a slot.
    QTimer::singleShot(3000, this, SLOT(doSomething()));
}

// This is a slot
void MainWindow::doSomething()
{
    myLabel->hide();
    [..]
    // some more stuff
}

Upvotes: 1

Related Questions