Catch QML error message

孤街醉人 提交于 2019-12-08 03:23:49

问题


I'm using Qt.createQmlObject() to create a QML object from a file. In the case the file is corrupted, QML outputs a message that looks like this:

Qt.createQmlObject(): failed to create object: qrc:/graphics/inline:5:2: Expected token}'`

I'd like to catch the message in order to tell the user that his file is corrupted.

I am trying to use the third argument provided in the Qt.createQmlObject() but I don't understand how it works. The wiki describes the function quite well but doesn't give any example exploiting it:

https://wiki.qt.io/QML_Dynamic_Objects#Creation_of_Dynamic_QML_Objects

The third argument is a string used as a file name in error reporting in the Qt Creator IDE. For example if an error is encountered in loaded QML string it is reported as one in the file with filename name. In invocation filename as a string has to be surrounded by double quotes.


回答1:


You need to use "try-catch" block like this:

try {
        var newObject = Qt.createQmlObject('import QtQuick 2.0; Rectangle11 {color: "red"; width: 20; height: 20}',
                                       this,
                                       "dynamicSnippet1");
    } catch (error) {
        print ("Error loading QML : ")
        for (var i = 0; i < error.qmlErrors.length; i++) {
            print("lineNumber: " + error.qmlErrors[i].lineNumber)
            print("columnNumber: " + error.qmlErrors[i].columnNumber)
            print("fileName: " + error.qmlErrors[i].fileName)
            print("message: " + error.qmlErrors[i].message)
        }
    }

This is described in the official documentation



来源:https://stackoverflow.com/questions/38049330/catch-qml-error-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!