PDA

View Full Version : make QVector's operator useful in qtscript



wookoon
17th May 2011, 11:07
We can make c++'s Object and Functions available in QtScript,

Can QVector's operator be availiable in QtScript?

then in qtscript:
var vector1 = [1,2,3];
var vector2 = [3,4,5];
var a = vector1 + vector2;

this is what I want get.

wysota
17th May 2011, 23:49
But you are not using QVector here anywhere. There is just javascript code here.

wookoon
18th May 2011, 02:55
c++ code:


Q_DECLARE_METATYPE(QVector<float>)

QVector<float> vector1;
QVector<float> vector2;
QVector<float> vector3;

vector1 << 1 << 2 << 3;
vector2 << 3 << 4 << 5;

QScriptEngine *engine = new QScriptEngine;

qScriptRegisterSequenceMetaType<QVector<float> >(engine);
QScriptValue value = engine->toScriptValue(vector1);
engine->globalObject().setProperty("vec1",value);

value = engine->toScriptValue(vector2);
engine->globalObject().setProperty("vec2",value);

value = engine->toScriptValue(vector3);
engine->globalObject().setProperty("vec3",value);


now the vec1,vec2 and vec3 is availiable in Qtscript,

If I want do like this in QtScript,:



vec3 = vec1 + vec2 ,


Could this be realized in Qtscript?

I think if can make QVector's operator function be availiable in qtscript, then can realize it.

wookoon
18th May 2011, 05:31
But you are not using QVector here anywhere. There is just javascript code here.

I have try another method:
I write a object and overide the "+" operator,and make it availiable in qtscript,



class MyObject : public QObject
{
Q_OBJECT
public:
explicit MyObject(QObject *parent = 0);

Q_INVOKABLE MyObject* operator+(const MyObject &other)
{
MyObject *object = new MyObject;
object->d = other.d + this->d;
return object;
};

void setValue(int value){d = value;};
int value(){return d;};

private:
int d;
};


main.cpp:


MyObject * object = new MyObject;
object->setValue(10);
QScriptValue objectValue = engine->newQObject(object);
engine->globalObject().setProperty("obj1", objectValue);

MyObject * object2 = new MyObject;
object2->setValue(5);
objectValue = engine->newQObject(object2);
engine->globalObject().setProperty("obj2", objectValue);

engine->evaluate("obj1+obj2;");


But from my debug, the "obj1 + obj2" did not execute the MyObject's "+" operator.

So this method maybe is no effect.

wysota
18th May 2011, 11:01
From what I can see Javascript does not support operator overloading. You need a "named" method for this. You can add this method to your objects by modifying their prototype or defining the method in C++ as part of the class. As for QVector, you need to make it scriptable manually using means such as QScriptable and/or QScriptClass.