QT:将异常从C 投掷到QML引擎
Qt: Throwing an exception from C++ to QML engine
在调用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
相关文章:
- 从C++实例化QML
- 使用CMake创建QML插件
- QT通过C++添加映射QML项目
- 如何在没有信号的情况下从C++执行QML插槽
- 当使用带有VS2019或VSCode的虚幻引擎4.24.2时,我如何修复这些错误的Intellisense错误
- QML按钮点击功能执行顺序
- Unity在虚幻引擎4中的"Vector3.Slerp"等效C++?
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 建议在运行时将带有类实例的列表从c++导入qml
- 如何创建从Maya(或类似程序)到虚幻引擎的自定义数据导出插件
- Qt Quick-如何仅从c++代码与qml属性交互
- 在虚幻引擎中删除NXOpen对象时崩溃
- 如何将带有自定义对象的容器从C++传递到QML
- 引擎节点:未定义的符号:_ZTV6Config
- QML 使用带有参数C++函数
- Agora.io 虚幻引擎插件构建错误
- 最佳做法是从另一个线程访问 qml 中的Q_PROPERTY
- QT:将异常从C 投掷到QML引擎
- QML 引擎不隐式将布尔字符串 QVarient 转换为布尔属性
- 从运行QML QtQuick2引擎的不同线程更新c++模型的行为