QML: passing a JS object to a C ++ member function

I am trying to pass a JS object (map) to a C ++ member function with a signature

Q_INVOKABLE virtual bool generate(QObject* context); 

using

 a.generate({foo: "bar"}); 

The method is called (defined via a breakpoint), but the passed context parameter is NULL . Since the documentation mentions that JS objects will be passed as QVariantMap , I tried using a signature

 Q_INVOKABLE virtual bool generate(QVariantMap* context); 

but this failed during the MOC. Using

 Q_INVOKABLE virtual bool generate(QVariantMap& context); 

causes the method to not be detected during QML execution (error message "Unknown method parameter type: QVariantMap &").

The documentation has only an example of passing a QVariantMap from C ++ to QML, and not in a different direction.

Using a public slot instead of Q_INVOKABLE shows exactly the same behavior and errors.

+5
source share
1 answer

Do not use links to pass values ​​from the QML world to the CPP world. This simple example works:

test.h

 #ifndef TEST_H #define TEST_H #include <QObject> #include <QDebug> #include <QVariantMap> class Test : public QObject { Q_OBJECT public: Test(){} Q_INVOKABLE bool generate(QVariantMap context) {qDebug() << context;} }; #endif // TEST_H 

main.cpp

 #include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include "test.h" int main(int argc, char *argv[]) { QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QQmlApplicationEngine engine; engine.rootContext()->setContextProperty(QStringLiteral("Test"), new Test()); engine.load(QUrl(QLatin1String("qrc:/main.qml"))); if (engine.rootObjects().isEmpty()) return -1; return app.exec(); } 

main.qml

 import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 ApplicationWindow { visible: true width: 640 height: 480 title: qsTr("Hello World") MouseArea { anchors.fill: parent onClicked: { Test.generate({foo: "bar"}); } } } 

click in the window, it will print the following messages in the output console:

 QMap(("foo", QVariant(QString, "bar"))) 
+5
source

Source: https://habr.com/ru/post/1273357/


All Articles