QML:当QApplication退出时,关闭所有QWidget
QML: Close all QWidgets when QApplication is exited
我有一个Qt程序,它使用QApplication作为主窗口,还可能产生许多QMessageBox小部件。当主QApplication窗口退出时,我需要关闭所有这些QMessageBox对话框。然而,我无法使用任何正常的回调,因为QMessageBox似乎阻止了onDestruction()信号。当我单击X退出QApplication时,它的窗口会消失,但只有在退出最后一个QMessageBox时才会触发onDestruction()符号。请告诉我做这件事的正确方法。
编辑:
这是我的主要.cpp:
int main(int argc, char* argv[]) {
QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
Application app(argc, argv);
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("applicationVersion", VER_FILEVERSION_STR);
engine.rootContext()->setContextProperty("applicationDirPath", QGuiApplication::applicationDirPath());
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
int retval = app.exec();
qInstallMessageHandler(0);
return retval;
}
下面是我如何实例化一个QMessageBox:
QMessageBox* errorD = new QMessageBox();
errorD->setStandardButtons(QMessageBox::Ok);
errorD->setDefaultButton(QMessageBox::Ok);
errorD->setModal(false);
errorD->setWindowTitle(title);
errorD->setText(msg);
// We reset when closed
QObject::connect(errorD, &QMessageBox::destroyed, [=]() { printf("QMBox destroyed.");});
errorD->raise();
errorD->activateWindow();
errorD->show();
QApplication::processEvents();
一个可能的解决方案是创建一个Helper来调用关闭小部件的函数,这应该在onClosing:中调用
main.cpp
class Helper : public QObject
{
Q_OBJECT
QWidgetList widgets;
public:
Q_INVOKABLE void closeAllWidgets(){
for(QWidget *w: widgets)
w->close();
}
void addWidget(QWidget *w){
widgets<<w;
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QQmlApplicationEngine engine;
Helper helper;
engine.rootContext()->setContextProperty("helper", &helper);
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
for(int i=1; i < 5; i++){
QMessageBox* errorD = new QMessageBox();
helper.addWidget(errorD);
[...]
main.qml
import QtQuick 2.7
import QtQuick.Controls 2.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
onClosing: helper.closeAllWidgets();
}
在下面的链接中,您将找到一个示例
相关文章:
- 如何在QT Creator上将QWidget声明为继承类的对象
- QWidget::p aintEngine:不应再在 QTreeWidget 派生类中调用
- 将一个 QWidget 链接到另一个新创建的 QWidget
- 为什么 isVisible 在 QWidget 孩子中不起作用
- 如何声明全局QWidget?
- QWidget UI 在使用 QQuickWidget 时冻结
- "(QWidget* pobj=0)"和"(QWidget* pwgt/*=0/)&quo
- qt QWidget::closeEvent link issue
- 如何在QMdiSubWindow关闭后删除QWidget
- 从插槽调用 QApplication::p rocessEvents 会导致再次调用同一插槽
- 如何在QGraphicsView中移动QWidget?
- 如何在QApplication中应用QLibraryInfo中加载的库和插件配置
- 如何为应用程序中的某些按钮重置QApplication::styleSheet?
- QPainter的QWidget滚动条
- QApplication::p rocessEvents 在不同的线程上
- 在类中创建 QWidget
- QML:当QApplication退出时,关闭所有QWidget
- QWidget:必须在 VS 发布模式下的 QPaintDevice 之前构造 QApplication
- 带有QWT运行时错误的QT:QWIDGET:必须在Qwidget之前构造Qapplication
- "Must construct a QApplication before a QWidget"