glitch in javascript bindings
-
Hi there and thx for reading and answering this post in you can.
I shouldn't ask you that because it worked before but doesn't now. Why ????
I declare 2 C++ classes:
class z: public QObject { Q_OBJECT public: Q_INVOKABLE z() {} }; class test: public QObject { Q_OBJECT public: Q_INVOKABLE test() {} public slots: z* get() { auto x = new z; return x; } }; `
Then the corresponding declarations for QJSEngine:
QJSValue ZObj = newQMetaObject(&z::staticMetaObject); globalObject().setProperty("z", ZObj); QJSValue TestObj = newQMetaObject(&test::staticMetaObject); globalObject().setProperty("test", TestObj);
so far so good, but when I run a javascript script such as :
var z = new test() var a = z.get()
QJSEngine returns:
Error: Unknown method return type: z*
What's wrong ?
Thx again for reading this post
-
@skylendar hi,
Can I ask why are you declaring the constructor of
z
with Q_INVOKABLE and creating an object in the JS engine ?QJSValue ZObj = newQMetaObject(&z::staticMetaObject); globalObject().setProperty("z", ZObj);
This should not be necessary as you don't need to create the object from Javascript.
Then the function
Test::get()
must return a Javascript object wrapping instance ofz
:QJSValue get() { auto x = new z; return jsEngine->newQObject(x); /* or return jsEngine->newQObject(new z);*/ }
Note that by doing this you avoid memory leak of
x
because the Javascript engine take ownershipt of the objectAre you sure you want to create a new instance of
z
each time you callget()
from Javascript ? I mean, this is more acreate()
function :). Or do you want to "share" an object your classTest
. Something like that in javascript:var z = new test() var a = z.x z.x.someFunction()
-
Ok, first of, thx for answering.
Q: can I ask why are you declaring the constructor of z with Q_INVOKABLE and creating an object in the JS engine ?
A: I use Q_INVOKABLE because it was suggested in the doc.Q: Are you sure you want to create a new instance of z each time you call get() from Javascript ?
A: Don't worry, it was just a simple ad-hoc code for this post, not the real code.
but ok, you answered my question with newObject(). I would have preferred something more straightforward.
Thank you again.
-
@skylendar said in glitch in javascript bindings:
A: I use Q_INVOKABLE because it was suggested in the doc.
Note Q_INVOKABLE is necessary only if you need to call the function from Javascript. In your code sample, this makes constructor of
z
available from JS, which is seemingly not what you want.var x = new z()