Unlike QScriptEngine , where you can add custom classes if they inherit from QObject using the Q_SCRIPT_DECLARE_QMETAOBJECT macro, QJSEngine does not directly provide this functionality.
You can still use the Qt meta-object system to provide interfaces for Javascript, but you need to instantiate the object in C ++ and add it to the Javascript context. Then its slots, methods defined with Q_INVOKABLE , and properties defined with Q_PROPERTY are made available from the Javascript runtime.
Now you can create a factory that instantiates your custom CustomClass for the given QJSEngine wrapped in Javascript objects:
class CustomClassFactory : public QObject { Q_OBJECT public: CustomClassFactory(QJSEngine* engine) : m_engine(engine) {} Q_INVOKABLE QJSValue createInstance() {
A factory instance must be created and added to the global Javascript runtime object:
QJSEngine engine; QJSValue factoryObj = engine.newQObject(new CustomClassFactory()); engine.globalObject().setProperty("_customClassFactory", factoryObj);
Now we can create objects in Javascript with:
var obj = _customClassFactory.createInstance()
Since we have come this far, let's add an additional constructor for the custom class to the Javascript runtime:
QJSEngine engine;
So now you can create a C ++ object in Javascript, as if you were using custom Javascript classes:
var obj = new CustomClass()
For the mentioned WebSocket API, you can wrap QtWebSocket for this purpose - this is exactly what I need when I came up with the proposed approach.
Note that for simplicity, I omitted the options for the constructor, but they can also just be added.
PS: I would add more links to the official documentation, but due to lack of reputation, this is forbidden to me.