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.
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