Qt show() 在函数之后执行

Qt show() executed after function

我想显示标签并在显示标签后执行函数。不幸的是,标签总是在函数执行后显示。

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

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

所以,当我执行我的代码时,程序会等待三秒钟,然后确实显示一个空的 window(因为它甚至在显示标签之前就直接隐藏了标签;如果我评论隐藏功能,等待三秒钟后显示标签)。 我试图做的是像这样修改 showEvent:

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

我是不是修改了方法做错了什么,或者有没有其他方法可以在执行后续函数之前显示标签?

我会通过以下方式解决您的问题:

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

即您不需要第二个函数并使用 QThread::msleep() 阻塞当前线程,这就是您的标签在超时被触发后出现的原因。

更新

如果您需要做的不仅仅是隐藏标签,请定义一个插槽并像这样调用它:

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
}

QThread::msleep(3000); 正在阻塞处理事件循环的主线程。所以它会阻止显示 myLabel 直到睡眠时间结束。解决方案是使用 QTimer 作为 vahancho 推荐或通过在 myLabel->show();[=16 之后调用 QEventLoop::exec() 手动调用事件循环处理=].