QVector<int> not working as model?
-
Hi,
I have a simple class that holds aQVector<int>
as aQ_PROPERTY
and I expose this class to QML usingsetContextProperty
. I want to use the vector as a model inside aRepeater
but I noticed that even though my QML code can access the data (I can print it to the console) the repeater does not generate any elements. So my question is: do I have to create my own models usingQAbstractItemModel
even for basic types likeQVector<int>
which Qt is capable of converting from c++ to js?
I then found this example where they put aQStringList
in aQVariant
so I tried the same with aQList<int>
but still it did not work.
Here is the class which I expose to QML:
MyClass.h:class MyClass : public QObject { Q_OBJECT Q_PROPERTY(QVariant mydata READ mydata WRITE setMydata NOTIFY mydataChanged) signals: void mydataChanged(); public: MyClass(QObject* parent = nullptr); QVariant mydata(); void setMydata(QVariant data); QList<int> mydata_; };
MyClass.cpp
MyClass::MyClass(QObject* parent) : QObject(parent), mydata_({1,2,3,4}) { } QVariant MyClass::mydata() { return QVariant::fromValue(mydata_); } void MyClass::setMydata(QVariant data) { mydata_ = data.value<QList<int>>(); emit mydataChanged(); }
The QML file simply draws a rectangle for each element in the model (works fine when I replace model data with an integer like
model: 5
)Repeater { model: myclass.mydata Rectangle { x: index*20 y: 0 width: 10 height: 10 color: "red" } }
In case I'm doing it all wrong: what would be the fastest way to create a model which only holds integers?
Thank you very much. -
@tmnku
https://doc.qt.io/qt-5/qtqml-cppintegration-data.html#sequence-type-to-javascript-arrayuse the "length" property as model. an access the elements in the delegate component via the "index" variable