Search code examples
c++qtqjsengine

How to register an enum type to QJSEngine to be used from the scripting environment?


I've searched for hours on end but I cannot figure out how do I register an enum type from C++ side so I can use it from the scripting environment side when using QJSEngine?

I have a class that derives from QObject, is registered to the scripting environment and has a function that takes an enum as an argument. I want to be able to call that function from the scripting environment.

class ScriptWrapper : public QObject
{
    Q_OBJECT

  public:
    ScriptWrapper(QJSEngine& engine)
    {
        QJSValue scriptVal = engine.newQObject(this);
        engine.globalObject().setProperty("someClass", scriptVal);
    }

    enum class Foo
    {
        Bar,
        Kek
    };
    // Q_ENUM(Foo)

    Q_INVOKABLE void set(Foo foo);

};

What do I need to do to be able to call set() from the scripting side when using QJSEngine? I've tried the Q_ENUM call commented out but it doesn't seem to help.


Solution

  • Bring Q_ENUM back in place and add this to the constructor:

    QJSValue meta = engine.newQMetaObject(&ScriptWrapper::staticMetaObject);
    engine.globalObject().setProperty("ScriptWrapper", meta);
    

    Now you can use the enum like, e.g.

    engine.evaluate("someClass.set(ScriptWrapper.Kek)");