【问题标题】:Qt show() executed after functionQt show() 在函数之后执行
【发布时间】:2020-03-04 10:39:58
【问题描述】:

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

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

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

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

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

是我修改方法做错了还是有其他方法在执行后续函数之前显示标签?

【问题讨论】:

    标签: c++ qt show


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 如果我想向 doSomething() 添加更多代码,我该怎么办?
    • 请不要使用 Qt4 风格的语法。使用更安全的:QTimer::singleShot(3000, this, &MainWindow::doSomething)); 它甚至不需要是一个插槽。甚至是函数,您都可以使用 lambda。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-04
      相关资源
      最近更新 更多