1 /* This file is part of qjson
3 * Copyright (C) 2009 Till Adam <adam@kde.org>
4 * Copyright (C) 2009 Flavio Castelli <flavio@castelli.name>
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License version 2.1, as published by the Free Software Foundation.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this library; see the file COPYING.LIB. If not, write to
18 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 * Boston, MA 02110-1301, USA.
23 #include "qobjecthelper.h"
25 #include <QtCore/QMetaObject>
26 #include <QtCore/QMetaProperty>
27 #include <QtCore/QObject>
29 using namespace QJson;
31 class QObjectHelper::QObjectHelperPrivate {
34 QObjectHelper::QObjectHelper()
35 : d (new QObjectHelperPrivate)
39 QObjectHelper::~QObjectHelper()
44 QVariantMap QObjectHelper::qobject2qvariant( const QObject* object,
45 const QStringList& ignoredProperties)
48 const QMetaObject *metaobject = object->metaObject();
49 int count = metaobject->propertyCount();
50 for (int i=0; i<count; ++i) {
51 QMetaProperty metaproperty = metaobject->property(i);
52 const char *name = metaproperty.name();
54 if (ignoredProperties.contains(QLatin1String(name)) || (!metaproperty.isReadable()))
57 QVariant value = object->property(name);
58 result[QLatin1String(name)] = value;
63 void QObjectHelper::qvariant2qobject(const QVariantMap& variant, QObject* object)
65 const QMetaObject *metaobject = object->metaObject();
67 QVariantMap::const_iterator iter;
68 for (iter = variant.constBegin(); iter != variant.constEnd(); ++iter) {
69 int pIdx = metaobject->indexOfProperty( iter.key().toAscii() );
75 QMetaProperty metaproperty = metaobject->property( pIdx );
76 QVariant::Type type = metaproperty.type();
77 QVariant v( iter.value() );
78 if ( v.canConvert( type ) ) {
80 metaproperty.write( object, v );
81 } else if (QString(QLatin1String("QVariant")).compare(QLatin1String(metaproperty.typeName())) == 0) {
82 metaproperty.write( object, v );