在Qt中,有没有人知道如何创建类型为错误的QJSValue?
上下文:我使用QJSEngine::evaluate()在用QT创建的GUI中执行用户编写的JavaScript代码。该JavaScript代码调用C ++函数。根据文档,只有在JavaScript代码中存在错误时,QJSEngine :: evaluate()才会抛出脚本异常(类型为Error的QJSValue)。因此,如果C ++函数中存在错误,我的方法是返回类型错误的QJSValue。我遵循这条路径因为QJSEngine :: evaluate没有捕获C ++异常。
这是预期功能的代码片段:
void CMainWindow::slot_ExecuteJVScript()
{
myCppClass myObject(parameters); //It has a foo() method.
QJSEngine myEngine;
myEngine.globalObject().setProperty("myObj", myEngine.newQObject(&myObject)); //Now we can access the C++ object from JavaScript code.
QString myScriptJS = "var X = myObj.foo()"; //Calling a C++ function from JavaScript
QJSValue myValue = myEngine.evaluate(myScriptJS);
if(myValue.isError())
{
//If there is an error in the JavaScript code we enter here
//But I also wanto to enter here if there is an error in my foo() C++ function.
}
else
{
//Do things with myValue
}
}
myCppClass :: foo()的迷你示例
QJSValue myCppClass::foo()
{
if(something)
{
//Create a QJSValue myValue with some data
return myValue;
}
else
{ //ERROR
//Create a QJSValue of type Error
return myValueOfTypeError;
}
}
非常感谢你。