问题描述
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDialog dlg;
dlg.exec();
return a.exec();
}
那是我的全部代码,但是当我关闭窗口时,该过程没有退出,似乎是循环a.exec()
中的下落.
That's all my code, but when I close the window, The process isn't exit, it seems that drop in the loop a.exec()
.
推荐答案
通常来说,调用 any exec是一个好主意,除了QCoreApplication::exec()
或QDrag::exec()
之外. exec()
和waitForXxx()
方法的存在是一个诱人的陷阱.这些方法使用起来容易",但是要付出代价却很难跟踪错误.不要使用它们.
Generally speaking, calling any exec is a bad idea, other than QCoreApplication::exec()
or QDrag::exec()
. The presence of exec()
and waitForXxx()
methods is an enticing trap for the unwary. Those methods are "easy" to use, but that ease comes at a price of hard to track bugs. Don't use them.
您应该只显示对话框:
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMessageBox msg;
msg.setText("Hello");
msg.addButton(QMessageBox::Close);
msg.show();
return a.exec();
}
如果希望等待对话框被接受或拒绝,则应使用对话框的clickedButton
插槽. QMessageBox
有一个长期存在的错误,使accepted
和rejected
信号无用:(
If you wish to wait for the dialog to be accepted or rejected, you should use the dialog's clickedButton
slot. QMessageBox
has a long-standing bug that makes the accepted
and rejected
signals useless :(
// https://github.com/KubaO/stackoverflown/tree/master/questions/messagebox-show-25545652
#include <QtGui>
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
#include <QtWidgets>
#endif
#include <functional>
[...]
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMessageBox msg;
msg.setText("Continue?");
msg.addButton(QMessageBox::Yes);
msg.addButton(QMessageBox::No);
auto onClick = [&msg]() {
auto role = msg.buttonRole(msg.clickedButton());
if (role == QMessageBox::NoRole)
QApplication::quit();
if (role == QMessageBox::YesRole) {
auto label = new QLabel("I'm running");
label->setAttribute(Qt::WA_DeleteOnClose);
label->show();
}
};
#if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
QObject::connect(&msg, &QMessageBox::buttonClicked, onClick);
#else
QObject::connect(&msg, SIGNAL(buttonClicked(QAbstractButton*)),
new FunctorSlot{onClick, &msg}, SLOT(call()));
#endif
msg.show();
return app.exec();
}
#include "main.moc"
对于Qt 4,您需要以下帮助程序:
For Qt 4, you need the following helper:
// Qt 4 only
struct FunctorSlot : public QObject {
Q_OBJECT
public:
std::function<void()> callable;
template <typename Fun>
FunctorSlot(Fun && fun, QObject * parent = {}) :
QObject{parent}, callable{std::forward<Fun>(fun)} {}
Q_SLOT void call() {
callable();
}
};
这篇关于QDialog exec()无法退出进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!