I played with QSqlQueryModel, but now I'm completely stuck. I searched for a solution all day, but so far no luck.
What I got is that it retrieves data from my sqlite database, but for some reason I cannot show this in my list. It seems that my role names do not exist.
I get messages like .... ReferenceError: id is not defined ..... for every row I pull from the database.
I used an example: http://qt-project.org/wiki/How_to_use_a_QSqlQueryModel_in_QML
I tried both examples, but always get the same problem.
My ccp file looks like this:
#include "artistssqlmodel.h"
const char* ArtistsSqlModel::COLUMN_NAMES[] = {
"id",
"word",
NULL
};
const char* ArtistsSqlModel::SQL_SELECT = "SELECT id, word FROM dictionary LIMIT 5";
ArtistsSqlModel::ArtistsSqlModel(QObject *parent) :
QSqlQueryModel(parent)
{
mydb=QSqlDatabase::addDatabase("QSQLITE");
QString dbPath = "E://mydb.db";
mydb.setDatabaseName(dbPath);
connectToDb();
int idx = 0;
QHash<int, QByteArray> roleNames;
while( COLUMN_NAMES[idx]) {
roleNames[Qt::UserRole + idx + 1] = COLUMN_NAMES[idx];
idx++;
}
refresh();
}
void ArtistsSqlModel::connectToDb()
{
if(!mydb.open())
{
qDebug() << "Database didnt open";
}
else
{
qDebug() << "Your database is open";
}
}
void ArtistsSqlModel::refresh()
{
this->setQuery(SQL_SELECT);
}
QVariant ArtistsSqlModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlQueryModel::data(index, role);
if(role < Qt::UserRole)
{
value = QSqlQueryModel::data(index, role);
}
else
{
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
}
return value;
}
and my qml file is as follows
import QtQuick 2.2
import QtQuick.Window 2.1
Window {
visible: true
width: 800
height: 800
ListView{
anchors.fill:parent
model:artistsModel
delegate: Item{
width:parent.width
height: width/10
Text {
id: name
text: word
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
anchors.fill:parent
}
}
}
}
, , , - , . qt ++, .
, sqlite db .
EDIT:
, ( , )
artistsqlmodel.h
#ifndef ARTISTSSQLMODEL_H
#define ARTISTSSQLMODEL_H
#include <QObject>
#include <QSqlQueryModel>
#include <QDebug>
class ArtistsSqlModel : public QSqlQueryModel
{
Q_OBJECT
public:
explicit ArtistsSqlModel(QObject *parent);
void refresh();
QVariant data(const QModelIndex &index, int role) const;
void connectToDb();
signals:
public slots:
private:
const static char* COLUMN_NAMES[];
const static char* SQL_SELECT;
QSqlDatabase mydb;
};
#endif
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtQml>
#include "artistssqlmodel.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext *context = engine.rootContext();
ArtistsSqlModel *artistsSqlModel = new ArtistsSqlModel( qApp);
context->setContextProperty("artistsModel", artistsSqlModel);
engine.load(QUrl(QStringLiteral("qrc:///qml/main.qml")));
return app.exec();
}