PDA

View Full Version : Call object method using qtscript



mvbhavsar
6th March 2013, 17:15
Hi,

I want to use QtScript in one of my application. for this I have created following class.


datefunction.h



#ifndef DATEFUNCTION_H
#define DATEFUNCTION_H

#include <QtCore>

class DateFunction : public QObject
{
Q_OBJECT

public:
explicit DateFunction(QObject *parent = 0);

signals:

public slots:
int daysInYear(QString year);
};

#endif // DATEFUNCTION_H



datefunction.cpp



#include "datefunction.h"

DateFunction::DateFunction(QObject *parent) :
QObject(parent)
{
}

int DateFunction::daysInYear(QString year)
{
int str=0;
QDate d1 = QDate::fromString(year,"yyyy");
if (!d1.isValid())
return str;
str = d1.daysInYear();
return str;
}


Now I want user to use this in qtscript and user should be able to call daysInYear() method in QScriptEngine.evaluate() function by passing this method and required parameter as a string.
Can anybody help me on this.


Regards

Manish

wysota
6th March 2013, 17:21
What have you tried so far?

mvbhavsar
6th March 2013, 17:29
I have come up upto here only


#include <QtCore>
#include "datefunction.h"
#include <QtScript>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QScriptEngine eng;
QObject *obj = new DateFunction;
QScriptValue val = eng.newQObject(obj,QScriptEngine::ScriptOwnership) ;

return a.exec();
}

Not sure how to use val variable to get class function call


Manish

wysota
6th March 2013, 21:18
Fetch the global object and set val as a property of that object. Then you can use this property to access your function.

anda_skoa
10th March 2013, 10:19
Additionally, have a look at registering a stand-alone function
http://qt-project.org/doc/qt-4.8/qscriptengine.html#newFunction

Cheers,
_