Using QSqlQueryModel class in QML
Solved
QML and Qt Quick
-
I want to populate QSqlQueryModel in QML TableView
#include "model.h" Model::Model(QObject *parent) : QSqlQueryModel(parent) { } QVariant Model::data(const QModelIndex & index, int role) const { int columnId = role - Qt::UserRole - 1; QModelIndex modelIndex = this->index(index.row(), columnId); return QSqlQueryModel::data(modelIndex, Qt::DisplayRole); } QHash<int, QByteArray> Model::roleNames() const { QHash<int, QByteArray> roles; roles[IDRole] = "ID"; roles[TitleRole] = "Title"; roles[PoemRole] = "Poem"; roles[GrpRole] = "Grp"; return roles; }
main.cpp
DataBase database; Model *model = new Model(); model->setQuery("SELECT " TABLE_ID ", " TABLE_TITLE ", " TABLE_POEM ", " TABLE_GRP " FROM " TABLE); engine.rootContext()->setContextProperty("myModel", model);
TableViewColumn { role: "IDRole" title: "Id" } TableViewColumn { role: "TitleRole" title: "Title" }
-
@behruz-montazeri
At least, state your problem. -
Database is connected but TableView is empty. I hard search google but i couldn't find similar example.
-
Did you have a look at this:
https://forum.qt.io/topic/51219/solved-qsqlquerymodel-for-qml-tableview/ -
I saw the page but hard to read and understand . I uploaded my project : https://github.com/sudebiar/QSqlQueryModel-Class. take look at it if it's possible.
-
Since the role names of TableViewColumn is case-sensitive and must match a role returned by roleNames() of your model , your table view should be look like this to solve the problem
TableView {
anchors.fill: parentTableViewColumn { role: "ID" // These roles are roles names coincide with a C ++ model title: "Id" } TableViewColumn { role: "Title" // These roles are roles names coincide with a C ++ model title: "Title" } TableViewColumn { role: "Poem" // These roles are roles names coincide with a C ++ model title: "Poem" } TableViewColumn { role: "Grp" // These roles are roles names coincide with a C ++ model title: "Group" } // We set the model in the TableView model: myModel }
-
Now TableView has my records.Thanks.