on fe640cb help sign in
114 lines 3.1 kB history raw
1/*
2 * Copyright 2013 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 *
16 * Authors:
17 * Nick Dedekind <nick.dedekind@canonical.com>
18 */
20// self
21#include "modelprinter.h"
23// Qt
24#include <QTextStream>
26ModelPrinter::ModelPrinter(QObject *parent)
27 : QObject(parent)
28 , m_model(NULL)
32void ModelPrinter::setSourceModel(QAbstractItemModel * sourceModel)
34 if (m_model != NULL) {
35 disconnect(m_model);
36 }
37 if (m_model != sourceModel) {
38 m_model = sourceModel;
39 Q_EMIT modelChanged();
40 Q_EMIT textChanged();
41 }
42 if (m_model != NULL) {
43 connect(m_model, SIGNAL(modelReset()), this, SIGNAL(textChanged()));
44 connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(textChanged()));
45 connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(textChanged()));
46 }
49QAbstractItemModel* ModelPrinter::sourceModel() const
51 return m_model;
54QString ModelPrinter::text(const QModelIndex& index) const
56 return recurseString(index, 0);
59QString tabify(int level) { QString str;
60 for (int i = 0; i < level; i++) {
61 str += " ";
62 }
63 return str;
66QString ModelPrinter::recurseString(const QModelIndex& index, int level) const
68 if (!m_model)
69 return "";
71 QString str;
72 QTextStream stream(&str);
74 QHash<int, QByteArray> roleNames = m_model->roleNames();
75 QList<int> roles = roleNames.keys();
76 qSort(roles);
77 Q_FOREACH(int role, roles) {
78 QVariant vData = m_model->data(index, role);
79 if (vData.canConvert(QMetaType::QVariantMap)) {
80 QMapIterator<QString, QVariant> iter(vData.toMap());
81 while (iter.hasNext()) {
82 iter.next();
83 stream << tabify(level)
84 << roleNames[role]
85 << "."
86 << iter.key()
87 << ": "
88 << iter.value().toString()
89 << endl;
90 }
91 }
92 else {
93 stream << tabify(level)
94 << roleNames[role]
95 << ": "
96 << vData.toString()
97 << endl;
98 }
99 }
101 int rowCount = m_model->rowCount(index);
102 stream << tabify(level)
103 << "child count"
104 << ": "
105 << rowCount
106 << endl
107 << endl;
109 for (int i = 0; i < rowCount; i++) {
110 QModelIndex child = m_model->index(i, 0, index);
111 str += recurseString(child, level+1);
112 }
113 return str;