PDA

View Full Version : Custom object usage inside QtScript



FuturePrimitive
6th September 2012, 02:57
Hello,

Problem:

I have an app that uses external library - this library uses one single major class for all lib calls.
Now im using this library class object all over the application and what i would like to do is simple scripting feature alowing power users to make some custom use of this application - including usage of the library object im using in this app.

Question:
Is this possible using QtScript?
If yes can you point me somehow to the right direction?

My main problem is that i cant find any leads how to make this lib class object available inside the QtScript.

NOTE:
The library is not using Qt so no Q_OBJECTs and i cant make any changes in the library.

Thanks in advance

pkj
6th September 2012, 07:40
There is a easy to understand way out. And there is a complicated but better way out.
Easy way out:
Create a wrapper QObject derived class. Get all the required functions of library get called from here. So if you have void Lib::callMePlease(), you will have a Q_INVOKABLE or public slot function in your MyQObject::callMePlease(). You introduce the MyQObject to script. All the functions get redirected.
Now, the problem start as in the Lib you will not particularly have functions which return nothing and take nothing. They might be doing more than printing 'Hi There'. Now these types you need to introduce to scripts. The way to do it is via the QVariant subsystem. The idea of QVariant broadly is to enable QVariant to create your types. Very helping macros are available like Q_DECLARE_METATYPE and qRegisterMetatype(). You will have to read about them.
Needless to say it is a laborious process.
The complicated way is use QScriptEngine::newFunction(). To do that you have to write C Style functions in a file. Basically like QScriptValue func (QScriptContext*, QScriptEngine*).
If you go through the documentation, you will find that it is very repetitive and a candidate for code generation. So you may write a code that generates code for these functions. Something which the ScriptCodeGenerator does. Have the function body defined in a xml, or generate xml from header file if possible, use it to generate these C style functions. It kind of automates if there are too may functions in your LIB.
Once hand written or generated, you can just call a QScriptEngine::newObject() for lib... and add keep on adding properties for these functions...
Hope it helps,
Prashant