QML:当QApplication退出时,关闭所有QWidget

QML: Close all QWidgets when QApplication is exited

本文关键字:QWidget QApplication 退出 QML      更新时间:2023-10-16

我有一个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();
}

在下面的链接中,您将找到一个示例