PySide 如何在 python 控制台中查看 QML 错误? [英] PySide How to see QML errors in python console?

查看:71
本文介绍了PySide 如何在 python 控制台中查看 QML 错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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 错误?

As you can see, if `engine.load' fails all I'll see is a '-1' exit code, without any elaboration on why it failed and what the error happened. How can I print the QML error in the python console?

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

There was a walkaround for this with when using QQuickView instead of QQmlApplicationEngine and is described in this post, however, I wonder if the something similar can be achieved for QQmlApplicationEngine?

推荐答案

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

If you want to know the error message when using QQmlApplicationEngine you should use the warnings signal but it does not seem to work, so a workaround is to use qInstallMessageHandler to get the messages that Qt gives.

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_())

这篇关于PySide 如何在 python 控制台中查看 QML 错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆