QVariantList is easy to use in Qt. If it involves data transfer, you need to convert QVariantList data to JsonArray string. This conversion has been implemented in Qt, just need to call the interface to complete the conversion, the code is as follows:

main.cpp

#include <QCoreApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>

#include <QVariantMap>
#include <QVariantList>
#include <QDebug>


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QVariantList QVarList;

    QVariantMap tmpvm;
    for ( int i = 0; i < 3; i ++ )
    {
        tmpvm.clear(a); tmpvm["name"] = QString("Test%1").arg(i);
        tmpvm["no"] = QString::number(i);

        QVarList<<tmpvm;
    }

    qDebug() < <"qvarList: "<<QVarList;


    //QVariantList is converted to a Jsonarray string
    QJsonArray jsonArray = QJsonArray::fromVariantList(QVarList);

    QJsonDocument jsonDoc(jsonArray);
    qDebug() < <"------------------------------QVariantList to json-------------------------------";
    qDebug() << jsonDoc.toJson(a);//Jsonarray string is converted to QVariantList
    QString str = "[{\"no\": \"1\", \"name\": \"Jack\"},{\"no\": \"2\", \"name\": \"Tom\"},{\"no\": \"3\", \"name\": \"Stans\"}]";
    QJsonDocument json = QJsonDocument::fromJson(str.toLatin1());
    qDebug() < <"------------------------------json to QVariantList-------------------------------";

    qDebug() < <"qvarList: "<<json.array().toVariantList();;


    return a.exec(a); }Copy the code

 

Execution Result:

To make it easier to see, manually format the results and add a newline.

​
qvarList:  
(
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Test0"(a))"no".QVariant(QString, "0")))), 
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Test1"(a))"no".QVariant(QString, "1")))), 
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Test2"(a))"no".QVariant(QString, "2"))))
)
​
------------------------------QVariantList to json-------------------------------
"[{"name":"Test0","no":"0"}, {"name":"Test1","no":"1"}, {"name":"Test2","no":"2"}]"
------------------------------json to QVariantList-------------------------------
qvarList:  
(
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Jack"(a))"no".QVariant(QString, "1")))), 
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Tom"(a))"no".QVariant(QString, "2")))),
QVariant(QVariantMap, QMap(("name".QVariant(QString, "Stans"(a))"no".QVariant(QString, "3")))))Copy the code

Wechat Official Account: