I want to show SQL data from a local db-File in a QML-Tableview and than would like to do some edits to the sql-database. What I managed to do after about three weeks: Showing my data in a QML-Tableview. I am not sure if I really need to subclass QSqlTableModel and I definitly would be glad if subclassing would not be neccessary at all.
In my main.cpp following should create my model and directly add a record.
// Create an instance of the SqlModel for accessing the data
SqlDataModel *sqlModel;
sqlModel = new SqlDataModel(0,base.database());
sqlModel->setTable("diaBaneDatabase");
sqlModel->setSort(0, Qt::AscendingOrder);
sqlModel->setEditStrategy(QSqlTableModel::OnFieldChange);
sqlModel->select();
QSqlRecord record(sqlModel->record());
record.setValue(0,50);
record.setValue(3,222);
sqlModel->insertRecord(-1, record);
sqlModel->submitAll();
This should add 222 to the 4th column. But nothing will be stored in my sqlDatabase
My SqlDataModel::setData loolks like this:
bool SqlDataModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
qDebug() << index.column() << " " << index.row() << " " << value << " ---- " << role;
qDebug() << roles[Qt::UserRole + 1];
//qDebug() << QSqlTableModel::setData(modelIndex, value);
qDebug() << QSqlQueryModel::setData(index, value);
return false;
}
The output will be:
0 39 QVariant(int, 50) ---- 2
"id"
false
1 39 QVariant(QString, "") ---- 2
"id"
false
2 39 QVariant(QString, "") ---- 2
"id"
false
3 39 QVariant(int, 222) ---- 2
"id"
false
4 39 QVariant(double, 0) ---- 2
"id"
false
5 39 QVariant(int, 0) ---- 2
"id"
false
6 39 QVariant(double, 0) ---- 2
"id"
false
7 39 QVariant(double, 0) ---- 2
"id"
false
For sure my setData method is wrong but I don't understand what should happen there and I didn't find any example for this.
Am I wrong with my assumption that I need to subclass QSqlTableModel to be able to put the model through QQmlContext to QML and than show the columns with roles named like my column-namings? If not how could I put the content of column 1 to QMLTableview:
TableViewColumn {
role: "id" // what should be the role if I don't subclass???
title: "ID"
width: 80
}
I'm happy for any help, comment, example, other posts or whatever brings me further forward ... thanks