Unsolved QJSEngine, how to expose C++ enum to a JavaScript?
-
I managed to expose an (uninstantiable) class to JavaScript using qmlRegisterType as follows:
class MyClass : public QObject { Q_OBJECT public: MyClass () : _name("MyClass") { } Q_INVOKABLE void setName(QString name) { _name = name; } Q_INVOKABLE QString getName() { return _name; } enum MyEnum { Entry1, Entry2 }; private: QString _name; }; // registered using qmlRegisterType<MyClass>()
But I cannot access MyEnum. Looking online there are only examples on how to do it with QML using import.
-
Did you try using Q_ENUM ?
-
@dheerendra I added Q_ENUM(MyEnum) after the enum declaration but that didn't work.
When I try to access it using m.Entry1 where m is an instance of MyClass I instantiate from a global object, I just get an "undefined" value.
Note that I also cannot access it using MyClass.Entry1, I get the error:
Uncaught exception at line 5: ReferenceError: MyClass is not defined -
Can you register your class like this ?
qmlRegisterType< MyClass >("MyApp",1,0,"MyEnums");
Now accès it as MyEnums.Entry1
-
Still doesn't work unfortunately.
class MyClass : public QObject { Q_OBJECT public: MyClass() : _name("MyClass") { } Q_INVOKABLE void setName(QString name) { _name = name; } Q_INVOKABLE QString getName() { return _name; } enum MyEnum { Entry1, Entry2 }; Q_ENUM(MyEnum) private: QString _name; }; // registered using qmlRegisterType<MyClass>("MyApp", 1, 0, "MyEnums");
Evaluate:
let c = controller.createClass(); c.getName(); MyEnums.Entry1
Error: Uncaught exception at line 4: ReferenceError: MyEnums is not defined
With QML, the examples would also import the registered type when running the script, but that doesnt work with QJSEngine...
-
Where did you include the qmlRegisterType ? Did you make the import statements in qml ?
-
I don't understand the question. I am using QJSEngine, not QQMLEngine.
I use qmlRegisterType like this:
QJSEngine _jsEngine; QJSValue objectValue = _jsEngine.newQObject(_controller); _jsEngine.globalObject().setProperty("controller", objectValue); _jsEngine.installExtensions(QJSEngine::Extension::ConsoleExtension); qmlRegisterType<MyClass>("MyApp", 1, 0, "MyEnums"); QJSValue result = _jsEngine.evaluate(script->toPlainText());
-
Hi @Alhasni,
According to https://doc.qt.io/qt-5/qjsengine.html#qobject-integration I guess you need to use
QJSEngine::newQMetaObject()
:QJSValue enumObjectValue = _jsEngine.newQMetaObject(_controller->metaObject()); _jsEngine.globalObject().setProperty("controller", enumObjectValue);