2
votes

I want to access a QList from qml. Here is a sample code

class A;
class B : public QObject {
   ...
   Q_INVOKABLE QQmlListProperty<A> read();
   ...
private:
   QList<A*> lst;
}

I'm using context property to access object of class B in qml. How can I access the list in qml. Any sample code will be helpful.

1

1 Answers

3
votes

You will need to Q_DECLARE_METATYPE(A *) to be able to wrap it in a QVariant for use in QML.

But that's just for referring to and passing it around QML.

If you want to use A in QML as in C++, it will have to inherit QObject and implement properties, slots and such.

You can see how to implement the QQmlListProperty here: http://doc.qt.io/qt-5/qtqml-referenceexamples-properties-example.html

Also, if QObject is too heavy for you and impractical to have a lot of them, you can always use a single QObject derived to work as a controller for a non-QObject but still registered as metatype type.

class A {
public:
  int a;
};

Q_DECLARE_METATYPE(A *)

class AProxy : public QObject {
  Q_OBJECT
public slots:
  int a(QVariant aVar) {
    return aVar.value<A *>()->a;
  }
  void setA(QVariant aVar, int v) {
    aVar.value<A *>()->a = v;
  }
};

This way you don't have the size overhead and limitations of QObject for every object in the list, and can instead use a single controller to access the data, albeit at lower performance. In your case you could use B to act as both container and controller proxy for A.