Reputation: 1572
I have a custom type, called Patients
(please ignore the plural mistake). I want to create a QList<Patients*>
in my cpp and consume that from my QML. I am following the patterns from here, but it is not working.
Here is my patients.h (probably more info than needed) . . .
class Patients : public QObject
{
Q_OBJECT
Q_PROPERTY(QString name READ getName)
Q_PROPERTY(QString email READ getEmail)
Q_PROPERTY(int id READ getId)
public:
explicit Patients(QObject *parent = 0);
explicit Patients(int id, QString name, QString email, QObject *parent = 0);
QString getName() const;
QString getEmail() const;
int getId() const;
private:
QString email, name;
int id;
};
Here is the main cpp
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQmlApplicationEngine engine;
QList<Patients*> lst;
lst.append(new Patients(0, QString("abe"), QString("albert")));
QQmlContext *ctx = engine.rootContext();
ctx->setContextProperty("pLst", QVariant::fromValue(lst));
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
Here is the qml . . .
ListView{
id: lst
height: 100; width: 100
anchors.fill: parent
x: 100; y: 100
model: pLst
delegate: Text{
text: model.modelData.name
}
}
It works when I bind a single object, but not as a list. Even presenting the index
inside Text
does not work. No error messages or anything.
Upvotes: 0
Views: 1435
Reputation: 378
You will define new class with QQmlListProperty
, and define a container data object(this class will inherit from QObject
), in the class of QQmlListProperty
you will define the container QList
of pointers of QObject
. I wrote two posts about this topic:
Show, change data and keep QQmlListProperty in qml
Use QQmlListProperty to show and modify QList in Qml
Upvotes: 0
Reputation: 1139
There is no general support for the QList
container in QML even if the type it is holding is registered to Qt's meta system. Some special variants (e.g. QStringList
QList<QObject*>
) are supported by default so you can use QList<QObject*>
if your class is derived from QObject
.
If your type is not derived from QObject
or if you want to keep your interface in C++ clean and typesafe I suggest to use QQmlListProperty
. Mind that you don't have to implement the append()
or clear()
method if you do not want to make the list modifiable from inside QML.
Upvotes: 3