Model based on QList containing objects of custom class
-
Hi All,
I need to expose a QList containing objects of custom class to QML as a model. The problem is that when I'm trying to do this qml 'says' that reference to model cannot be resolved. Would someone please help me out?The custom class is defined as follows:
#include <QMetaType> #include <QObject> class Move { Q_GADGET Q_PROPERTY(int fromIndex READ getFrom) Q_PROPERTY(int toIndex READ getTo) private: int from; int to; protected: public: Move(int _from, int _to); Move():from(0), to(0){} Move(const Move& move):from(move.getFrom()), to(move.getTo()){} ~Move() {} int getFrom() const; int getTo() const; }; Q_DECLARE_METATYPE(Move)
This is how I define a list which I'm going to expose as a model.QList<Move> moves;
I'm exposing the model to QML as below. With this code I receive a complaint from QML -
qrc:/qmls/Main.qml:39: ReferenceError: Moves is not definedQQmlContext* cntx = engine.rootContext(); if(cntx != nullptr) { cntx->setContextProperty("Moves", QVariant::fromValue(moves)); }
When I'm passing a number (say 64) as a model I can see that model is recognized and QML is inflated with items:QQmlContext* cntx = engine.rootContext(); if(cntx != nullptr) { cntx->setContextProperty("Moves", QVariant::fromValue(64)); }
Thanks.
-
Hi
It all seems fine.
You should delete ur build folder and make sure all is recompiled.
Make sure there is a moc_ file for where Move lives.Also test that QVariant do like your type
QVariant v = QVariant::fromValue(moves); -
Hi,
Did you register
Moves
? -
I was thinking about
qmlRegisterType
like shown in Defining QML Types from C++. -
How are you using that type in your QML code ?
-
@SGaist
I'm not using Move type in QML directly. I'm only accessing model which is a QList<Move> as below:Column { Repeater { model: Moves Text {height: 20; width: 20; text: "HELLO"} } }
Also I tried a little "experiment" as @mrjj suggested:
Move move(1, 2); QVariant var = QVariant::fromValue(move); Move move1 = var.value<Move>(); std::cout << move1.getFrom() << " " << move1.getTo() << std::endl;
This code outputs "1 2" as expected