考虑这个例子:
通过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
替换它,它应该可以工作(尽管显然它不是常数(。