Pamba
Pamba

Reputation: 822

How to use QTimer singleShot with QEventLoop in Qt

I need to open QDialog by using QTimer singleShot and wait for a status flag. If this variable is true then continue.

This is my code

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();
}

In NewGUI constructor StatusFlag is set to 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");  
}

Current Output is

Enter 
OpenWindow

Expected Output is

Enter 
Exit
OpenWindow
Do something

If i comment the line

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

Then the output is

Enter 
Exit.. still continuing

Do you have any suggestion?

Upvotes: 1

Views: 3867

Answers (1)

Lahiru Chandima
Lahiru Chandima

Reputation: 24068

In your code, gui->exec(); starts a new local event loop so you never come out of OpenWindow(). So your while loop will block in mWait(1); until you close the dialog.

Instead of setting a flag, you can emit a signal in the NewGUI constructor to which you can connect a slot of MainWindow. You can do whatever the work you need to do in this slot.

Upvotes: 1

Related Questions