【问题标题】:How to use QTimer singleShot with QEventLoop in Qt如何在 Qt 中使用 QTimer singleShot 和 QEventLoop
【发布时间】:2015-02-27 04:48:03
【问题描述】:

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

这是我的代码

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

你有什么建议吗?

【问题讨论】:

  • 不要在您的 GUI 线程中使用任何类型的等待机制。它是事件驱动的编程。充分利用这一点。使用信号和槽。

标签: qt qdialog qtimer qeventloop


【解决方案1】:

在您的代码中,gui->exec(); 启动了一个新的本地事件循环,因此您永远不会退出 OpenWindow()。因此,您的 while 循环将在 mWait(1); 中阻塞,直到您关闭对话框。

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

【讨论】:

  • 谢谢你的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 1970-01-01
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
相关资源
最近更新 更多