如何在使用 Qt.quit() 而不是整个 QGuiApplication 时只退出当前的 QQmlApplicationEngine?

How to only quit current QQmlApplicationEngine while using Qt.quit() instead of the whole QGuiApplication?

我编写这些代码是为了更好地理解我的问题:

main.py

from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine

app = QGuiApplication([])

engine1 = QQmlApplicationEngine()
engine1.load("hello.qml")

engine2 = QQmlApplicationEngine()
engine2.load("hello.qml")

app.exec_()

hello.qml

import QtQuick.Window 2.14
import QtQuick.Controls 2.15

Window {
    visible: true

    Button {
        text: "Button"
        onPressed: Qt.quit()
    }

}

按下按钮后,windows都关闭了。这不是我所期望的。

说明

这是 the docs 中指出的默认行为:

List of configuration changes from a default QQmlEngine:

  • Connecting Qt.quit() to QCoreApplication::quit()
  • Automatically loads translation files from an i18n directory adjacent to the main QML file.
    • Translation files must have "qml_" prefix e.g. qml_ja_JP.qm.
  • Translations are reloaded when the QJSEngine::uiLanguage / Qt.uiLanguage property is changed.
  • Automatically sets an incubation controller if the scene contains a QQuickWindow.
  • Automatically sets a QQmlFileSelector as the url interceptor, applying file selectors to all QML files and assets.

The engine behavior can be further tweaked by using the inherited methods from QQmlEngine.

(强调我的)

所以有两种选择:

  • 删除连接:

    for engine in (engine1, engine2):
        engine.disconnect()
    
  • 使用 QQmlEngine 而不是 QQmlApplicationEngine。


正确的解决方案

转到后台问题,即如何在用户按下按钮时关闭 window,因此您不应使用 window 的 Qt.quit() but instead invoke the close() 方法:

import QtQuick.Window 2.14
import QtQuick.Controls 2.15

Window {
    <b>id: root</b>
    visible: true

    Button {
        text: "Button"
        onPressed: <b>root.close()</b>
    }
}

如果您想退出整个应用程序,您应该只使用 Qt.quit()