捕获 QML 错误消息 [英] Catch QML error message

查看:30
本文介绍了捕获 QML 错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Qt.createQmlObject() 从文件创建一个 QML 对象.在文件损坏的情况下,QML 输出如下所示的消息:

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():创建对象失败:qrc:/graphics/inline:5:2: 预期令牌}'`

我想捕捉消息以告诉用户他的文件已损坏.

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

我正在尝试使用 Qt.createQmlObject() 中提供的第三个参数,但我不明白它是如何工作的.wiki 很好地描述了这个函数,但没有给出任何利用它的例子:

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

第三个参数是一个字符串,用作 Qt Creator IDE 中错误报告中的文件名.例如,如果在加载的 QML 字符串中遇到错误,则在文件名名称的文件中将其报告为错误.在调用文件名作为字符串时,必须用双引号括起来.

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.

推荐答案

你需要像这样使用try-catch"块:

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)
        }
    }

这在官方文档中有所描述

这篇关于捕获 QML 错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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