Subclassing QSqlTableModel Insert New Value
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 d
Solution 1:
I've been working on an example.
Some notes:
- QML items such as
TableView
require a model so I think aQSqlTableModel
is a very good option. Of course, you have other models that could be used to handle items of data. - In the class
MySqlTableModel
you will see the required role names.MySqlTableModel
reimplementsroleNames()
to expose the role names, so that they can be accessed via QML. - You could reimplement the
setData
method inMySqlTableModel
, but I think it is better to use the methodinsertRecord
provided byQSqlTableModel
.
I hope this example will help you to fix your errors.
main.cpp
#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "mysqltablemodel.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("mydb");
if(!db.open()) {
qDebug() << db.lastError().text();
return 0;
}
QSqlQuery query(db);
if(!query.exec("DROP TABLE IF EXISTS mytable")) {
qDebug() << "create table error: " << query.lastError().text();
return 0;
}
if(!query.exec("CREATE TABLE IF NOT EXISTS mytable \
(id integer primary key autoincrement, name varchar(15), salary integer)")) {
qDebug() << "create table error: " << query.lastError().text();
return 0;
}
MySqlTableModel *model = new MySqlTableModel(0, db);
model->setTable("mytable");
model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->select();
QSqlRecord rec = model->record();
rec.setValue(1, "peter");
rec.setValue(2, 100);
model->insertRecord(-1, rec);
rec.setValue(1, "luke");
rec.setValue(2, 200);
model->insertRecord(-1, rec);
if(model->submitAll()) {
model->database().commit();
} else {
model->database().rollback();
qDebug() << "database error: " << model->lastError().text();
}
QQmlApplicationEngine engine;
QQmlContext *ctxt = engine.rootContext();
ctxt->setContextProperty("myModel", model);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
mysqltablemodel.h
#ifndef MYSQLTABLEMODEL_H
#define MYSQLTABLEMODEL_H
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QSqlError>
#include <QSqlQuery>
#include <QDebug>
class MySqlTableModel : public QSqlTableModel
{
Q_OBJECT
public:
MySqlTableModel(QObject *parent = 0, QSqlDatabase db = QSqlDatabase());
Q_INVOKABLE QVariant data(const QModelIndex &index, int role=Qt::DisplayRole ) const;
Q_INVOKABLE void addItem(const QString &name, const QString &salary);
protected:
QHash<int, QByteArray> roleNames() const;
private:
QHash<int, QByteArray> roles;
};
#endif // MYSQLTABLEMODEL_H
mysqltablemodel.cpp
#include "mysqltablemodel.h"
MySqlTableModel::MySqlTableModel(QObject *parent, QSqlDatabase db): QSqlTableModel(parent, db) {}
QVariant MySqlTableModel::data ( const QModelIndex & index, int role ) const
{
if(index.row() >= rowCount()) {
return QString("");
}
if(role < Qt::UserRole) {
return QSqlQueryModel::data(index, role);
}
else {
return QSqlQueryModel::data(this->index(index.row(), role - Qt::UserRole), Qt::DisplayRole);
}
}
QHash<int, QByteArray> MySqlTableModel::roleNames() const
{
QHash<int, QByteArray> roles;
roles[Qt::UserRole + 1] = "name";
roles[Qt::UserRole + 2] = "salary";
return roles;
}
void MySqlTableModel::addItem(const QString &name, const QString &salary)
{
QSqlRecord rec = this->record();
rec.setValue(1, name);
rec.setValue(2, salary.toInt());
this->insertRecord(-1, rec);
if(this->submitAll()) {
this->database().commit();
} else {
this->database().rollback();
qDebug() << "database error: " << this->lastError().text();
}
}
main.qml
import QtQuick 2.4
import QtQuick.Controls 1.3
import QtQuick.Window 2.2
import QtQuick.Dialogs 1.2
ApplicationWindow {
title: qsTr("Hello World")
width: 640
height: 480
visible: true
TableView {
id: tableView
anchors.fill: parent
TableViewColumn {
role: "name"
title: "Name"
width: 200
}
TableViewColumn {
role: "salary"
title: "Salary"
width: 200
}
model: myModel
}
Button {
id: addButton
anchors.verticalCenter: parent.verticalCenter
text: "Add item"
onClicked: {
if (nameBox.text || salaryBox.text) {
myModel.addItem(nameBox.text, salaryBox.text)
}
}
}
TextField {
id: nameBox
placeholderText: "name"
anchors.verticalCenter: parent.verticalCenter
anchors.left: addButton.right
anchors.leftMargin: 5
}
TextField {
id: salaryBox
placeholderText: "salary"
anchors.verticalCenter: parent.verticalCenter
anchors.left: nameBox.right
anchors.leftMargin: 5
}
}
Post a Comment for "Subclassing QSqlTableModel Insert New Value"