How to create a QList<CustomClass> data from QMetaType and QVariant in QT?

19 Views Asked by At

I am creating a serialization method between a Q_GADGET(Q_PROPERTY) class and JSON for my program. I have already mastered and implemented the method to convert from Q_GADGET to JSON.

What slightly consumed my time was handling the containers (QList, QVector) present in Q_GADGET, but I eventually managed to solve it.

I have defined a Q_PROPERTY attribute QList<Custom>, where Custom is also a Q_GADGET and has been registered with QMetaType. I can obtain a QVariant using QMetaProperty.readOnGadget, and then use QSequentialIterable to retrieve each Custom object, and serialize it one by one.

e.g :

struct{
   Q_GADGET

   GPROP_GETSET(QList<Custom>, b_list_custom, B_list_custom)
}

// QVariant from QList<Custom>, to QVariantList
static QVariantList _toVariantList(const QVariant &list)
{
    QVariantList valueList;
    foreach (const QVariant &valueItem, list.value<QSequentialIterable>()) {
        qInfo() << "_toVariantList" << valueItem.typeName() << valueItem;
        valueList.append(readVariant(valueItem));
    }

    return valueList;
}

Unfortunately, I have not found a method to generate a QList from QMetaType and add objects to the QList.

// QVariantList valueList is a JsonValue.toVariant();
static QVariant deserializeJsonList(const QVariantList &valueList, const QMetaType &metaType)
{
    const QMetaObject *metaObject = metaType.metaObject();

    // ???
    // metaType is "QList<AAA>", How create a QList<AAA> from metaType, and convert to QVarint;

    QVariant variant(metaType.id(), metaType.create());
    
    // ??? how append to `variant` from `AAA`

    return variant;
}

What should I do? Is there a better way or does QT provide a safe built-in solution for this?

Here is my test code:

https://github.com/zshuaia/test_qt_serialize

PS:

  1. I found some emails, but it seems that the final solution was not mentioned.

https://lists.qt-project.org/pipermail/interest/2017-February/026183.html

  1. I also found QJson and QSerialize on GitHub, but they do not seem to work properly.
0

There are 0 best solutions below