QQmlApplicationEngine not emitting warnings signal

2019-08-02 12:20发布

问题:

I am loading a QML file in PyQt application and I would like to display error and warning messages in case QML file is not valid. QQmlApplicationEngine should emit warnings signal in that case, but that doesn't appear to happen. In code below, if QML file contains errors, it is not loaded but display_warnings slot is never called. What am I doing wrong? PyQt version is 5.9.

# -*- coding: utf-8 -*-
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine

def display_warnings(warnings):
    pass # Process warnings

if __name__ == '__main__':
    import os
    import sys
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()
    engine.warnings.connect(display_warnings)
    qml_filename = os.path.join(os.path.dirname(__file__), 'MainWindow.qml')
    engine.load(qml_filename)
    sys.exit(app.exec_())

回答1:

I don't know how does it work in Python but in C++ that works well ie. reports about all QML errors:

QQmlApplicationEngine engine;
QObject::connect(&engine, &QQmlApplicationEngine::warnings, [=] (const QList<QQmlError> &warnings) {
    foreach (const QQmlError &error, warnings) {
        qWarning() << "warning: " << error.toString();
    }
});

Note that in this case the type of connection is Qt::DirectConnection. In fact all the errors are the same as console ones.

In my test the error this code error anchors.centerIn: parnt will be reported twice, one error by console and one error by warnings signal handler:

warning: "qrc:/main.qml:13: ReferenceError: parnt is not defined"

qrc:/main.qml:13: ReferenceError: parnt is not defined

So you should check if your QML code contains error at all and also check if your console produces some warnings.