Bitcoin Core 28.99.0
P2P Digital Currency
csvmodelwriter.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2018 The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <qt/csvmodelwriter.h>
6
7#include <QAbstractItemModel>
8#include <QFile>
9#include <QTextStream>
10
11CSVModelWriter::CSVModelWriter(const QString& _filename, QObject* parent)
12 : QObject(parent),
13 filename(_filename)
14{
15}
16
17void CSVModelWriter::setModel(const QAbstractItemModel *_model)
18{
19 this->model = _model;
20}
21
22void CSVModelWriter::addColumn(const QString &title, int column, int role)
23{
24 Column col;
25 col.title = title;
26 col.column = column;
27 col.role = role;
28
29 columns.append(col);
30}
31
32static void writeValue(QTextStream &f, const QString &value)
33{
34 QString escaped = value;
35 escaped.replace('"', "\"\"");
36 f << "\"" << escaped << "\"";
37}
38
39static void writeSep(QTextStream &f)
40{
41 f << ",";
42}
43
44static void writeNewline(QTextStream &f)
45{
46 f << "\n";
47}
48
50{
51 QFile file(filename);
52 if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
53 return false;
54 QTextStream out(&file);
55
56 int numRows = 0;
57 if(model)
58 {
59 numRows = model->rowCount();
60 }
61
62 // Header row
63 for(int i=0; i<columns.size(); ++i)
64 {
65 if(i!=0)
66 {
68 }
69 writeValue(out, columns[i].title);
70 }
72
73 // Data rows
74 for(int j=0; j<numRows; ++j)
75 {
76 for(int i=0; i<columns.size(); ++i)
77 {
78 if(i!=0)
79 {
81 }
82 QVariant data = model->index(j, columns[i].column).data(columns[i].role);
83 writeValue(out, data.toString());
84 }
86 }
87
88 file.close();
89
90 return file.error() == QFile::NoError;
91}
QList< Column > columns
CSVModelWriter(const QString &filename, QObject *parent=nullptr)
bool write()
Perform export of the model to CSV.
void setModel(const QAbstractItemModel *model)
void addColumn(const QString &title, int column, int role=Qt::EditRole)
const QAbstractItemModel * model
static void writeValue(QTextStream &f, const QString &value)
static void writeSep(QTextStream &f)
static void writeNewline(QTextStream &f)