Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Custom type registered in QML and QVariant



  • Dear

    In Qt/QML, it is possible to define custom types from C++ and use them in QML by using:
    qmlRegisterType<CustomType>("ImportName",1,0,"TypeName");

    Qt also has support for the QVariant type which acts as an union for common datatypes. A custom type can be used with QVariant by using:
    Q_DECLARE_METATYPE(CustomType);

    Recently, I was doing implementations with listviews and treeviews where the model inherits from QAbstractItemModel and where this function is provided:
    virtual QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const = 0

    I would like to use a custom type for visualizing an item of my ListView and it would be great if the data function could return a QVariant which can be converted to my custom type in QML. How can I do this?

    Thanks
    Pieter


  • Moderators

    @Pieter-Cardoen
    the qml engine only support this types: https://doc.qt.io/qt-5/qtqml-cppintegration-data.html

    if you want to support a custom type you will have to convert it to one of those. before you can process them in QML.
    For example a struct can be converted to a QVariantMap, or a custom class must interhit QObject and use the meta object system (properties, invokabkle methods, etc.)


Log in to reply