-
Notifications
You must be signed in to change notification settings - Fork 0
/
qdatabasemodels.cpp
71 lines (56 loc) · 1.68 KB
/
qdatabasemodels.cpp
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "qdatabasemodels.h"
#include <QSqlError>
QSqlQmlTableModel::QSqlQmlTableModel(QSqlDatabase db):QSqlTableModel(Q_NULLPTR,db)
{
setEditStrategy(QSqlTableModel::OnManualSubmit);
}
bool QSqlQmlTableModel::selectTable(const QString &tableName)
{
setTable(tableName);
QSqlError err = lastError();
if (err.isValid()){
qCritical() << "Error with setTable:" << err.text();
return false;
}
if ( !generateRoleNames()) return false;
return select();
}
QVariant QSqlQmlTableModel::data ( const QModelIndex & index, int role ) const
{
if(index.row() >= rowCount())
return QString("");
if(role < Qt::UserRole)
return QSqlQueryModel::data(index, role);
else
{
int columnIdx = role - Qt::UserRole - 1;
QModelIndex modelIndex = this->index(index.row(), columnIdx);
QVariant value = QSqlQueryModel::data(modelIndex, Qt::DisplayRole);
return value;
}
}
bool QSqlQmlTableModel::generateRoleNames()
{
roles.clear();
int nbCols = this->columnCount();
//qInfo() << "Retrieve " << nbCols << "field from table";
for (int i = 0; i < nbCols; i++)
roles[Qt::UserRole + i + 1] = QVariant(this->headerData(i, Qt::Horizontal).toString()).toByteArray();
return nbCols > 0;
}
int QSqlQmlTableModel::selectedRow()
{
return m_selectedRow;
}
void QSqlQmlTableModel::setSelectedRow(int _selectedRow)
{
m_selectedRow = _selectedRow;
m_selectedRecord = record(m_selectedRow);
emit selectedRowChanged();
}
QVariant QSqlQmlTableModel::selectedData(QString fieldName)
{
//qDebug() << m_selectedRecord;
QVariant var = m_selectedRecord.value( fieldName);
return var;
}