Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send javascript object to C++ from qml?

I have a method in C++ that expects an object:

Q_INVOKABLE void sendValue (const MyClass &value);

I'd like to call this method from qml, inside a javascript function, like this:

MyApi.sendValue({
    "one":"one",
    "two":2.0,
    "three": false,
    "four": [ 5, 6 ],
    }
});

MyClass is defined as follows:

#ifndef MYCLASS_H
#define MYCLASS_H
#include <QString>
#include <QVariant>
class MyClass {
    QString one;
    double two;
    bool three;
    int four[10];
public:
    MyClass();
    ~MyClass();
    // getters, setters, etc.
};
Q_DECLARE_METATYPE(MyClass)
#endif // MYCLASS_H

In main.cpp, MyClass is registered with qRegisterMetaType<MyClass>(); But none of the setters gets called, only MyClass' default constructor.

like image 997
kazmer Avatar asked Jan 27 '15 21:01

kazmer


People also ask

What is QML in JavaScript?

QML has a deep JavaScript integration, and allows signal handlers and methods to be defined in JavaScript. Another core feature of QML is the ability to specify and enforce relationships between object properties using property bindings, which are also defined using JavaScript.

How do I read a QML document from c++?

Once a QML object is created, it can be inspected from C++ in order to read and write to properties, invoke methods and receive signal notifications. For more information about C++ and the different QML integration methods, see the C++ and QML integration overview page. A QML document can be loaded with QQmlComponent or QQuickView.

Is it possible to access QML objects from c++?

Warning: Although it is possible to access QML objects from C++ and manipulate them, it is not the recommended approach, except for testing and prototyping purposes.

How can I receive a signal from a QML component?

In return, any C++ signal can be received by a QML object using signal handlers. Here is a QML component with a signal named qmlSignal that is emitted with a string-type parameter. This signal is connected to a C++ object's slot using QObject::connect (), so that the cppSlot () method is called whenever the qmlSignal is emitted:


1 Answers

You can send javascript objects to c++ from qml via QVariantMap and javascript array with QVariantList. It also goes the other way, you can send javascript object to qml using QVariantMap from c++. Just make your function in c++ Q_INVOKABLE or a slot and have the parameter be QVariantMap, and convert that QVariantMap into MyClass {}.

See http://doc.qt.io/qt-5/qtqml-cppintegration-data.html for details (search for QVariantList and QVariantMap to JavaScript Array and Object).

like image 115
vpicaver Avatar answered Sep 29 '22 10:09

vpicaver