Create a global object
Hi would like create a Global object to expose function.
And is it possible to add it in a plugin?
thanks
[edit: fixed typos / $chetankjain ]
12 replies
I want make a global object like Qt Object to expose functions :
http://doc.trolltech.com/main-snapshot/qml-qt.html [doc.trolltech.com]
Or something like
- import "file.js" as myObject
And this global Object is added with import of my QML plugin. This object could be coded in C++ or JS
[edit: fixed hyperlink / $chetankjain ]
Sorry, didn’t realize you are talking about scripting. Haven’t played with QML that much, bit if things are inherited from the QtScript module, it should go something like this:
- engine.globalObject().setProperty("myObject", engine.newQObject(object));
After that, your object will be available to qtscript.
As for making it pluggable with both c++ and js, I can’t really help. (I could think of a dirty way to achieve it, but IMO it is better to wait for our friendly Trolls to tell us the proper way)
You could try using setContextProperty() on the root context of the engine — this will effectively add the object as a context property that is available to all the elements in the engine. From a plugin, you can do so inside the initializeEngine() [doc.trolltech.com] function.
I believe there are plans to look at this more for a future release, so plugins can easily add “namespaces” like the Qt object with functions, enum values, etc.
With this method, how create QScriptValue with newXXXX function ?
http://doc.qt.nokia.com/4.7-snapshot/qscriptengine.html [doc.qt.nokia.com]
Another solution that i will test, it’s create a component with QDeclarativeComponent
http://doc.qt.nokia.com/4.7-snapshot/qdeclarativecomponent.html [doc.qt.nokia.com]
Make
- import "file.js" as myObject
[edit: fixed hyperlink / $chetakjain ]
With the setContextProperty() approach, you would use a QObject with slots or Q_INVOKABLEs for your “global” object, rather than a QScriptValue. The Minehunt demo shows this approach (adds a MinehuntGame object in the root context).
Thanks.
I’ve ever test it and it’s work perfectly ^^
I find a solution for JS code :D
1- create a qml file wich define function on the root element (I use QtObject)
2- in initializeEngine(), use a“QDeclarativeComponent “:http://doc.qt.nokia.com/4.7-snapshot/qdeclarativecomponent.html.
3- set qml file path or use setData
4- use create to make a QObject
5- add this QObject with setContextProperty
Like QDeclarativeComponent use qml file, i think it’s so possible to mix JS and C++ code
You must log in to post a reply. Not a member yet? Register here!






