QML 应用程序在使用 QEventLoop 时不会退出。窗口会正常打开,但是当应用程序窗口关闭时,程序不会退出。它也不会触发任何事件,例如QGuiApplication::lastWindowClosed
or QQmlApplicationEngine::destroyed
。尝试运行下面的示例以了解我的意思。您必须按 CTRL-C 才能退出。
#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;
}
有没有办法在 QML 应用程序中使用 QEventLoop 作为主事件循环?
注意:是的,我确实需要使用 QEventLoop 作为主事件循环。qGuiApp->exec()
有效,但这不是我需要的。