如何在Qt中使用QTimer singleShot和QEventLoop

时间:2015-02-27 04:48:04

标签: qt qdialog qtimer qeventloop

我需要使用QTimer singleShot打开QDialog并等待状态标志。如果此变量为true,则继续。

这是我的代码

  

StatusFlag = FALSE;

void MainWindow::OpenWindow()
{
   qDebug("OpenWindow"); 
   NewGUI *gui=new NewGUI();
   gui->setModal(true);
   gui->exec();
}
void MainWindow::mWait(ulong milliSeconds)
{
    QEventLoop loop;
    QTimer::singleShot(milliSeconds, &loop, SLOT(quit()));
    loop.exec();
}
  

在NewGUI构造函数中,StatusFlag设置为TRUE

QTimer::singleShot(0, this, SLOT(OpenWindow()));
while(StatusFlag == FALSE)
{
   //Wait until StatusFlag is TRUE.
   qDebug("Enter"); 
   mWait(1);
   qDebug("Exit");         
}

if(StatusFlag == TRUE)
{
   //Do something
   qDebug("Do something");  
}

当前输出

Enter 
OpenWindow

预期输出

Enter 
Exit
OpenWindow
Do something

如果我评论该行

  

QTimer :: singleShot(0,this,SLOT(OpenWindow()));

然后输出

Enter 
Exit.. still continuing

你有什么建议吗?

1 个答案:

答案 0 :(得分:0)

在您的代码中,gui->exec();启动一个新的本地事件循环,因此您永远不会离开OpenWindow()。因此,在关闭对话框之前,您的while循环将在mWait(1);中阻止。

您可以在NewGUI构造函数中发出一个可以连接MainWindow插槽的信号,而不是设置一个标志。你可以在这个插槽中做任何你需要做的工作。

相关问题