-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmymodel.cpp
90 lines (75 loc) · 2.19 KB
/
mymodel.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include "mymodel.h"
#include <QSqlQuery>
#include <QSqlError>
MyModel::MyModel(QObject *parent)
: QAbstractTableModel(parent)
{
fetchData(); // Fetch data when the model is created
}
int MyModel::rowCount(const QModelIndex & /*parent*/) const
{
return m_data.size();
}
int MyModel::columnCount(const QModelIndex & /*parent*/) const
{
if (m_data.isEmpty()){
qDebug() << "test1";
return 0;
}
else{
qDebug() << "test2";
return m_data.first().size();
}
}
QVariant MyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role == Qt::DisplayRole && orientation == Qt::Horizontal) {
// Fetch headers from the first row
if (section >= 0 && section < m_data.first().size())
return m_data.first().at(section);
}
return QVariant();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (role == Qt::DisplayRole) {
// Fetch data from the corresponding row and column
if (index.row() >= 0 && index.row() < m_data.size() &&
index.column() >= 0 && index.column() < m_data.first().size()) {
return m_data.at(index.row()).at(index.column());
}
}
return QVariant();
}
void MyModel::fetchData()
{
// Clear existing data
beginResetModel();
m_data.clear();
endResetModel();
QString queryStr = QString("SELECT `Latitude`, `Longitude`, `Node Id`, `sigPowS`,`sigQualS`, `sigQualSName` FROM Drive_Test");
QSqlQuery query(queryStr);
if(!query.exec()){
qDebug() << "Query Error:" << query.lastError().text();
return;
}
// Fetch column names
QStringList headers;
for (int i = 0; i < query.record().count(); ++i) {
headers << query.record().fieldName(i);
}
m_data[0].append(headers);
// Fetch data rows
while (query.next()) {
QList<QVariant> row;
for (int i = 0; i < query.record().count(); ++i) {
row.append(query.value(i));
}
m_data.append(row);
}
// Emit signal to notify views that the model data has changed
beginResetModel();
endResetModel();
}