Qt 5.0: Exposing C++ methods to Java Script

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.


All that needs to be done is calling the method below somewhere before referencing MyObject in the script.

qmlRegisterType<MyObject>("", 1, 0, "MyObject");

Then createMyObject method will return correct type without any conversion:

var obj = createMyObject();

MyObject

Actually if we change type of the method below

Q_INVOKABLE MyObject* createMyObject();

to

Q_INVOKABLE QObject* createMyObject();

it will start working even without

qmlRegisterType

You can use QJSEngine::newQObject() method.

Use newQObject() to wrap a QObject (or subclass) pointer. newQObject() returns a proxy script object; properties, children, and signals and slots of the QObject are available as properties of the proxy object. No binding code is needed because it is done dynamically using the Qt meta object system.

Please read further details at QJSEngine Class: QObject Integration.

Tags:

Javascript

Qt

Qt5