-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmydatamodel.cpp
More file actions
53 lines (53 loc) · 1.72 KB
/
mydatamodel.cpp
File metadata and controls
53 lines (53 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "mydatamodel.h"
#include <QSqlTableModel>
#include <QSqlRecord>
#include <QSqlField>
#include <QSqlError>
#include <QDebug>
#include <QSqlQueryModel>
#include <QSqlDatabase>
MyDataModel::MyDataModel(QString table_name, QSqlDatabase *db, QObject *parent) :
QObject(parent)
{
QSqlQueryModel query_model;
if(db){
this->table_model = new QSqlTableModel(parent, *db);
query_model.setQuery(QString("SELECT * FROM %1 ASC LIMIT 1").arg(table_name),*db);
}else{
this->table_model = new QSqlTableModel(parent);
query_model.setQuery(QString("SELECT * FROM %1 ASC LIMIT 1").arg(table_name));
}
this->table_model->setTable(table_name);
this->table_model->setEditStrategy(QSqlTableModel::OnManualSubmit);
this->table_model->select();
//qDebug()<<this->table_model->database().tables();
//Recovery default Record with all fiedls name
this->record = new QSqlRecord();
*this->record = query_model.record();
}
void MyDataModel::setValue(QString field, QVariant value){
/*
this->fields.append(field);
this->values.append(value);
*/
this->record->setValue(field,value);
}
int MyDataModel::submitAll(){
/*
QSqlRecord record;
for(int i=0;i<this->fields.length();++i){
record.append(QSqlField(this->fields.at(i)));
record.setValue(this->fields.at(i),this->values.at(i));
}
*/
if(!this->table_model->insertRecord(-1,*this->record)){
qDebug()<<this->table_model->lastError();
return -1;
}
if(!this->table_model->submitAll()){
qDebug()<<this->table_model->lastError();
return -1;
}
int row=this->table_model->rowCount();
return (this->table_model->record(row-1).value("id")).toInt();
}