简体   繁体   English

超时后如何关闭并退出与exec()一起显示的QDialog?

[英]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. 我正在尝试使用QTimer中的超时来关闭QDialog。

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. 但是当触发超时并执行close插槽时,不会退出事件循环。 Same behavior with reject slot. reject槽的行为相同。 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. 我知道done插槽应该具有预期的行为,但是由于它需要一个额外的参数( int r ),因此它不能直接连接到timeout()信号。

Of course, i can "relay" the timeout signal to provide the missing argument but is there another more straightforward way to do it ? 当然,我可以“中继” timeout信号以提供缺少的参数,但是还有另一种更直接的方法吗?

Thank you. 谢谢。

dlg.exec(); 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类中使用QTimer的一种方法:

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

or do not use dialog.exec(); 或者不使用dialog.exec(); use dialog.show(); 使用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):

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. 正如OP在其评论中所担心的那样,如果在与对话框关闭连接之前将计时器超时信号连接到其他某个插槽,并在该插槽中调用QTimer::disconnect() ,则将永远不会调用对话框关闭插槽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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