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

问题描述 投票:2回答:2

我试图使用QTimer的超时来关闭QDialog。

到目前为止,我试图这样做:

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

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

但是当触发超时并执行close插槽时,不会退出eventloop。与reject插槽相同的行为。我知道done插槽应该有预期的行为,但因为它需要一个额外的参数(int r),它不能直接连接到timeout()信号。

当然,我可以“转发”timeout信号以提供缺失的参数,但还有另一种更直接的方法吗?

谢谢。

c++ qt
2个回答
2
投票

dlg.exec();是一个同步,他回答接受或拒绝的答案。

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

在Dialog类中使用QTimer的一种方法:

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

或者不要使用dialog.exec();使用dialog.show();如果你想要对话框让它成为你可以使用的模态:

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

2
投票

我建议给对话框自己的计时器(即在切换对话框之前在本地实例化QTimer):

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

由于OP担心他们的注释,如果定时器超时信号已经连接到其他一些插槽,在连接对话框关闭之前,并且在该插槽中调用QTimer::disconnect(),则永远不会调用对话框关闭插槽。

© www.soinside.com 2019 - 2024. All rights reserved.