QML applications do not exit when using QEventLoop. The window will open just fine, but when the application window is closed, the program does not exit. It also doesn't fire any events like QGuiApplication::lastWindowClosed
or QQmlApplicationEngine::destroyed
. Try running the example below to see what I mean. You have to hit CTRL-C for it to exit.
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QEventLoop>
#include <string>
const std::string qmlStr = R"(
import QtQuick 2.15
import QtQuick.Controls 2.15
ApplicationWindow {
title: "My Application"
width: 640
height: 480
visible: true
Button {
text: "Push Me"
anchors.centerIn: parent
}
})";
int main(int argc, char** argv) {
auto app = new QGuiApplication(argc, argv);
auto m_engine = new QQmlApplicationEngine();
m_engine->loadData(QByteArray::fromStdString(qmlStr));
QObject::connect(QGuiApplication::instance(), &QGuiApplication::aboutToQuit, []() {
qDebug("aboutToQuit");
});
QObject::connect(qGuiApp, &QGuiApplication::lastWindowClosed, []() {
qDebug("lastWindowClosed");
});
QObject::connect(m_engine, &QQmlApplicationEngine::destroyed, []() {
qDebug("Destroyed");
});
QEventLoop loop;
while (loop.isRunning()) {
loop.processEvents(QEventLoop::AllEvents | QEventLoop::WaitForMoreEvents | QEventLoop::EventLoopExec);
}
// loop.exec() doesn't work either.
return 0;
}
Is there any way to use QEventLoop as the main event loop in a QML application?
NOTE: Yes, I do need to use QEventLoop as the main event loop. qGuiApp->exec()
works, but it's not what I need.