Dash Core Source Documentation (0.16.0.1)

Find detailed information regarding the Dash Core source code.

csvmodelwriter.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2014 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 
11 CSVModelWriter::CSVModelWriter(const QString &_filename, QObject *parent) :
12  QObject(parent),
13  filename(_filename), model(0)
14 {
15 }
16 
17 void CSVModelWriter::setModel(const QAbstractItemModel *_model)
18 {
19  this->model = _model;
20 }
21 
22 void 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 
32 static void writeValue(QTextStream &f, const QString &value)
33 {
34  QString escaped = value;
35  escaped.replace('"', "\"\"");
36  f << "\"" << escaped << "\"";
37 }
38 
39 static void writeSep(QTextStream &f)
40 {
41  f << ",";
42 }
43 
44 static 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  {
67  writeSep(out);
68  }
69  writeValue(out, columns[i].title);
70  }
71  writeNewline(out);
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  {
80  writeSep(out);
81  }
82  QVariant data = model->index(j, columns[i].column).data(columns[i].role);
83  writeValue(out, data.toString());
84  }
85  writeNewline(out);
86  }
87 
88  file.close();
89 
90  return file.error() == QFile::NoError;
91 }
void addColumn(const QString &title, int column, int role=Qt::EditRole)
QList< Column > columns
static void writeValue(QTextStream &f, const QString &value)
static void writeSep(QTextStream &f)
const QAbstractItemModel * model
CSVModelWriter(const QString &filename, QObject *parent=0)
void setModel(const QAbstractItemModel *model)
static void writeNewline(QTextStream &f)
bool write()
Perform export of the model to CSV.
Released under the MIT license