PySide 如何在 python 控制台中查看 QML 错误?

PySide How to see QML errors in python console?

我有以下代码:

if __name__ == '__main__':
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    engine.load('./QML/main.qml')

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())

如您所见,如果“engine.load”失败,我只会看到“-1”退出代码,而不会详细说明失败原因和发生的错误。如何在 python 控制台中打印 QML 错误?

当使用 QQuickView 而不是 QQmlApplicationEngine 时,有一个解决方法,并且在这个 中有描述,但是,我想知道 QQmlApplicationEngine 是否可以实现类似的东西?

如果你想知道使用 QQmlApplicationEngine 时的错误消息,你应该使用 warnings 信号,但它似乎不起作用,所以解决方法是使用 qInstallMessageHandler 来获取消息Qt 给出。

import os
import sys
from PySide2 import QtCore, QtGui, QtQml

def qt_message_handler(mode, context, message):
    if mode == QtCore.QtInfoMsg:
        mode = 'Info'
    elif mode == QtCore.QtWarningMsg:
        mode = 'Warning'
    elif mode == QtCore.QtCriticalMsg:
        mode = 'critical'
    elif mode == QtCore.QtFatalMsg:
        mode = 'fatal'
    else:
        mode = 'Debug'
    print("%s: %s (%s:%d, %s)" % (mode, message, context.file, context.line, context.file))


if __name__ == '__main__':
    os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material"
    QtCore.qInstallMessageHandler(qt_message_handler)
    app = QtGui.QGuiApplication(sys.argv)
    engine = QtQml.QQmlApplicationEngine()
    qml_filename = os.path.join(os.path.dirname(__file__), 'QML/main.qml')
    engine.load(QtCore.QUrl.fromLocalFile(qml_filename))
    if not engine.rootObjects():
        sys.exit(-1)
    sys.exit(app.exec_())