如何从 QML 关闭 Pyqt5 程序?

How to close Pyqt5 program from QML?

我最初在 Qt Creator 中使用 C++ 后端启动了一个项目,但后来将其切换为使用 PyQt5。我有一个 main.qml,当我按下一个名为 Exit 的按钮时,我会调用 Qt.quit()

但是,我收到 General Message 说明:Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.

我的问题是,如何接收和处理这个信号?

代码:

main.py:

import sys
import PyQt5

from PyQt5 import QtCore
from PyQt5 import QtGui
from PyQt5 import QtQml
from PyQt5.QtCore import QObject pyqtSignal


class DestinyManager,(QtGui.QGuiApplication):
    """the app self"""
    def __init__(self, argv):
        super(DestinyManager, self).__init__(argv)

    # Define a new signal called 'trigger' that has no arguments.
    trigger = pyqtSignal()

    def connect_and_emit_trigger(self):
        # Connect the trigger signal to a slot.
        self.trigger.connect(self.handle_trigger)
        self.menuItem_Exit.clicked.connect(self.close)
        # Emit the signal.
        self.trigger.emit()

    def handle_trigger(self):
        # Show that the slot has been called.
        print("trigger signal received")

def main(argv):
    app = DestinyManager(sys.argv)
    engine = QtQml.QQmlEngine(app)
    component = QtQml.QQmlComponent(engine)
    component.loadUrl(QtCore.QUrl("exit.qml"))
    topLevel = component.create()
    if topLevel is not None:
        topLevel.show()
    else:
        for err in component.errors():
            print(err.toString())
    app.exec()

if __name__ == '__main__':
    QObject,main(sys.argv)

Exit.qml:

import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2

Window {

    Button {
    id: btn_Exit
    text: "Exit"

    onClicked: Qt.quit();

    }
}

python 脚本中存在一些语法错误,但忽略这些错误,代码可以像这样工作:

    def main(argv):
        app = DestinyManager(sys.argv)
        engine = QtQml.QQmlEngine(app)
        engine.quit.connect(app.quit)
        ...

也就是说,您只需将 qml quit 信号连接到 python 脚本中的适当插槽。