on 031898f help sign in
unity8/plugins/Unity/Indicators/modelprinter.cpp
98 lines 3.0 kB history raw
1/*
2 * Copyright (C) 2012 Canonical, Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU 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 General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
17// self
18#include "modelprinter.h"
20// Qt
21#include <QDebug>
23ModelPrinter::ModelPrinter(QObject *parent)
24 : QObject(parent)
25 , m_model(NULL)
29void ModelPrinter::setSourceModel(QAbstractItemModel * sourceModel)
31 if (m_model != NULL)
32 {
33 disconnect(m_model, SIGNAL(modelReset()), this, SIGNAL(sourceChanged()));
34 disconnect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
35 disconnect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
36 }
37 if (m_model != sourceModel)
38 {
39 m_model = sourceModel;
40 Q_EMIT modelChanged();
41 Q_EMIT sourceChanged();
42 }
43 if (m_model != NULL)
44 {
45 connect(m_model, SIGNAL(modelReset()), this, SIGNAL(sourceChanged()));
46 connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
47 connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
48 }
51QAbstractItemModel* ModelPrinter::sourceModel() const
53 return m_model;
56QString ModelPrinter::getString(const QModelIndex& index) const
58 return recurse_string(index, 0);
61QString tabify(int level) { QString str;
62 for (int i = 0; i < level; i++) {
63 str += " ";
64 }
65 return str;
68QString ModelPrinter::recurse_string(const QModelIndex& index, int level) const
70 QString str;
71 QTextStream stream(&str);
73 QHash<int, QByteArray> roleNames = m_model->roleNames();
74 QList<int> roles = roleNames.keys();
75 qSort(roles);
76 Q_FOREACH(int role, roles) {
77 QVariant vData = m_model->data(index, role);
78 if (vData.canConvert(QMetaType::QVariantMap)) {
79 QMapIterator<QString, QVariant> iter(vData.toMap());
80 while (iter.hasNext()) {
81 iter.next();
82 stream << tabify(level) << roleNames[role] << "." << iter.key() << ": " << iter.value().toString() << endl;
83 }
84 }
85 else {
86 stream << tabify(level) << roleNames[role] << ": " << vData.toString() << endl;
87 }
88 }
90 int rowCount = m_model->rowCount(index);
91 stream << tabify(level) << "child count" << ": " << rowCount << endl;
92 for (int i = 0; i < rowCount; i++)
93 {
94 QModelIndex child = m_model->index(i, 0, index);
95 str += recurse_string(child, level+1);
96 }
97 return str;