C++与QML间的JSON处理

C++ 与QML间通过把类注册到QML间来实现通信,同时在双方传递结构体或多参数时,使用json 是非常方便的。以下从二个方面来说明怎么传递:

一、从C++ 传递给QML

先在C++注册到QML的类中定义一个 public slots 函数,比如QJsonObject getJsonValue(); 具体返回json 的什么类型,根据具体情况。

QJsonObject InterfaceForQml::getJsonValue()
{
    QJsonObject object;
    object.insert("name","xiaoming");
    object.insert("age",48);
    return object;
}

在QML中我们就可以调用来获取这个传递过去的json 对象了。

            var tobjec = toQmlInfo.getJsonValue();
            console.log("object:",tobjec.name);
            console.log("object age:",tobjec.age);

二、从QML传递给C++

在QML中

        var mytestJson = {};
        mytestJson.cmdId = 0;
        var listFileName = [];
        listFileName[0]="test1";
        listFileName[1]="test2";
        listFileName[2]="test3";
        mytestJson.fileName = listFileName;
        toQmlInfo.sendCmd(mytestJson);

在C++中

void InterfaceForQml::sendCmd(QJsonObject cmd)
{

    qDebug()<<"cmd"<<cmd;
}
C++类注册到QML中

InterfaceForQml *toQmlInfo = InterfaceForQml::getInstance();

engine.rootContext()->setContextProperty("toQmlInfo",toQmlInfo);

猜你喜欢

转载自blog.csdn.net/dreamliweiming/article/details/130962685