-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqcsvlistmodel.cpp
More file actions
102 lines (80 loc) · 2.03 KB
/
qcsvlistmodel.cpp
File metadata and controls
102 lines (80 loc) · 2.03 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
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
91
92
93
94
95
96
97
98
99
100
101
102
#include "qcsvlistmodel.h"
#include "qmodels_log.h"
QCsvListModel::QCsvListModel(QObject *parent) :
QVariantListModel(parent)
{
}
bool QCsvListModel::loadPath(const QString& fileName)
{
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
{
QMODELSLOG_WARNING()<<"Error opening file:"<<file.errorString();
return false;
}
bool ret = loadCsv(file.readAll());
file.close();
return ret;
}
bool QCsvListModel::loadCsv(const QByteArray& csv)
{
QTextStream fileStream(csv);
QVariantList storage;
do
{
QString line = fileStream.readLine();
const QStringList values = line.split(m_separator);
QVariantMap map;
int pos=0;
for(const QString& value: values)
{
map.insert(QString("column_%1").arg(pos), value);
pos++;
}
storage.append(map);
}
while(!fileStream.atEnd());
return setStorage(storage);
}
bool QCsvListModel::syncPath(const QString& fileName) const
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
QMODELSLOG_WARNING()<<"cannot open file:"<<fileName;
return false;
}
bool ret = file.write(toCsv());
file.close();
return ret;
}
QByteArray QCsvListModel::toCsv() const
{
QByteArray csv;
for(const QVariant& variant: storage())
{
QByteArray csvLine;
const QVariantMap values = variant.toMap();
for (QVariantMap::const_iterator it = values.begin(); it != values.end(); ++it)
{
csvLine.append(it.value().toString());
csvLine.append(separator());
}
csvLine.chop(1);
csvLine.append('\n');
csv.append(csvLine);
}
return csv;
}
char QCsvListModel::separator() const
{
return m_separator;
}
bool QCsvListModel::setSeparator(char separator)
{
if(m_separator==separator)
return false;
m_separator=separator;
emit this->separatorChanged(m_separator);
return true;
}