Search code examples
qmlqt5qtquick2qlistqvariant

QML Qvariant from custom class


I have my custom C++ class: Media.h:

#ifndef MEDIA_H
#define MEDIA_H

class Media
{

public:
    explicit Media();
    virtual ~Media();

    void setAllMedia(QString id, QString type, QString media, QString meta);


signals:


private slots:


private:
    QString _id;
    QString _type;
    QString _media;
    QString _meta;
};

#endif

in other QML file, i have some code wich reads very good values from a QML variant like this: main.ml:

property variant medias:[[]]
...
medias = [{
    "id": "7",
    "type": "image",
    "media": "1451138132567e9c544fc64.png",
    "meta": null
}, {
    "id": "8",
    "type": "image",
    "media": "1451150881567ece21bb77e.png",
    "meta": null
}, {
    "id": "9",
    "type": "video",
    "media": "1451150924567ece4c68775.png",
    "meta": null
}]

The problem is that I need to dynamically create the variant medias array from C++ and send it to QML.

I have some signals to send the medias array from C++ to QML but this array is inside QList<Media>. How can I convert it to QVariant in order to be readable by QML?


Solution

  • You can store custom classes inside a QVariant object if you register these classes with Q_DECLARE_METATYPE.

    This will make the conversion possible from Media to QVariant in your C++ code, but the Media class will not be usable in QML as you would like.

    Instead, just create a QHash<QString, QVariant> or QMap<QString, QVariant> for storing the properties since they are automatically inverted (see here).