如何在QWebView中获取Javascript以创建基于C ++的类的新实例? [英] How to get Javascript in a QWebView to create new instances of C++ based classes?
问题描述
我使用 addToJavaScriptWindowObject
I've successfully added an C++ object to a QWebFrame with addToJavaScriptWindowObject, and can call a slot on that object from javascript.
但我真正想做的是让其中一个插槽返回一个新对象。例如,我有一个这样的插槽,它返回一个QObject派生类实例:
But what I really want to do is have one of those slots return a new object. For example, I have a slot like this, which returns a QObject derived class instance:
MyObject* MyApp::helloWorld()
{
//MyObject is dervied from QObject
return new MyObject();
}
我可以像这样成功地从javascript调用这个插槽
I can call this slot from javascript successfully like this
var foo=myapp.helloWorld();
但是foo似乎是空的,我无法拨打任何插槽或访问任何
来自Javascript的属性。
But foo appears to be empty, I can't call any slots or access any properties on it from Javascript.
关于如何实现这一点的任何想法?
Any ideas on how I can achieve this?
推荐答案
我考虑过的一个相当丑陋的黑客是使用addToJavaScriptWindowObject来删除我想要以随机名称返回到窗口对象的对象,然后让我的插槽返回对象实例的名称:
One rather ugly hack I've considered is to use addToJavaScriptWindowObject to drop the object I want to return into the window object with a random name, then have my slot return the name of the object instance instead:
QString MyApp::helloWorld()
{
//general a unique name for the js variable
QString name=getRandomVariableName();
//here's the object we want to expose to js
MyObject* pReturn=new MyObject();
//we make attach our object to the js window object
getWebFrame()->addToJavaScriptWindowObject(name, pReturn,
QScriptEngine::ScriptOwnership);
//tell js the name we used
return name;
}
可以编写JS以检查返回值是否为字符串,并且如果是,从窗口抓取对象。:
The JS can be written to check if the return value is a string, and if it is, grab the object from the window.:
var foo=myapp.helloWorld();
if (typeof foo == "string")
{
foo=window[foo];
}
有点难看,但会让我走过,直到有更好的方法出现。未来的Qt版本将统一脚本支持,所以它都基于WebKit中的JavaScriptCore,所以希望这会有所改进!
A little ugly, but will get me by until a better method comes along. Future Qt versions are going unify the scripting support so that it's all based on the JavaScriptCore in WebKit, so hopefully this will improve then!
这篇关于如何在QWebView中获取Javascript以创建基于C ++的类的新实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!