vlad_tepesch
vlad_tepesch

Reputation: 6891

How to make a C++ class accessible from Javascript

I am using Qt 4.8 and QScriptEngine.

I want to make a C++ class usable from Javascript but I did not get it.

I already know how to expose a single object of the class.

My class looks like that:

#include <QtCore/QObject>

class Tada: public QObject
{
  Q_OBJECT
public:

  Tada(int i=0): m_i(i){};

public slots:
  int giveNumber();

private:
  int m_i;
};

on the location there I set up the script engine I can add something like

static Tada tada;
engine->globalObject().setProperty("tada", engine->newQObject(&tada));

this makes the object tadaavailable in the scripts so I can use it like

tada.giveNumber();

But that if I want to create Tada objects in the script itself like:

var mt = new Tada(34);
mt.giveNumber();

?

Upvotes: 1

Views: 249

Answers (1)

mjk99
mjk99

Reputation: 1330

First create a constructor function like:

QScriptValue constructTada(QScriptContext * context, QScriptEngine * engine)
{
    Tada * pTada = new Tada;

    if (context->argumentCount() > 0)
    {
        // Set any properties...
        pTada->setNumber(context->argument(0).toInt32());
    }

    return engine->newQObject(pTada);
}

Then you need to put that function into the scripting environment:

QScriptEngine engine;
QScriptValue ctor = engine.newFunction(constructTada);
engine.globalObject().setProperty("Tada", ctor);

Upvotes: 1

Related Questions