Beispiel #1
0
qObjectnode::
qObjectnode(QObject *data, QGraphicsItem *parent, bool autodelete) : GraphicsNode(parent),m_autodelete(autodelete)
{
	m_data=data;
	if(m_data==0)
		qWarning("NULL Data Object!");
	else {
		QWidget* tst = dynamic_cast<QWidget*>(data);
		if(tst!=0)
			setCentralWidget(tst);

		const QMetaObject* m = m_data->metaObject();
		int property_count = m->propertyCount()-1;

		for(;property_count>=0;property_count--) {
			QMetaProperty prop = m->property(property_count);
			if(prop.isConstant() || !prop.isUser())
				continue;
			if(prop.isReadable() && prop.hasNotifySignal())
			{
				add_source(QString(prop.name()) + "[" +QString(prop.typeName())  +"]",m_data,property_count);
			}
			if(prop.isWritable())
				add_sink(QString(prop.name()) + "[" +QString(prop.typeName())  +"]",m_data,property_count);
		}
	}
}
QVariant ObjectStaticPropertyModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid() || !m_obj || index.row() < 0 ||
      index.row() >= m_obj.data()->metaObject()->propertyCount()) {
    return QVariant();
  }

  const QMetaProperty prop = m_obj.data()->metaObject()->property(index.row());
  if (role == Qt::DisplayRole) {
    if (index.column() == 0) {
      return prop.name();
    } else if (index.column() == 1) {
      // QMetaProperty::read sets QVariant::typeName to int for enums,
      // so we need to handle that separately here
      const QVariant value = prop.read(m_obj.data());
      const QString enumStr = Util::enumToString(value, prop.typeName(), m_obj.data());
      if (!enumStr.isEmpty()) {
        return enumStr;
      }
      return VariantHandler::displayString(value);
    } else if (index.column() == 2) {
      return prop.typeName();
    } else if (index.column() == 3) {
      const QMetaObject *mo = m_obj.data()->metaObject();
      while (mo->propertyOffset() > index.row()) {
        mo = mo->superClass();
      }
      return mo->className();
    }
  } else if (role == Qt::DecorationRole) {
    if (index.column() == 1) {
      return VariantHandler::decoration(prop.read(m_obj.data()));
    }
  } else if (role == Qt::EditRole) {
    if (index.column() == 1) {
      return prop.read(m_obj.data());
    }
  } else if (role == Qt::ToolTipRole) {
    const QString toolTip =
      tr("Constant: %1\nDesignable: %2\nFinal: %3\nResetable: %4\n"
         "Has notification: %5\nScriptable: %6\nStored: %7\nUser: %8\nWritable: %9").
      arg(translateBool(prop.isConstant())).
      arg(translateBool(prop.isDesignable(m_obj.data()))).
      arg(translateBool(prop.isFinal())).
      arg(translateBool(prop.isResettable())).
      arg(translateBool(prop.hasNotifySignal())).
      arg(translateBool(prop.isScriptable(m_obj.data()))).
      arg(translateBool(prop.isStored(m_obj.data()))).
      arg(translateBool(prop.isUser(m_obj.data()))).
      arg(translateBool(prop.isWritable()));
    return toolTip;
  }

  return QVariant();
}
Beispiel #3
0
static int writeProperty(QObject *obj, const QByteArray &property_name, QVariant value,
                         int propFlags = QDBusConnection::ExportAllProperties)
{
    const QMetaObject *mo = obj->metaObject();
    int pidx = mo->indexOfProperty(property_name);
    if (pidx == -1) {
        // this object has no property by that name
        return PropertyNotFound;
    }

    QMetaProperty mp = mo->property(pidx);

    // check if this property is writable
    if (!mp.isWritable())
        return PropertyReadOnly;

    // check if this property is exported
    bool isScriptable = mp.isScriptable();
    if (!(propFlags & QDBusConnection::ExportScriptableProperties) && isScriptable)
        return PropertyNotFound;
    if (!(propFlags & QDBusConnection::ExportNonScriptableProperties) && !isScriptable)
        return PropertyNotFound;

    // we found our property
    // do we have the right type?
    int id = mp.userType();
    if (!id){
        // type not registered or invalid / void?
        qWarning("QDBusConnection: Unable to handle unregistered datatype '%s' for property '%s::%s'",
                 mp.typeName(), mo->className(), property_name.constData());
        return PropertyWriteFailed;
    }

    if (id != QMetaType::QVariant && value.userType() == QDBusMetaTypeId::argument()) {
        // we have to demarshall before writing
        void *null = 0;
        QVariant other(id, null);
        if (!QDBusMetaType::demarshall(qvariant_cast<QDBusArgument>(value), id, other.data())) {
            qWarning("QDBusConnection: type `%s' (%d) is not registered with QtDBus. "
                     "Use qDBusRegisterMetaType to register it",
                     mp.typeName(), id);
            return PropertyWriteFailed;
        }

        value = other;
    }

    if (mp.userType() == qMetaTypeId<QDBusVariant>())
        value = QVariant::fromValue(QDBusVariant(value));

    // the property type here should match
    return mp.write(obj, value) ? PropertyWriteSuccess : PropertyWriteFailed;
}
Beispiel #4
0
QSObject QSAEditor::queryQSObject( const QMetaObject *meta, const QString &property, bool /*includeSuperClass*/ ) const
{
    int propertyIndex = -1;
    const QMetaObject *m = meta;
    propertyIndex = m->indexOfProperty(property.toLatin1().constData());

    if (propertyIndex >= 0) {
        QMetaProperty mp = m->property(propertyIndex);
        QSObject o = vTypeToQSType( QString::fromLatin1(mp.typeName()) );
	    if ( !o.isNull() && !o.isUndefined() )
	        return o;
    }

    m = meta;
    for (int i=0; i<m->methodCount(); ++i) {
        QMetaMethod mm = m->method(i);

        if (mm.methodType() == QMetaMethod::Slot) {
            QString n = QLatin1String(mm.methodSignature());
	        n = n.left(n.indexOf('('));
	        if ( property != n )
		        continue;

            return vTypeToQSType(mm.typeName());
        }
    }

    return env()->createUndefined();
}
Beispiel #5
0
QWidget* Enums::createEditor(QWidget * parent, const QModelIndex & index)
{
    Q_UNUSED(index);

    const QMetaObject * metaObject = object()->metaObject();
    QMetaProperty metaProperty = metaObject->property(objectProperty());
    const char *typeName = metaProperty.typeName();
    int enumIdx = metaObject->indexOfEnumerator(typeName);

    QStringList excludeList;

    if (int index = metaObject->indexOfProperty(QString("_%1_exclude").arg(metaProperty.name()).toLatin1())) {
        excludeList = metaObject->property(index).read(object()).toStringList();
    }

    cb = new QComboBox(parent);

    for (int en = 0; en < metaObject->enumerator(enumIdx).keyCount(); ++en) {
        QString itemName = metaObject->enumerator(enumIdx).key(en);
        int itemData = metaObject->enumerator(enumIdx).value(en);
        if (!excludeList.contains(itemName))
            cb->insertItem(en, itemName, itemData);
    }

    connect(cb, SIGNAL(currentIndexChanged(int)), this, SLOT(setValue(int)));

    return cb;
}
Beispiel #6
0
static QVariantMap readAllProperties(QObject *object, int flags)
{
    QVariantMap result;
    const QMetaObject *mo = object->metaObject();

    // QObject has properties, so don't start from 0
    for (int i = QObject::staticMetaObject.propertyCount(); i < mo->propertyCount(); ++i) {
        QMetaProperty mp = mo->property(i);

        // is it readable?
        if (!mp.isReadable())
            continue;

        // is it a registered property?
        int typeId = qDBusNameToTypeId(mp.typeName());
        if (!typeId)
            continue;
        const char *signature = QDBusMetaType::typeToSignature(typeId);
        if (!signature)
            continue;

        // is this property visible from the outside?
        if ((mp.isScriptable() && flags & QDBusConnection::ExportScriptableProperties) ||
            (!mp.isScriptable() && flags & QDBusConnection::ExportNonScriptableProperties)) {
            // yes, it's visible
            QVariant value = mp.read(object);
            if (value.isValid())
                result.insert(QString::fromLatin1(mp.name()), value);
        }
    }

    return result;
}
Beispiel #7
0
// Creates a string, describing an object, using meta-object introspection
QString objToString(const QObject *obj) {
    QStringList result;
    const QMetaObject *meta = obj->metaObject();
    result += QString("class %1 : public %2 {").arg(meta->className())
            .arg(meta->superClass()->className());
    for (auto i=0; i < meta->propertyCount(); ++i) {
        const QMetaProperty property = meta->property(i);
        QVariant value = obj->property(property.name());
        if (value.canConvert(QVariant::String))
            result += QString("  %1 %2 = %3;")
                    .arg(property.typeName())
                    .arg(property.name())
                    .arg(value.toString());
    }

    QString signalPrefix("");
    for (auto i=0; i < meta->methodCount(); ++i) {
        const QMetaMethod method = meta->method(i);
        const QMetaMethod::MethodType methodType = method.methodType();
        if (methodType == QMetaMethod::Signal)
            signalPrefix = QStringLiteral("Q_SIGNAL");
        else if (methodType == QMetaMethod::Slot)
            signalPrefix = QStringLiteral("Q_SLOT");
        result += QString("  %1 %2 %3;")
                .arg(signalPrefix)
                .arg(QVariant::typeToName(method.returnType()))
                .arg(QString(method.methodSignature()));
    }
    result += "};";
    return result.join("\n");
}
void QDBusViewer::setProperty(const BusSignature &sig)
{
    QDBusInterface iface(sig.mService, sig.mPath, sig.mInterface, c);
    QMetaProperty prop = iface.metaObject()->property(iface.metaObject()->indexOfProperty(sig.mName.toLatin1()));

    bool ok;
    QString input = QInputDialog::getText(this, tr("Arguments"),
                    tr("Please enter the value of the property %1 (type %2)").arg(
                        sig.mName, QString::fromLatin1(prop.typeName())),
                    QLineEdit::Normal, QString(), &ok);
    if (!ok)
        return;

    QVariant value = input;
    if (!value.convert(prop.type())) {
        QMessageBox::warning(this, tr("Unable to marshall"),
                tr("Value conversion failed, unable to set property"));
        return;
    }

    QDBusMessage message = QDBusMessage::createMethodCall(sig.mService, sig.mPath, QLatin1String("org.freedesktop.DBus.Properties"), QLatin1String("Set"));
    QList<QVariant> arguments;
    arguments << sig.mInterface << sig.mName << qVariantFromValue(QDBusVariant(value));
    message.setArguments(arguments);
    c.callWithCallback(message, this, SLOT(dumpMessage(QDBusMessage)));

}
Beispiel #9
0
extern "C" SEXP qt_qproperties(SEXP x) {
  const QMetaObject *meta = unwrapSmoke(x, QMetaObject);
  int n = meta->propertyCount();
  
  SEXP ans, ans_type, ans_name, ans_readable, ans_writable;
  PROTECT(ans = allocVector(VECSXP, 4));
  ans_name = allocVector(STRSXP, n);
  SET_VECTOR_ELT(ans, 0, ans_name);
  ans_type = allocVector(STRSXP, n);
  SET_VECTOR_ELT(ans, 1, ans_type);
  ans_readable = allocVector(LGLSXP, n);
  SET_VECTOR_ELT(ans, 2, ans_readable);
  ans_writable = allocVector(LGLSXP, n);
  SET_VECTOR_ELT(ans, 3, ans_writable);
  
  for (int i = 0; i < n; i++) {
    QMetaProperty metaProperty = meta->property(i);
    SET_STRING_ELT(ans_type, i, mkChar(metaProperty.typeName()));
    SET_STRING_ELT(ans_name, i, mkChar(metaProperty.name()));
    LOGICAL(ans_readable)[i] = metaProperty.isReadable();
    LOGICAL(ans_writable)[i] = metaProperty.isWritable();
  }
  
  UNPROTECT(1);
  return ans;
}
Beispiel #10
0
 ExpressionType type(const QByteArray& name, const QMetaProperty& prop) const
 {
     ExpressionType typeGet(ExpressionType::Lambda);
     typeGet.addParameter(ExpressionType(name))
         .addParameter(toExpressionType(prop.type(), prop.typeName()));
     
     return typeGet;
 }
Beispiel #11
0
bool QObject::setProperty(const char *name, const QVariant &value)
{
   const QMetaObject* metaObj = metaObject();

   if (! name || ! metaObj) {
      return false;
   }

   int index = metaObj->indexOfProperty(name);

   if (index < 0) {
      const int k = m_extra_propertyNames.indexOf(name);

      if (value.isValid()) {
         // add or update dynamic property

         if (k == -1) {
            m_extra_propertyNames.append(name);
            m_extra_propertyValues.append(value);

         } else {
            m_extra_propertyValues[k] = value;

         }

      } else {
         // remove dynamic property

         if (k == -1) {
            return false;
         }

         m_extra_propertyNames.removeAt(k);
         m_extra_propertyValues.removeAt(k);
      }

      QDynamicPropertyChangeEvent event(name);
      QCoreApplication::sendEvent(this, &event);

      return false;
   }

   QMetaProperty p = metaObj->property(index);

   if (! p.isWritable()) {
      qWarning("%s::setProperty() Property \"%s\" is invalid, read only, or does not exist", metaObj->className(), name);
   }

   //
   bool retval = p.write(this, value);

   if (! retval) {
      qWarning("%s::setProperty() Set property \"%s\" failed. Passed value is of type %s, property is of type %s",
                     metaObj->className(), name, value.typeName(), p.typeName() );
   }

   return retval;
}
void QJnextMainLoop::set(QObject *object, QVariantList& args,
		QByteArray* retval) {
	QByteArray property = args.takeFirst().toByteArray();

	const QMetaObject * meta = object->metaObject();
	int propertyIndex = meta->indexOfProperty(property);
	if (propertyIndex < 0) {
		retval->append("No such property " + property);
		return;
	}

	QMetaProperty metaprop = meta->property(propertyIndex);
	if (!metaprop.isWritable()) {
		retval->append("Property " + property + " is not writable");
		return;
	}
	QVariant vValue = args.takeFirst();

	/* handle enum inputs as text */
	if (metaprop.isEnumType()) {
		int id;
		const QMetaEnum &enumerator = metaprop.enumerator();
		QByteArray keys;
		for (int i = 0; i < enumerator.keyCount(); ++i)
			keys += enumerator.key(i) + QByteArray(" ");
#ifdef DEBUG_QJnextMainLoop
		qDebug() << "[QJnextMainLoop]\tEnumerator" << enumerator.isFlag() << enumerator.scope() << enumerator.name() <<
		keys;
#endif

		if (enumerator.isFlag())
			id = enumerator.keyToValue(vValue.toByteArray().constData());
		else
			id = enumerator.keysToValue(vValue.toByteArray().constData());

		if (id != -1)
			vValue = QVariant(id);
	}
#ifdef DEBUG_QJnextMainLoop
	qDebug() << "[QJnextMainLoop]\tSET" << meta->className() << property << vValue
	<< vValue.canConvert(metaprop.type());
#endif

	if (!vValue.convert(metaprop.type())) {
		retval->append(
				"Unable to convert \"" + vValue.toByteArray() + "\" to "
						+ metaprop.typeName());
		return;
	}

	if (!metaprop.write(object, vValue))
		retval->append(
				QByteArray("Unable to set property ") + meta->className() + "."
						+ property + " to " + vValue.toByteArray());
	else
		*retval = QByteArray();
}
Beispiel #13
0
QVariant QDBusAbstractInterfacePrivate::property(const QMetaProperty &mp) const
{
    if (!connection.isConnected())    // not connected
        return QVariant();

    // try to read this property
    QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
                       QLatin1String(DBUS_INTERFACE_PROPERTIES),
                       QLatin1String("Get"));
    msg << interface << QString::fromUtf8(mp.name());
    QDBusMessage reply = connection.call(msg, QDBus::Block);

    if (reply.type() == QDBusMessage::ReplyMessage && reply.arguments().count() == 1 &&
            reply.signature() == QLatin1String("v")) {
        QVariant value = qvariant_cast<QDBusVariant>(reply.arguments().at(0)).variant();

        // make sure the type is right
        if (qstrcmp(mp.typeName(), value.typeName()) == 0) {
            if (mp.type() == QVariant::LastType)
                // QVariant is special in this context
                return qvariant_cast<QDBusVariant>(reply.arguments().at(0)).variant();

            return value;
        }
    }

    // there was an error...
    if (reply.type() == QDBusMessage::ErrorMessage)
        lastError = reply;
    else if (reply.signature() != QLatin1String("v")) {
        QString errmsg = QLatin1String("Invalid signature `%1' in return from call to "
                                       DBUS_INTERFACE_PROPERTIES);
        lastError = QDBusError(QDBusError::InvalidSignature, errmsg.arg(reply.signature()));
    } else {
        QString errmsg = QLatin1String("Unexpected type `%1' when retrieving property "
                                       "`%2 %3.%4'");
        lastError = QDBusError(QDBusError::InvalidSignature,
                               errmsg.arg(QLatin1String(reply.arguments().at(0).typeName()),
                                          QLatin1String(mp.typeName()),
                                          interface, QString::fromUtf8(mp.name())));
    }

    return QVariant();
}
QVariant Properties::data( const QModelIndex & index, int role ) const
{
    if ( getTarget() == nullptr )
        return QVariant();

    QList< QByteArray > dynamicProperties = getTarget()->dynamicPropertyNames( );
    int staticPropertyCount = getTarget()->metaObject( )->propertyCount( )
                                            - _hiddenStaticPropertiesCount;
    int propertyCount = getTarget()->metaObject( )->propertyCount( ) + dynamicProperties.size( );

    QString propertyName( "" );
    QString propertyType( "" );
    bool    propertyIsEnum( false );

    if ( index.row( ) >= 0 && index.row( ) < staticPropertyCount ) {   // Dealing with static properties
        QMetaProperty staticProperty = getTarget()->metaObject( )->property( _hiddenStaticPropertiesCount + index.row( ) );
        propertyName = ( staticProperty.name( ) != nullptr ? QString( staticProperty.name( ) ) : "" );
        propertyType = ( staticProperty.typeName( ) != nullptr ? QString( staticProperty.typeName( ) ) : "" );
    }
    else if ( index.row( ) >= staticPropertyCount &&    // Dealing with dynamic properties
         index.row( ) < propertyCount ) {
        int dynamicPropertyIndex = index.row( ) - staticPropertyCount;
        propertyName = dynamicProperties.at( dynamicPropertyIndex );
        propertyType = getTarget()->property( propertyName.toLatin1( ) ).typeName( );
        qDebug() << "propertyType=" << propertyType;
        propertyIsEnum = isEnum( propertyName );
    }

    if ( !propertyName.isEmpty( ) && !propertyType.isEmpty( ) )
    {
        if ( role == PropertyNameRole )
            return propertyName;
        else if ( role == PropertyTypeRole )
            return propertyType;
        else if ( role == PropertyIsEnumRole )
            return propertyIsEnum;
        else if ( role == PropertyDataRole )
            return property( propertyName.toLatin1( ) );
        else if ( role == PropertyOptionsRole )
            return QVariant::fromValue< qps::Options* >( const_cast< qps::Properties* >( this )->getPropertyOptions( propertyName ) ); // Return the corresponding options object for the requested property
    }

    return data( index, role );
}
void listInterface(const QString &service, const QString &path, const QString &interface)
{
    QDBusInterfacePtr iface(*connection, service, path, interface);
    if (!iface->isValid()) {
        QDBusError err(iface->lastError());
        fprintf(stderr, "Interface '%s' not available in object %s at %s:\n%s (%s)\n",
                qPrintable(interface), qPrintable(path), qPrintable(service),
                qPrintable(err.name()), qPrintable(err.message()));
        exit(1);
    }
    const QMetaObject *mo = iface->metaObject();

    // properties
    for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
        QMetaProperty mp = mo->property(i);
        printf("property ");

        if (mp.isReadable() && mp.isWritable())
            printf("readwrite");
        else if (mp.isReadable())
            printf("read");
        else
            printf("write");

        printf(" %s %s.%s\n", mp.typeName(), qPrintable(interface), mp.name());
    }

    // methods (signals and slots)
    for (int i = mo->methodOffset(); i < mo->methodCount(); ++i) {
        QMetaMethod mm = mo->method(i);

        QByteArray signature = mm.signature();
        signature.truncate(signature.indexOf('('));
        printf("%s %s%s%s %s.%s(",
               mm.methodType() == QMetaMethod::Signal ? "signal" : "method",
               mm.tag(), *mm.tag() ? " " : "",
               *mm.typeName() ? mm.typeName() : "void",
               qPrintable(interface), signature.constData());

        QList<QByteArray> types = mm.parameterTypes();
        QList<QByteArray> names = mm.parameterNames();
        bool first = true;
        for (int i = 0; i < types.count(); ++i) {
            printf("%s%s",
                   first ? "" : ", ",
                   types.at(i).constData());
            if (!names.at(i).isEmpty())
                printf(" %s", names.at(i).constData());
            first = false;
        }
        printf(")\n");
    }
}
Beispiel #16
0
PropertyWidget* GooeyEngine::CreatePropertyWidget(Block* block, kint propertyIndex)
{
	QMetaProperty property = block->metaObject()->property(propertyIndex);
	QString type = QString::fromAscii(property.typeName());

	const QMetaObject* mo = Instance()->_inputWidgets.value(type, K_NULL);
	if(mo == K_NULL)
	{
		qWarning("GooeyEngine / Could not find property widget for type %s !", property.typeName());
		return K_NULL;
	}

	// Create an instance
	PropertyWidget* widget = static_cast<PropertyWidget*>(mo->newInstance());
	// Setup the data
	widget->setData(block, propertyIndex);
	// Build the UI
	widget->update();

	return widget;
}
Beispiel #17
0
const char* getpropertytype(QObject* obj, const char* propname, bool includesuper)
{
	const QMetaObject* objmeta = obj->metaObject();
	int i = objmeta->indexOfProperty(propname);
	if (i == -1)
		return NULL;
	QMetaProperty propmeta = objmeta->property(i);
	if (!propmeta.isValid())
		return NULL;
	const char* type = propmeta.typeName();
	return type;
}
Beispiel #18
0
void MetaInfoPrivate::parseProperties(NodeMetaInfo &nodeMetaInfo, const QMetaObject *qMetaObject) const
{
    Q_ASSERT_X(qMetaObject, Q_FUNC_INFO, "invalid QMetaObject");
    Q_ASSERT_X(nodeMetaInfo.isValid(), Q_FUNC_INFO, "invalid NodeMetaInfo");

    for (int i = qMetaObject->propertyOffset(); i < qMetaObject->propertyCount(); ++i) {
        QMetaProperty qProperty = qMetaObject->property(i);

        PropertyMetaInfo propertyInfo;

        propertyInfo.setName(QLatin1String(qProperty.name()));

        QString typeName(qProperty.typeName());
        QString noStar = typeName;
        bool star = false;
        while (noStar.contains('*')) {//strip star
            noStar.chop(1);
            star = true;
        }
        if (m_QtTypesToQmlTypes.contains(noStar)) {
            typeName = star ? m_QtTypesToQmlTypes.value(noStar) + '*' : m_QtTypesToQmlTypes.value(noStar);
            //### versions
        }
        propertyInfo.setType(typeName);
        propertyInfo.setValid(true);
        propertyInfo.setReadable(qProperty.isReadable());
        propertyInfo.setWritable(qProperty.isWritable());
        propertyInfo.setResettable(qProperty.isResettable());
        propertyInfo.setEnumType(qProperty.isEnumType());
        propertyInfo.setFlagType(qProperty.isFlagType());

        if (propertyInfo.isEnumType()) {
            EnumeratorMetaInfo enumerator;

            QMetaEnum qEnumerator = qProperty.enumerator();
            enumerator.setValid(qEnumerator.isValid());
            enumerator.setIsFlagType(qEnumerator.isFlag());
            enumerator.setScope(qEnumerator.scope());
            enumerator.setName(qEnumerator.name());
            for (int i = 0 ;i < qEnumerator.keyCount(); i++)
            {
                enumerator.addElement(qEnumerator.valueToKey(i), i);
            }

            propertyInfo.setEnumerator(enumerator);
        }

        nodeMetaInfo.addProperty(propertyInfo);
    }
}
QString objToString(const QObject* obj) {
    QStringList result;
    const QMetaObject* meta = obj->metaObject();
    result += QString("class %1 : public %2 {")
              .arg(meta->className()).arg(meta->superClass()->className());
    for (int i=0; i < meta->propertyCount(); ++i) {
        const QMetaProperty qmp = meta->property(i);
        QVariant value = obj->property(qmp.name());
        result += QString("  %1 %2 = %3;")
            .arg(qmp.typeName()).arg(qmp.name())
            .arg(value.toString()); }
    result += "};";
    return result.join("\n");
}
Beispiel #20
0
	QMap<QString,QPair<QString,QVariant> > Modifier::serializeProperties() {
		QMap<QString,QPair<QString,QVariant> > result;

		for (int i = 0; i < metaObject()->propertyCount(); ++i) {
			QMetaProperty metaproperty = metaObject()->property(i);
			const char *name = metaproperty.name();
			QVariant value = property(name);
			QString type(metaproperty.typeName());
			if (metaproperty.isEnumType())
				type = "int";
			result.insert(name, QPair<QString,QVariant>(type, value));
		}

		return result;
	}
Beispiel #21
0
void SaxsviewProperty::setValue(QObject *obj) {
  if (!mProperty) {
    //
    // Find the meta-property information; the passed object must
    // provide the Q_PROPERTY name passed to the constructor.
    //
    int indexOfProperty = obj->metaObject()->indexOfProperty(qPrintable(mPropertyName));
    QMetaProperty metaProperty = obj->metaObject()->property(indexOfProperty);

    if (metaProperty.isValid()) {
      //
      // Create an editor factory if and only if the property is writeable.
      //
      if (metaProperty.isWritable()) {
        mBrowser->setFactoryForManager(mManager, new QtVariantEditorFactory(this));
        connect(mManager, SIGNAL(valueChanged(QtProperty*, const QVariant&)),
                this, SLOT(valueChanged(QtProperty*, const QVariant&)));
      }

      if (!mManager->isPropertyTypeSupported(metaProperty.type()))
        qFatal("internal error: property '%s', property type not supported: '%s'",
               metaProperty.name(), metaProperty.typeName());

      //
      // Check if this is an enum and handle it specially if yes.
      //
      if (metaProperty.isEnumType()) {
        QStringList enumNames;
        QMetaEnum metaEnum = metaProperty.enumerator();

        //
        // WARNING: This only builds a  list of names in the order
        //          as defined. The combobox to display these names
        //          provides the selected index, not the actual enum
        //          value.
        //
        for (int i = 0; i < metaEnum.keyCount(); ++i)
          enumNames << metaEnum.key(i);

        setEnumNames(enumNames);
      }

      if (mAttributes.contains("enumNames"))
        mProperty = mManager->addProperty(mManager->enumTypeId(), mPropertyLabel);
      else
        mProperty = mManager->addProperty(metaProperty.type(), mPropertyLabel);

    } else if (obj->dynamicPropertyNames().contains(qPrintable(mPropertyName))) {
QVariant ObjectStaticPropertyModel::data(const QModelIndex &index, int role) const
{
  if (!index.isValid() || !m_obj || index.row() < 0 ||
      index.row() >= m_obj.data()->metaObject()->propertyCount()) {
    return QVariant();
  }

  const QMetaProperty prop = m_obj.data()->metaObject()->property(index.row());
  if (role == Qt::DisplayRole) {
    if (index.column() == 0) {
      return prop.name();
    } else if (index.column() == 1) {
      return Util::variantToString(prop.read(m_obj.data()));
    } else if (index.column() == 2) {
      return prop.typeName();
    } else if (index.column() == 3) {
      const QMetaObject *mo = m_obj.data()->metaObject();
      while (mo->propertyOffset() > index.row()) {
        mo = mo->superClass();
      }
      return mo->className();
    }
  } else if (role == Qt::EditRole) {
    if (index.column() == 1) {
      return prop.read(m_obj.data());
    }
  } else if (role == Qt::ToolTipRole) {
    const QString toolTip =
      tr("Constant: %1\nDesignable: %2\nFinal: %3\nResetable: %4\n"
         "Has notification: %5\nScriptable: %6\nStored: %7\nUser: %8\nWritable: %9").
      arg(translateBool(prop.isConstant())).
      arg(translateBool(prop.isDesignable(m_obj.data()))).
      arg(translateBool(prop.isFinal())).
      arg(translateBool(prop.isResettable())).
      arg(translateBool(prop.hasNotifySignal())).
      arg(translateBool(prop.isScriptable(m_obj.data()))).
      arg(translateBool(prop.isStored(m_obj.data()))).
      arg(translateBool(prop.isUser(m_obj.data()))).
      arg(translateBool(prop.isWritable()));
    return toolTip;
  }

  return QVariant();
}
Beispiel #23
0
QVariant Enums::data(const QModelIndex & index)
{
    const QMetaObject * metaObject = object()->metaObject();
    QMetaProperty metaProperty = metaObject->property(objectProperty());
    const char *typeName = metaProperty.typeName();
    int enumIdx = metaObject->indexOfEnumerator(typeName);

    if (!index.isValid() || !object() || -1 == objectProperty())
        return QVariant();

    switch (index.column())
    {
        case 0:
            return metaProperty.name();
        case 1: {
            return metaObject->enumerator(enumIdx).valueToKey(*reinterpret_cast<int*>(value().data()));
            }
    }
    return QVariant();
}
void QDeclarativePropertyCache::Data::lazyLoad(const QMetaProperty &p, QDeclarativeEngine *engine)
{
    Q_UNUSED(engine);

    coreIndex = p.propertyIndex();
    notifyIndex = p.notifySignalIndex();
    revision = p.revision();

    flags = fastFlagsForProperty(p);

    int type = p.type();
    if (type == QMetaType::QObjectStar || type == QMetaType::QWidgetStar) {
        propType = type;
        flags |= QDeclarativePropertyCache::Data::IsQObjectDerived;
    } else if (type == QVariant::UserType || type == -1) {
        propTypeName = p.typeName();
        flags |= QDeclarativePropertyCache::Data::NotFullyResolved;
    } else {
        propType = type;
    }
}
void GCF::Components::ScriptableObjectExplorer::on_itemDoubleClicked(QTreeWidgetItem* item)
{
    if(!item)
        return;

    int type = item->type();
    QTreeWidgetItem* objItem = item;
    QObject* object = 0;
    QString objectName;

    while(objItem && objItem->type() != OBJECT_ITEM)
        objItem = objItem->parent();

    if(!objItem)
        return;

    object = objItem->data(0, Qt::UserRole).value<QObject*>();
    objectName = objItem->text(1);

    switch(type)
    {
    case OBJECT_ITEM:
        emit objectDoubleClicked(object, objectName);
        break;
    case METHOD_ITEM: {
        QMetaMethod m = item->data(0, Qt::UserRole).value<QMetaMethod>();
        emit methodDoubleClicked(object, objectName, item->text(0), QString(m.signature()) );
        } break;
    case EVENT_ITEM:  {
        QMetaMethod m = item->data(0, Qt::UserRole).value<QMetaMethod>();
        emit signalDoubleClicked(object, objectName, item->text(0), QString(m.signature()) );
        } break;
    case PROPERTY_ITEM:{
        QMetaProperty prop = item->data(0, Qt::UserRole).value<QMetaProperty>();
        emit propertyDoubleClicked(object, objectName, item->text(0), QString(prop.typeName()));
        } break;
    }
}
Beispiel #26
0
void QObjectHelper::qvariant2qobject(const QVariantMap& variant, QObject* object)
{
  const QMetaObject *metaobject = object->metaObject();

  QVariantMap::const_iterator iter;
  for (iter = variant.constBegin(); iter != variant.constEnd(); ++iter) {
    int pIdx = metaobject->indexOfProperty( iter.key().toUtf8() );

    if ( pIdx < 0 ) {
      continue;
    }

    QMetaProperty metaproperty = metaobject->property( pIdx );
    QVariant::Type type = metaproperty.type();
    QVariant v( iter.value() );
    if ( v.canConvert( type ) ) {
      v.convert( type );
      metaproperty.write( object, v );
    } else if (QString(QLatin1String("QVariant")).compare(QLatin1String(metaproperty.typeName())) == 0) {
     metaproperty.write( object, v );
    }
  }
}
Beispiel #27
0
bool parseObject(const QVariant &source, QObject *target)
{
    if (!source.isValid() || !source.canConvert(QVariant::Map)) {
        qDebug() << "[ObjectParser] Error: Invalid object... " << source.toByteArray();
        return false;
    }
    const QVariantMap &map = source.toMap();
    const QMetaObject *metaobject = target->metaObject();

    QVariantMap::const_iterator it;
    QVariantMap::const_iterator end = map.constEnd();
    for (it = map.constBegin(); it != end; ++it) {
        const int index = metaobject->indexOfProperty(it.key().toLatin1());
        if (index < 0) {
            continue;
        }

        const QMetaProperty metaproperty = metaobject->property(index);
        const QVariant::Type type = metaproperty.type();
        QVariant v = it.value();

        if (v.canConvert(type)) {
            v.convert(type);
            metaproperty.write(target, v);
        } else if (QString(QLatin1String("QVariant"))
                       .compare(QLatin1String(metaproperty.typeName())) == 0) {
            metaproperty.write(target, v);
        } else {
            qDebug() << "[ObjectParser] Warning: unable to map variable" << it.key() << "of type"
                     << v.type() << "to type" << metaproperty.type() << "!";
            metaproperty.write(target, QVariant());
        }
    }

    return true;
}
void ControlInfo::setControl(QWidget *activex)
{
    listInfo->clear();

    const QMetaObject *mo = activex->metaObject();
    QTreeWidgetItem *group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Class Info"));
    group->setText(1, QString::number(mo->classInfoCount()));

    QTreeWidgetItem *item = 0;
    int i;
    int count;
    for (i = mo->classInfoOffset(); i < mo->classInfoCount(); ++i) {
	const QMetaClassInfo info = mo->classInfo(i);
	item = new QTreeWidgetItem(group);
        item->setText(0, QString::fromLatin1(info.name()));
        item->setText(1, QString::fromLatin1(info.value()));
    }
    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Signals"));

    count = 0;
    for (i = mo->methodOffset(); i < mo->methodCount(); ++i) {
	const QMetaMethod method = mo->method(i);
        if (method.methodType() == QMetaMethod::Signal) {
            ++count;
	    item = new QTreeWidgetItem(group);
            item->setText(0, QString::fromLatin1(method.signature()));
        }
    }
    group->setText(1, QString::number(count));

    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Slots"));

    count = 0;
    for (i = mo->methodOffset(); i < mo->methodCount(); ++i) {
	const QMetaMethod method = mo->method(i);
        if (method.methodType() == QMetaMethod::Slot) {
            ++count;
	    item = new QTreeWidgetItem(group);
            item->setText(0, QString::fromLatin1(method.signature()));
        }
    }
    group->setText(1, QString::number(count));

    group = new QTreeWidgetItem(listInfo);
    group->setText(0, tr("Properties"));

    count = 0;
    for (i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
        ++count;
	const QMetaProperty property = mo->property(i);
	item = new QTreeWidgetItem(group);
        item->setText(0, QString::fromLatin1(property.name()));
        item->setText(1, QString::fromLatin1(property.typeName()));
        if (!property.isDesignable()) {
            item->setTextColor(0, Qt::gray);
            item->setTextColor(1, Qt::gray);
        }
    }
    group->setText(1, QString::number(count));
}
int Dialog::showDialog(const QString& view, QObject* viewModel, int type)
{
    QDialog* dialog = NULL;
    QMainWindow* mainWindow = NULL;
    QWidget* windowWidget = NULL;
    QWidget* layoutWidget = NULL;

    switch (type)
    {
    case Dialog::MainWindow:
        mainWindow = new QMainWindow();
        windowWidget = mainWindow;
        layoutWidget = new QWidget(windowWidget);
        mainWindow->setCentralWidget(layoutWidget);
        break;

    case Dialog::ModalDialog:
        dialog = new QDialog(QApplication::activeWindow());
        windowWidget = dialog;
        layoutWidget = dialog;
        break;

    default:
        dialog = new QDialog();
        windowWidget = dialog;
        layoutWidget = dialog;
        break;
    }

    QGridLayout* layout = new QGridLayout(layoutWidget);

    // Create view

    QDeclarativeView* v = new QDeclarativeView(layoutWidget);

    if (viewModel)
    {
        int count = viewModel->metaObject()->propertyCount();
        for (int i = 0; i < count; ++i)
        {
            QMetaProperty p = viewModel->metaObject()->property(i);
            if (p.isReadable() && p.typeName() == QString("QDeclarativeImageProvider*"))
            {
                QString name = p.name();
                QDeclarativeImageProvider* value = p.read(viewModel).value<QDeclarativeImageProvider*>();

                v->engine()->addImageProvider(name.toLatin1(), new ProxyImageProvider(value));
            }
        }

        v->rootContext()->setContextProperty("dataContext", viewModel);
    }

    QString path;
    foreach (path, importPaths)
        v->engine()->addImportPath(path);
    foreach (path, pluginPaths)
        v->engine()->addPluginPath(path);

    v->setSource(QUrl(view));
    v->setResizeMode(QDeclarativeView::SizeRootObjectToView);

    // Initialize dialog

    QGraphicsObject* root = v->rootObject();

    QVariant property = root->property("dialogTitle");
    if (property.isValid())
        windowWidget->setWindowTitle(property.toString());

    property = root->property("dialogMinWidth");
    if (property.isValid())
        layoutWidget->setMinimumWidth(property.toInt());

    property = root->property("dialogMinHeight");
    if (property.isValid())
        layoutWidget->setMinimumHeight(property.toInt());

    property = root->property("dialogMaxWidth");
    if (property.isValid())
        layoutWidget->setMaximumWidth(property.toInt());

    property = root->property("dialogMaxHeight");
    if (property.isValid())
        layoutWidget->setMaximumHeight(property.toInt());

    property = root->property("dialogResizable");
    if (property.isValid() && !property.toBool())
        layout->setSizeConstraint(QLayout::SetFixedSize);

    Qt::WindowStates states = windowWidget->windowState();
    Qt::WindowFlags flags = windowWidget->windowFlags();

    property = root->property("dialogMinimizeButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowMinimizeButtonHint : flags & ~Qt::WindowMinimizeButtonHint;

    property = root->property("dialogMaximizeButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowMaximizeButtonHint : flags & ~Qt::WindowMaximizeButtonHint;

    property = root->property("dialogCloseButton");
    if (property.isValid())
        flags = property.toBool() ? flags | Qt::WindowCloseButtonHint : flags & ~Qt::WindowCloseButtonHint;

    property = root->property("dialogFullScreen");
    if (property.isValid())
        states = property.toBool() ? states | Qt::WindowFullScreen : states & ~Qt::WindowFullScreen;

    flags = flags & ~Qt::WindowContextHelpButtonHint;

    windowWidget->setWindowFlags(flags);
    windowWidget->setWindowState(states);

    property = root->property("dialogToolBar");
    if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>"))
    {
        QToolBar* toolbar = new QToolBar(mainWindow);
        toolbar->setMovable(false);
        toolbar->setFloatable(false);
        toolbar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
        toolbar->setAllowedAreas(Qt::TopToolBarArea);

        QDeclarativeListProperty<QDeclarativeItem> btnList = property.value< QDeclarativeListProperty<QDeclarativeItem> >();
        int btnCount = btnList.count(&btnList);

        for (int i = 0; i < btnCount; ++i)
        {
            QDeclarativeItem* item = btnList.at(&btnList, i);

            if (!item->property("text").isValid())
                continue;

            QString itemText = item->property("text").toString();
            QString itemTooltip = item->property("tooltip").isValid() ? item->property("tooltip").toString() : "";
            QString itemIconSource = item->property("iconSource").isValid() ? item->property("iconSource").toString() : "";
            int itemIconSize = item->property("iconSize").isValid() ? item->property("iconSize").toInt() : -1;

            if (itemText == "|")
            {
                toolbar->addSeparator();
            }
            else if (itemText == "-")
            {
                QWidget* spacer = new QWidget();
                spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
                toolbar->addWidget(spacer);
            }
            else
            {
                QAction* action = new QAction(mainWindow);
                action->setText(itemText);
                action->setToolTip(itemTooltip);
                action->setIcon(QIcon(itemIconSource));
                QObject::connect(action, SIGNAL(triggered()), item, SLOT(trigger()));

                if (item->property("enabled").isValid())
                    new PropertyBinding(action, "enabled", item, "enabled", PropertyBinding::OneWay, NULL, this);

                if (item->property("visible").isValid())
                    new PropertyBinding(action, "visible", item, "visible", PropertyBinding::OneWay, NULL, this);

                toolbar->addAction(action);
            }

            if (itemIconSize != -1)
                toolbar->setIconSize(QSize(itemIconSize, itemIconSize));
        }

        mainWindow->setUnifiedTitleAndToolBarOnMac(true);
        mainWindow->addToolBar(toolbar);
    }

    property = root->property("dialogMenu");
    if (type == Dialog::MainWindow && property.isValid() && property.typeName() == QString("QDeclarativeListProperty<QDeclarativeItem>"))
    {
        QDeclarativeListProperty<QDeclarativeItem> list = property.value< QDeclarativeListProperty<QDeclarativeItem> >();
        int count = list.count(&list);

        for (int i = 0; i < count; ++i)
        {
            QDeclarativeItem* item = list.at(&list, i);

            if (!item->property("text").isValid())
                continue;

            QString itemText = item->property("text").toString();
            QMenu * menuItem = mainWindow->menuBar()->addMenu(itemText);

            if (!item->property("submenu").isValid() || item->property("submenu").typeName() != QString("QDeclarativeListProperty<QDeclarativeItem>"))
                continue;

            QDeclarativeListProperty<QDeclarativeItem> innerList = item->property("submenu").value< QDeclarativeListProperty<QDeclarativeItem> >();
            int innerCount = innerList.count(&innerList);

            for (int j = 0; j < innerCount; ++j)
            {
                QDeclarativeItem* innerItem = innerList.at(&innerList, j);

                if (!innerItem->property("text").isValid())
                    continue;

                QString innerItemText = innerItem->property("text").toString();
                QString innerItemShortcut = innerItem->property("shortcut").isValid() ? innerItem->property("shortcut").toString() : "";
                QString innerItemIconSource = innerItem->property("iconSource").isValid() ? innerItem->property("iconSource").toString() : "";

                if (innerItemText == "-")
                {
                    menuItem->addSeparator();
                }
                else
                {
                    QAction * action = menuItem->addAction(QIcon(innerItemIconSource), innerItemText);
                    action->setShortcut(QKeySequence(innerItemShortcut));

                    QObject::connect(action, SIGNAL(triggered()), innerItem, SLOT(trigger()));

                    if (innerItem->property("enabled").isValid())
                        new PropertyBinding(action, "enabled", innerItem, "enabled", PropertyBinding::OneWay, NULL, this);

                    if (innerItem->property("visible").isValid())
                        new PropertyBinding(action, "visible", innerItem, "visible", PropertyBinding::OneWay, NULL, this);
                }
            }
        }
    }

    new DialogCallbacks(windowWidget, v, root);

    // Initialize layout

    layout->setMargin(0);
    layout->addWidget(v, 0, 0);

    // Execute

    switch (type)
    {
    case Dialog::ModalDialog:
        dialog->exec();
        break;

    case Dialog::MainWindow:
    {
        if (mainWindowGeometry.isEmpty())
        {
            mainWindow->adjustSize();
            mainWindow->move(QApplication::desktop()->screen()->rect().center() - mainWindow->rect().center());
        }
        else
            mainWindow->restoreGeometry(mainWindowGeometry);
    }

    default:
        windowWidget->setAttribute(Qt::WA_DeleteOnClose);
        windowWidget->show();
        break;
    }

    int result = 0;

    property = root->property("dialogResult");
    if (property.isValid())
        result = property.toInt();

    if (type == Dialog::ModalDialog)
        delete dialog;

    return result;
}
Beispiel #30
0
void QDBusAbstractInterfacePrivate::property(const QMetaProperty &mp, QVariant &where) const
{
    if (!isValid || !canMakeCalls()) {   // can't make calls
        where.clear();
        return;
    }

    // is this metatype registered?
    const char *expectedSignature = "";
    if (mp.type() != 0xff) {
        expectedSignature = QDBusMetaType::typeToSignature(where.userType());
        if (expectedSignature == 0) {
            qWarning("QDBusAbstractInterface: type %s must be registered with QtDBus before it can be "
                     "used to read property %s.%s",
                     mp.typeName(), qPrintable(interface), mp.name());
            lastError = QDBusError(QDBusError::Failed,
                                   QString::fromLatin1("Unregistered type %1 cannot be handled")
                                   .arg(QLatin1String(mp.typeName())));
            where.clear();
            return;
        }
    }

    // try to read this property
    QDBusMessage msg = QDBusMessage::createMethodCall(service, path,
                                                      QLatin1String(DBUS_INTERFACE_PROPERTIES),
                                                      QLatin1String("Get"));
    QDBusMessagePrivate::setParametersValidated(msg, true);
    msg << interface << QString::fromUtf8(mp.name());
    QDBusMessage reply = connection.call(msg, QDBus::Block);

    if (reply.type() != QDBusMessage::ReplyMessage) {
        lastError = reply;
        where.clear();
        return;
    }
    if (reply.signature() != QLatin1String("v")) {
        QString errmsg = QLatin1String("Invalid signature `%1' in return from call to "
                                       DBUS_INTERFACE_PROPERTIES);
        lastError = QDBusError(QDBusError::InvalidSignature, errmsg.arg(reply.signature()));
        where.clear();
        return;
    }

    QByteArray foundSignature;
    const char *foundType = 0;
    QVariant value = qvariant_cast<QDBusVariant>(reply.arguments().at(0)).variant();

    if (value.userType() == where.userType() || mp.type() == 0xff
        || (expectedSignature[0] == 'v' && expectedSignature[1] == '\0')) {
        // simple match
        where = value;
        return;
    }

    if (value.userType() == qMetaTypeId<QDBusArgument>()) {
        QDBusArgument arg = qvariant_cast<QDBusArgument>(value);

        foundType = "user type";
        foundSignature = arg.currentSignature().toLatin1();
        if (foundSignature == expectedSignature) {
            // signatures match, we can demarshall
            QDBusMetaType::demarshall(arg, where.userType(), where.data());
            return;
        }
    } else {
        foundType = value.typeName();
        foundSignature = QDBusMetaType::typeToSignature(value.userType());
    }

    // there was an error...
    QString errmsg = QLatin1String("Unexpected `%1' (%2) when retrieving property `%3.%4' "
                                   "(expected type `%5' (%6))");
    lastError = QDBusError(QDBusError::InvalidSignature,
                           errmsg.arg(QString::fromLatin1(foundType),
                                      QString::fromLatin1(foundSignature),
                                      interface,
                                      QString::fromUtf8(mp.name()),
                                      QString::fromLatin1(mp.typeName()),
                                      QString::fromLatin1(expectedSignature)));
    where.clear();
    return;
}