2

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.

dtech
  • 47,916
  • 17
  • 112
  • 190
Vedanshu
  • 2,230
  • 23
  • 33
  • 2
    Possible duplicate: http://stackoverflow.com/questions/14287252/accessing-c-qlists-from-qml – GPPK Mar 16 '15 at 18:48

1 Answers1

3

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.

dtech
  • 47,916
  • 17
  • 112
  • 190