QT:将异常从C 投掷到QML引擎

Qt: Throwing an exception from C++ to QML engine

本文关键字:QML 引擎 异常 QT      更新时间:2023-10-16

在调用C++JavaScript函数中编写的Q_INVOKABLE方法中的CC_3函数时,您如何抛出异常?该方法由< MyApp >类型的对象所有,并注册了qmlRegisterType()

例如,我有以下QML代码:

TextField {
    id: fld_recipient
    onEditingFinished: {
        try {
            var identity=myapp.identities.current_Identity;
            var company=identity.companies.current_Company;
            myapp.lookup_email(identity.identity_id,company.company_id,fld_recipient.text)
        } catch(e) {
            console.log(e);
        }
    }
}

在这里,方法myApp :: Lookup_email()转到服务器并搜索匹配的电子邮件地址。这个过程可以通过大量错误阻止,我希望catch()语句显示该错误。

这是如何在C 方面完成的?有点这样:

void MyApp::lookup_email(int identity_id,int company_id,QString email) {
    ....
    error_code=server->lookup_email(identity_id,company_id,email);
    if (error_code) { /// throw an exception to QML engine, 
         ????? <= what goes here ?
    }
}

qml不应包括任何业务逻辑,而应显示任何结果。如果您的应用程序运行到一个例外状态,请捕获业务逻辑中的异常,并向用户介绍结果/新状态。

如果您假设您的(UI)代码将使用不完整的数据来调用您,则应忽略它。或在调试级别上使用断言。

以下代码段显示您如何使用QQmlEngine::throwError

#ifndef __MathTools__
#define __MathTools__
#include <QObject>
#include <QQmlEngine>
#include <QString>
class MathTools : public QObject
{
    Q_OBJECT
public:
    MathTools(QObject* parent = nullptr) : QObject(parent) { }
    Q_INVOKABLE double divide(double a, double b)
    {
        if (b == 0.0)
        {
            qmlEngine(this)->throwError(tr("Division by zero error"));
            return 0.0;
        }
        return a / b;
    }
};
#endif

在QML中使用时:

    ColumnLayout {
        TextField { id: first; text: "1" }
        TextField { id: second; text: "0" }
        Button {
            text: qsTr("Divide")
            onClicked: {
                try {
                    const f = parseFloat(first.text);
                    const s = parseFloat(second.text);
                    result.text = mathTools.divide(f, s);
                } catch (err) {
                    result.text = err.message;
                }
            }
        }
        TextField { id: result }
    }```
I see a QML/Javascript error being thrown when attempting to divide by zero:

qrc:/main.qml:58:错误:零错误

划分

Reference:
 - https://doc.qt.io/qt-5/qjsengine.html#throwError