在脚本调用的C++函数中调用QJSEngine::newQObject()是否有效



考虑这个例子:

通过QJSEngine:将ObjectCreator设置为全局属性

// ObjectCreator is exposed to engine_ env as global property
class ObjectCreator : public QObject
{
Q_OBJECT
public:
ObjectCreator(QJSEngine * engine, QObject * parent = nullptr) : QObject(parent), engine_(engine) {}

// Called from script env
Q_INVOKABLE QJSValue createObject();
private:

// engine_ is not owned
QJSEngine * engine_ = nullptr;
};
class SomeObj : public QObject
{
// ...
};
QJSValue ObjectCreator::createObject()
{
// No parent due to JavaScriptOwnership
return engine_->newQObject(new SomeObj());
}

JavaScript(在engine_中从上一个代码段中评估(:

function f
{
// objectCreator is a global property of engine_
const someObj = objectCreator.createObj();
}

阅读文档时,我找不到这个问题的答案:

在通过engine_评估的JavaScript脚本调用的C++函数中调用engine_->newQObject()是否有效?

是的,C++在从脚本调用QJSEngine::newQObject()时完全可以。

您可能遇到的问题是const不受ECMAScript 5的支持,ECMAScript5是QJSEngine的版本(请参阅QTBUG-69408中的解释(。用var替换它,它应该可以工作(尽管显然它不是常数(。

相关内容

  • 没有找到相关文章

最新更新