Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt 5.0: Exposing C++ methods to Java Script

Tags:

javascript

qt

qt5

I try to expose an object as a global property to Java Script which has the method below:

Q_INVOKABLE MyObject* createMyObject();

MyObject is derived from QObject.

when I call this method in Java Script it returns an object of type:

QVariant(MyObject*)

I'm wondering if it's possible to automatically convert it to QJSValue so I can use it further in the script?

like image 428
MaksymB Avatar asked Jan 18 '13 09:01

MaksymB


Video Answer


1 Answers

Seems that Java Script uses QVariant as an opaque wrapper around any 'unknown' type. The value can be passed around easily but non of its properties can be used and non of its methods can be invoked. To be used in script it should be converted to QJSValue. The only way I found is declaring helper function like this:

Q_INVOKABLE QJSValue convert(QVariant var)
{
    return _engine.newQObject(var.value<QObject*>());
}

then it's possible to convert QVariant to QJSValue:

var obj = convert(createMyObject());

and obj will be of type

MyObject

So now it can be used in script.

like image 149
MaksymB Avatar answered Sep 19 '22 00:09

MaksymB