PDA

View Full Version : Not understanding QtScript



zephod
18th April 2012, 01:24
I'm trying to learn about QT script and I'm clearly not understanding something basic.
Consider the following code:



#include <iostream>

#include <QApplication>
#include <QtScript>
#include <QObject>

using namespace std;

class MyClass : public QObject
{
public:
int x;
};

int main(int argc, char* argv[])
{
QApplication app(argc, argv);

MyClass mc;
mc.x = 0;

QScriptEngine eng;
QScriptValue scriptClass = eng.newQObject(&mc);
QScriptValue global = eng.globalObject();
global.setProperty("myClass", scriptClass);

QScriptValue res = eng.evaluate("myClass.x == 0");
if (res.isBoolean())
{
cout << "res is 0 = " << res.toBoolean() << endl;
}
else
{
cout << "res is not boolean!!!" << endl;
}
return 0;
}


This prints "res is 0 = 0" when run. It seems that the script engine does know about myClass but the value of myClass.x is not set.
Can someone enlighten me?

Thanks,
Steve

wysota
18th April 2012, 08:05
"x" needs to be a regular Qt property for this to work.

zephod
18th April 2012, 14:58
Thanks wysota!

Changed MyClass to



class MyClass : puble QObject
{
Q_PROPERTY(int x);
};


and


mc.x = 0;

to


mc.setProperty("x", 0);


and now its working.

wysota
19th April 2012, 09:18
That's not entirely correct. Should be:


class MyClass : public QObject
Q_OBJECT
Q_PROPERTY(int x READ x WRITE setX)
public:
MyClass(QObject *parent = 0) : QObject(parent) { m_x = 0; }
int x() const { return m_x; }
public slots:
void setX(int _x) { m_x = _x; }
private:
int m_x;
};

mc.setX(0);

zephod
19th April 2012, 14:33
It seems that what I did caused some dynamic properties to be created so that my program gave the answers I expected without actually being correct.
See my other post on Q_PROPERTY and Q_OBJECT.

wysota
19th April 2012, 15:43
I know, thus if you use my code above, it will work as expected.