简体   繁体   中英

How to close and exit a QDialog shown with exec() after a timeout?

I am trying to close a QDialog using a timeout from a QTimer.

So far, i have tried to do this :

QDialog dlg;
.. 
..
myTimer.start(60000); // 60 s
connect(&myTimer, SIGNAL(timeout()),
        &dlg, SLOT(close())));

dlg.exec();
qWarning() << "---timer expired or key pressed--";

But when timeout is triggered and the close slot executed the eventloop is not exited. Same behavior with reject slot. I know the done slot should have the expected behavior but as it needs an extra argument ( int r ), it cannot be directly connected to the timeout() signal.

Of course, i can "relay" the timeout signal to provide the missing argument but is there another more straightforward way to do it ?

Thank you.

dlg.exec(); Is a synchronic, He returns the answer accepted or rejected.

void MainWindow::btnClicked() {
    Dialog *dialog = new Dialog();
    dialog.exec();
    qDebug() << "test"; 
    // while dialog not destroyed (rejected, accepted) Print will not happen never. 
}

One way you can use QTimer in your Dialog class:

Dialog::dialog(...) {
    //constructor
    QTimer::singleShot(60000, this, SLOT(close()));
}

or do not use dialog.exec(); use dialog.show(); if you want dialog let it be modality you can use:

void MainWindow::btnClicked() {
    Dialog *dialog = new Dialog();
    dialog->setModal(true);
    dialog->show();
    qDebug() << "test"; //The "test" will be printed, and you can use QTimer :))
 }

I suggest to give the dialog its own timer (ie instantiate a QTimer locally, before excuting the dialog):

QTimer dlg_timer;
dlg_timer.start(60000); // 60 s
connect(&dlg_timer, SIGNAL(timeout()), &dlg, SLOT(close()));
dlg.exec();
dlg_timer.stop();

As the OP fears in their comment, if the timer timeout signal has been connected to some other slot, before connection with dialog close, and in that slot QTimer::disconnect() is called, the dialog close slot will never be called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM