A
A
Anton2015-12-26 21:44:12
Qt
Anton, 2015-12-26 21:44:12

How to display a list of records?

Hello!
How to display a list of records from a database using QML?
There is nothing sensible in Google, errors all the time ...
Start with:
ui = new QDeclarativeView;
Next, you need to get data from the database (for example, news):

QSqlQueryModel *sqlModel = new QSqlQueryModel(this);
sqlModel->setQuery("SELECT * FROM news");

Next, you need to transfer the model to the qml file:
QDeclarativeContext *context = ui->rootContext();
context->setContextProperty("sqlModel", sqlModel);

And in it already in the ListView to display lists:
ListView {
    anchors.fill: parent
    model: sqlModel
    delegate: Text {
        text: title
    }
}

We finish:
ui->setSource(QUrl("qrc:/mainpage.qml"));
setCentralWidget(ui);
ui->setResizeMode(QDeclarativeView::SizeRootObjectToView);

As a result, nothing is displayed in the qml file in the ListView. On the "title" field, he swears, they say, there is no such thing:
qrc:/mainpage.qml:74: ReferenceError: Can't find variable: title

Line 74: text: title
Please help, I've already googled everything...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jacob E, 2015-12-26
@Zifix

How to use a QSqlQueryModel in QML
5 step is deprecated, today instead of these lines in main.cpp we simply write:

ArtistsSqlModel *artistsSqlModel = new ArtistsSqlModel( qApp);

QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("artistsModel", artistsSqlModel);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question