Accessing QList<structure_type> from qml using qqmlproperty map

I am trying to access the value of qqml property map which gives me QList<user_defined_structure>, but I am unable to access the values, it says undefined.

C++

struct user_defined_structure
{
int a;
int b;
};

Q_PROPERTY(QQmlProperty* myMap READ getMyMap CONSTANT)

How do I access each structure values in Qml?? myMap.key gives me QList<user_defined_structure>

Upvotes: 0

Views: 153

Answers (1)

Dmitry Sokolov
Dmitry Sokolov

Reputation: 3190

You need to inherit your custom struct from QObject:

class user_defined_structure : public QObject
{
    Q_OBJECT

    Q_PROPERTY(int a  MEMBER a  NOTIFY propertyChanged)
    Q_PROPERTY(int b  MEMBER b  NOTIFY propertyChanged)

  public:
    user_defined_structure(QObject* parent = nullptr) : QObject(parent) {}

    int a = 0;
    int b = 0;

  signals:
    void propertyChanged ();  // NOTIFY signal must be specified to allow QML property bindings
};

To use it in another class:

class MyClass : public QObject
{
    Q_OBJECT

    Q_PROPERTY(user_defined_structure* myStruct  READ getMyStruct  NOTIFY propertyChanged)

  public:
    MyClass(QObject* parent = nullptr) : QObject(parent) {}

    user_defined_structure* getMyStruct() const;
};

To use it in Qml:

int main()
{
    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty(QStringLiteral("myClass"), &myClass);
}
ListView {
    model: myClass.myStruct
}

Upvotes: 0

Related Questions