I’m trying to include a SQLite database with QT Quick but I can’t find any examples. I just want to be able to access items from a database. Does anyone know of any example programs I can play with?
You could take QSqlQueryModel for example, or any other SQL model and add it to the QML context and use it in the ListView for example.
Define the role names that will be used by delegates to access data by role in QtQuick components (data
method is bit naive as there is no kind of error checking):
class SqlQueryModel: public QSqlQueryModel
{
Q_OBJECT
QHash<int,QByteArray> *hash;
public:
explicit SqlQueryModel(QObject * parent) : QSqlQueryModel(parent)
{
hash = new QHash<int,QByteArray>;
hash->insert(Qt::UserRole, QByteArray("someRoleName"));
hash->insert(Qt::UserRole + 1, QByteArray("otherRoleName"));
}
QVariant data(const QModelIndex &index, int role) const
{
if(role < Qt::UserRole) {
return QSqlQueryModel::data(index, role);
}
QSqlRecord r = record(index.row());
return r.value(QString(hash->value(role))).toString();
}
inline RoleNameHash roleNames() const { return *hash; }
};
Create an instance of newly defined model class and add it to the QML context
view = new QQuickView();
QSqlQueryModel *someSqlModel = new SqlQueryModel(this);
someSqlModel->setQuery("SELECT someRoleName, otherRoleName FROM some_table");
QQmlContext *context = view->rootContext();
context->setContextProperty("someSqlModel", someSqlModel);
view->setSource(QUrl("qrc:///MainView.qml"));
view->show();
Bind your model to the ListViews model
property and use previously defined role names to access the data in the delegate.
ListView {
id: someListView
model: someSqlModel
delegate: Text {
anchors.fill: parent
text: someRoleName
}
}