首页 > 解决方案 > Qt 错误:发出信号 QQmlEngine::quit(),但没有连接接收器来处理它

问题描述

我写了一个示例 PySide2/QML 代码,但我无法退出程序。

PySide2 代码:

import sys
from PySide2.QtGui import QGuiApplication
from PySide2.QtCore import QCoreApplication, Qt, QUrl
from PySide2.QtQuick import QQuickView

QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QGuiApplication(sys.argv)

view = QQuickView(QUrl('view.qml'))
view.show()

sys.exit(app.exec_())

QML 代码:

import QtQuick 2.3
import QtQuick.Controls 1.4

Rectangle {
    width: 200
    height: 200
    color: "green"

    Button {
        text: "Hello World"
        anchors.centerIn: parent
        onClicked: Qt.quit()
    }
}

当我单击按钮时,在命令提示符下运行代码会给我一个错误:

Signal QQmlEngine::quit() emitted, but no receivers connected to handle it.

搜索网络我意识到其他人也有类似的问题,因为 Qt 的新语法。但这都是C++,我不明白。

有谁知道如何在 Python 中解决这个问题?

标签: pythonpython-3.xqmlpyside2

解决方案


文档说明:

退出()

这个函数导致QQmlEngine::quit()信号被发出。在使用 qmlscene 进行原型设计时,这会导致启动器应用程序退出;要在调用此方法时退出 C++ 应用程序,请将QQmlEngine::quit()信号连接到 QCoreApplication::quit()槽。

明确指出必须将QQuickView的QQmlEngine::quit()连接到QCoreApplication::quit():

import os
import sys

from PySide2.QtCore import QCoreApplication, Qt, QUrl
from PySide2.QtGui import QGuiApplication
from PySide2.QtQuick import QQuickView

if __name__ == "__main__":
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QGuiApplication(sys.argv)

    current_dir = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(current_dir, "view.qml")
    view = QQuickView(QUrl.fromLocalFile(filename))
    view.engine().quit.connect(QCoreApplication.quit)  # <---
    view.show()

    sys.exit(app.exec_())

推荐阅读