When I used a model from C++, I had to use it as if it was an array. That's probably related to the fact that I set the context property with a QList.
main.cpp:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QList<QObject*> model;
QtQuick2ApplicationViewer viewer;
QQmlContext *ctxt = viewer.rootContext();
ctxt
->setContextProperty
("myModel",
QVariant::fromValue(model
));
viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer.showExpanded();
return app.exec();
}
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QList<QObject*> model;
model.append(new Book(QString("A Masterpiece"), QString("Gabriel")));
model.append(new Book(QString("Brilliance"), QString("Jens")));
model.append(new Book(QString("Outstanding"), QString("Frederick")));
QtQuick2ApplicationViewer viewer;
QQmlContext *ctxt = viewer.rootContext();
ctxt->setContextProperty("myModel", QVariant::fromValue(model));
viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer.showExpanded();
return app.exec();
}
To copy to clipboard, switch view to plain text mode
QML:
TableView {
id: table
width: parent.width
height: parent.height - 30
TableViewColumn{
role: "title"
title: "Title"
width: (root.width)/3
}
TableViewColumn{
role: "author"
title: "Author"
width: (root.width)/3
}
TableViewColumn{
title: "Author/Title"
width: (root.width)/3
delegate: Item{
Text{
text: model[styleData.row].author +"/"+ model[styleData.row].title
color: "red"
}
}
}
model: myModel
}
TableView {
id: table
width: parent.width
height: parent.height - 30
TableViewColumn{
role: "title"
title: "Title"
width: (root.width)/3
}
TableViewColumn{
role: "author"
title: "Author"
width: (root.width)/3
}
TableViewColumn{
title: "Author/Title"
width: (root.width)/3
delegate: Item{
Text{
text: model[styleData.row].author +"/"+ model[styleData.row].title
color: "red"
}
}
}
model: myModel
}
To copy to clipboard, switch view to plain text mode
Bookmarks