Expose QPointer returned from Q_INVOKABLE to QJSEngine
-
Hi All,
Let's this code:
test.h:
#ifndef TEST_H #define TEST_H #include <QtCore> class Test : public QObject { Q_OBJECT public: Q_INVOKABLE Test(QObject *parent = Q_NULLPTR) : QObject(parent) {}; Q_INVOKABLE QPointer<QObject> getMyQPointer() { QObject *o1 = new QObject(this); o1->setObjectName("O1"); return o1; } Q_INVOKABLE QObject * getMyRawPointer() { QObject *o2 = new QObject(this); o2->setObjectName("O2"); return o2; } }; Q_DECLARE_METATYPE(Test) Q_DECLARE_METATYPE(Test*) #endif // TEST_H
main.cpp:
#include <QtCore> #include <QtQml> #include "test.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QJSEngine engine; engine.installExtensions(QJSEngine::AllExtensions); engine.globalObject().setProperty("TEST", engine.newQMetaObject(&Test::staticMetaObject)); QJSValue r = engine.evaluate("var t = new TEST; var p = t.getMyQPointer(); var r = t.getMyRawPointer(); console.log('Object with QPointer: ' + p.objectName); console.log('Raw pointer: ' + r.objectName); console.log(p) ; console.log(r);"); return 0; }
Output is:
js: Object with QPointer: undefined // <--- **Expected to be O1** js: Raw pointer: O2 js: QVariant(QPointer<QObject>, QObject(0x5622e05f5010, name = "O1")) js: QObject(0x5622e0595d10, "O2")
As you can see, output is different if you use QPointer o raw pointer. Is it possible to return QPointer through Q_INVOKABLE on a QJSEngine script and have same behaviour as raw pointer registered with Q_DECLARE_METATYPE?
Thanks!
-
@David-Pinelo I don't think so. And also, please remember that returning a QPointer is not necessary and not recommended:
A guarded pointer will automatically cast to a T *, so you can freely mix guarded and unguarded pointers. This means that if you have a QPointer<QWidget>, you can pass it to a function that requires a QWidget *. For this reason, it is of little value to declare functions to take a QPointer as a parameter; just use normal pointers. Use a QPointer when you are storing a pointer over time.