[Qt-qml] 'property variant' mutilates / can't store a javascript object with js prototype?

Kent Hansen kent.hansen at nokia.com
Tue Oct 26 16:33:18 CEST 2010


Hi,

On 26. okt. 2010 13:58, ext Ville M. Vainio wrote:
> I'm trying to store a javascript object with 'prototype' in property variant.
>
> In my qml I have
>
> import "redditengine.js" as RE
>
> Rectangle {
> ...
>
>      property variant eng
>      Component.onCompleted: eng = RE.create()
>
> My javascript is here:
>
> http://gitorious.org/qmlreddit/qmlreddit/blobs/master/qml/qmlreddit/redditengine.js
>
> (It's perfectly normal javascript that follows GJS convention to
> create a javascript "class" RedditEngine)
>
> It appears that the object I create with "new RedditEngine" works
> perfectly fine before I store it to "property variant eng" (i.e. it
> works inside RE.create()), but once it's stored the attributes in
> prototype are forgotten (or "sliced out").
>    

When the JS object is stored to a variant, it'll be converted to a 
QVariantMap (so that the property can be usefully manipulated from C++). 
That's not what you want in this case, because as you've found, the 
conversion is lossy.
There currently isn't any way to create a JavaScript object reference 
property on an item (e.g. no "property Object foo").
You could store the object in a property of the script, by adding 
something like this to redditengine.js:

var _instance = null;

function instance() {
     if (!_instance)
         _instance = create();
     return _instance;
}

And then access it by "RE.instance()" in your qml.
By default, there will be a separate script "instance" per component 
instance, meaning each component instance will have its own RedditEngine 
(i.e. analogous to having an engine property on the component). If you 
make redditengine.js a library (by using ".pragma library"), the 
component instances will share a single engine.

Regards,
Kent



More information about the Qt-qml mailing list