如何从qml发送javascript对象到C++?

kaz*_*mer 5 javascript c++ qml

我在C++中有一个期望对象的方法:

Q_INVOKABLE void sendValue (const MyClass &value);
Run Code Online (Sandbox Code Playgroud)

我想从qml中调用这个方法,在javascript函数中,如下所示:

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

MyClass定义如下:

#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
Run Code Online (Sandbox Code Playgroud)

在main.cpp中,MyClass已注册qRegisterMetaType<MyClass>(); 但没有一个setter被调用,只有MyClass的默认构造函数.

vpi*_*ver 6

你可以通过qml QVariantMap和javascript数组将javascript对象发送到c ++ QVariantList.另外,你可以使用QVariantMapc ++ 将javascript对象发送到qml .只需在c ++ Q_INVOKABLE或插槽中创建函数,并将参数设置为QVariantMap,并将其转换QVariantMap为MyClass {}.

有关详细信息,请参阅http://doc.qt.io/qt-5/qtqml-cppintegration-data.html(搜索QVariantList和QVariantMap到JavaScript数组和对象).