on 940f47f help sign in
unity8/plugins/Unity/Indicators/modelprinter.cpp
94 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 disconnect(m_model, SIGNAL(modelReset()), this, SIGNAL(sourceChanged()));
33 disconnect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
34 disconnect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
35 }
36 if (m_model != sourceModel) {
37 m_model = sourceModel;
38 Q_EMIT modelChanged();
39 Q_EMIT sourceChanged();
40 }
41 if (m_model != NULL) {
42 connect(m_model, SIGNAL(modelReset()), this, SIGNAL(sourceChanged()));
43 connect(m_model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
44 connect(m_model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SIGNAL(sourceChanged()));
45 }
48QAbstractItemModel* ModelPrinter::sourceModel() const
50 return m_model;
53QString ModelPrinter::getString(const QModelIndex& index) const
55 return recurse_string(index, 0);
58QString tabify(int level) { QString str;
59 for (int i = 0; i < level; i++) {
60 str += " ";
61 }
62 return str;
65QString ModelPrinter::recurse_string(const QModelIndex& index, int level) const
67 QString str;
68 QTextStream stream(&str);
70 QHash<int, QByteArray> roleNames = m_model->roleNames();
71 QList<int> roles = roleNames.keys();
72 qSort(roles);
73 Q_FOREACH(int role, roles) {
74 QVariant vData = m_model->data(index, role);
75 if (vData.canConvert(QMetaType::QVariantMap)) {
76 QMapIterator<QString, QVariant> iter(vData.toMap());
77 while (iter.hasNext()) {
78 iter.next();
79 stream << tabify(level) << roleNames[role] << "." << iter.key() << ": " << iter.value().toString() << endl;
80 }
81 }
82 else {
83 stream << tabify(level) << roleNames[role] << ": " << vData.toString() << endl;
84 }
85 }
87 int rowCount = m_model->rowCount(index);
88 stream << tabify(level) << "child count" << ": " << rowCount << endl;
89 for (int i = 0; i < rowCount; i++) {
90 QModelIndex child = m_model->index(i, 0, index);
91 str += recurse_string(child, level+1);
92 }
93 return str;