voodoogiant voodoogiant - 1 year ago 77
C++ Question

Qt: How are arrays or dictionaries passed from qscriptengine?

I've created a QScriptEngine and exposed an object's function I can call from js script.

engine->globalObject().setProperty("obj", myObj);

myObj is a QObject that has a function like...

void MyObject::doSomething(int w, int h) {

and in my js code, I can call it like...

obj.doSomething(5, 9);

This works as I expect it would, but I can't find any docs on passing arrays or dictionaries to these functions. For example, if I wanted to pass an array, how would I define the C++ function so I could do something like this...

obj.doSomething([1,2,3], "foo");

Would that be something like...

void MyObject::doSomething(QVector<QVariant> firstArg, QString secondArg);

It's hard to work it out as it when it doesn't work, the call seems to silently fail.

Answer Source

For arrays you have two options

  1. Registering the C++ sequence container with the script engine, see qScriptRegisterSequenceMetaType(). The function's documentation has an example for an int vector.

  2. Use QScriptValue as the function's argument. The passed object can then be checked if it is an array (QScriptValue::isArray()) and accessed by index using QScriptValue::property()

Option (2) also works for dictionaries (objects in JavaScript).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download