我想显示一个标签并在显示标签后执行一个函数。不幸的是,标签总是在执行功能后显示。void MainWindow::showLabel(){
myLabel->show();
doSomething();
}
void MainWindow::doSomething(){
QThread::msleep(3000);
myLabel->hide();
}
因此,当我执行我的代码时,程序等待三秒钟,然后确实向我显示一个空窗口(因为它在显示之前就直接隐藏了标签;如果我注释了hide函数,则在等待三秒钟后才显示标签) 。
我试图做的就是像这样修改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
}
关于c++ - Qt show()在函数后执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60524172/