示例#1
0
void VectorPropertyWidgetItem::setEditValue( const QVariant& value )
{
    int userType = value.userType();
    if( userType == d->vector2d )
    {
        const Vector2f* vector = static_cast<const Vector2f*>( value.data() );
        d->x->setValue( vector->x() );
        d->y->setValue( vector->y() );
        d->z->setVisible( false );
        d->w->setVisible( false );
        d->vectorDim = 2;
    }
    else if( userType == d->vector3d )
    {
        const Vector3f* vector = static_cast<const Vector3f*>( value.data() );
        d->x->setValue( vector->x() );
        d->y->setValue( vector->y() );
        d->z->setValue( vector->z() );
        d->w->setVisible( false );
        d->vectorDim = 3;
    }
    else if( userType == d->vector4d )
    {
        const Vector4f* vector = static_cast<const Vector4f*>( value.data() );
        d->x->setValue( vector->x() );
        d->y->setValue( vector->y() );
        d->z->setValue( vector->z() );
        d->w->setValue( vector->w() );
        d->vectorDim = 4;
    }
}
示例#2
0
文件: config.cpp 项目: dganic/qutim
ConfigAtom::ConfigAtom(QVariant &var, bool isMap) : deleteOnDestroy(false), typeMap(isMap), readOnly(false)
{
	if (isMap && var.type() != QVariant::Map)
		var = QVariantMap();
	else if (!isMap && var.type() != QVariant::List)
		var = QVariantList();

	if (isMap)
		map = reinterpret_cast<QVariantMap*>(var.data());
	else
		list = reinterpret_cast<QVariantList*>(var.data());
}
示例#3
0
bool Nuria::Serializer::fieldToVariant (QVariant &value, bool &ignore) {
	QByteArray typeName = QByteArray (value.typeName (), -1);
	MetaObject *meta = this->d->finder (typeName);
	
	if (meta) {
		void *dataPtr = value.data ();
		
		if (typeName.endsWith ('*')) {
			dataPtr = *reinterpret_cast< void ** > (dataPtr);
		}
		
		if (this->d->curDepth == 1) {
			ignore = true;
		} else {
			value = serializeImpl (dataPtr, meta);
		}
		
		return true;
	}
	
	// Variant::convert() triggers QVariant conversion internally
	QVariant conv = Nuria::Variant::convert (value, QMetaType::QString);
	if (conv.isValid ()) {
		value = conv;
		return true;
	}
	
	return false;
}
void TabbedMainWindow::addUsersToCluster(QString hostname, QString usernamepassword, QListWidget *list1, QListWidget *list2) {
    ProgressDialog progbar("CMClusters - Connecting...", "Please wait while a connection to the selected clusters are established!");
    progbar.show();

    for (int i = list1->count(); i --> 0;) {
        if (list1->item(i)->isSelected()) {
        QString userid = getSubstringBetween(list1->item(i)->text(), QString("("), QString(")"));
        qDebug() << userid;
        QListWidgetItem* userToRemove = list1->item(i);
        QListWidgetItem* userToAdd = new QListWidgetItem(list1->item(i)->text());
        QByteArray jsonString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://www.cisco.com/AXL/API/8.5\">";
        jsonString += "<soapenv:Body><ns:executeSQLUpdate><sql>UPDATE enduser SET enduser.islocaluser = '******' WHERE enduser.userid = '" + userid.toLocal8Bit() + "'</sql></ns:executeSQLUpdate></SOAP-ENV:Envelope>";
        QByteArray postDataSize = QByteArray::number(jsonString.size());
        QUrl req("https://" + hostname.toLocal8Bit() + ":8443/axl/");
        QNetworkRequest request(req);

        request.setRawHeader("SOAPAction", "\"CUCM:DB ver=8.5 executeSQLUpdate\"");
        request.setRawHeader("Authorization", "Basic " + usernamepassword.toLocal8Bit());
        request.setRawHeader("Content-Type", "text/xml");
        request.setRawHeader("Content-Length", postDataSize);

        QNetworkAccessManager test;
        QEventLoop loop;
        connect(&test, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
        QNetworkReply * reply = test.post(request, jsonString);
        reply->ignoreSslErrors(); // Ignore only unsigned later on
        connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
        loop.exec();

        QByteArray response = reply->readAll();
        QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );

        if ( !statusCode.isValid() ) {
            qDebug() << "Failed...";
            qDebug() << statusCode.data();
        }

        int status = statusCode.toInt();

        if ( status != 200 ) {
            QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
            qDebug() << reason;
        } else {
            qDebug() << "Good reply";
            qDebug() << response;
            if (response.contains("<rowsUpdated>1</rowsUpdated>")) {
                qDebug() << "Something went correct!";
                delete userToRemove;
                list2->addItem(userToAdd);
                userToAdd->setBackground(QColor(0, 170, 255));//Correct the color scheme
            } else {
                qDebug() << "We f****d up!";
            }
        }
        }
    }
ReturnedValue QQmlValueTypeWrapper::get(const Managed *m, String *name, bool *hasProperty)
{
    Q_ASSERT(m->as<QQmlValueTypeWrapper>());
    const QQmlValueTypeWrapper *r = static_cast<const QQmlValueTypeWrapper *>(m);
    QV4::ExecutionEngine *v4 = r->engine();

    // Note: readReferenceValue() can change the reference->type.
    if (const QQmlValueTypeReference *reference = r->as<QQmlValueTypeReference>()) {
        if (!reference->readReferenceValue())
            return Primitive::undefinedValue().asReturnedValue();
    }

    QQmlPropertyData *result = r->d()->propertyCache->property(name, 0, 0);
    if (!result)
        return Object::get(m, name, hasProperty);

    if (hasProperty)
        *hasProperty = true;

    if (result->isFunction())
        // calling a Q_INVOKABLE function of a value type
        return QV4::QObjectMethod::create(v4->rootContext(), r, result->coreIndex);

#define VALUE_TYPE_LOAD(metatype, cpptype, constructor) \
    if (result->propType == metatype) { \
        cpptype v; \
        void *args[] = { &v, 0 }; \
        metaObject->d.static_metacall(reinterpret_cast<QObject*>(gadget), QMetaObject::ReadProperty, index, args); \
        return QV4::Encode(constructor(v)); \
    }

    const QMetaObject *metaObject = r->d()->propertyCache->metaObject();

    int index = result->coreIndex;
    QQmlMetaObject::resolveGadgetMethodOrPropertyIndex(QMetaObject::ReadProperty, &metaObject, &index);

    void *gadget = r->d()->gadgetPtr;

    // These four types are the most common used by the value type wrappers
    VALUE_TYPE_LOAD(QMetaType::QReal, qreal, qreal);
    VALUE_TYPE_LOAD(QMetaType::Int, int, int);
    VALUE_TYPE_LOAD(QMetaType::QString, QString, v4->newString);
    VALUE_TYPE_LOAD(QMetaType::Bool, bool, bool);

    QVariant v;
    void *args[] = { Q_NULLPTR, Q_NULLPTR };
    if (result->propType == QMetaType::QVariant) {
        args[0] = &v;
    } else {
        v = QVariant(result->propType, static_cast<void *>(Q_NULLPTR));
        args[0] = v.data();
    }
    metaObject->d.static_metacall(reinterpret_cast<QObject*>(gadget), QMetaObject::ReadProperty, index, args);
    return v4->fromVariant(v);
#undef VALUE_TYPE_ACCESSOR
}
QJsonValue QMetaObjectPublisher::invokeMethod(QObject *const object, const int methodIndex,
                                              const QJsonArray &args)
{
    const QMetaMethod &method = object->metaObject()->method(methodIndex);

    if (method.name() == QByteArrayLiteral("deleteLater")) {
        // invoke `deleteLater` on wrapped QObject indirectly
        deleteWrappedObject(object);
        return QJsonValue();
    } else if (!method.isValid()) {
        qWarning() << "Cannot invoke unknown method of index" << methodIndex << "on object" << object << '.';
        return QJsonValue();
    } else if (method.access() != QMetaMethod::Public) {
        qWarning() << "Cannot invoke non-public method" << method.name() << "on object" << object << '.';
        return QJsonValue();
    } else if (method.methodType() != QMetaMethod::Method && method.methodType() != QMetaMethod::Slot) {
        qWarning() << "Cannot invoke non-public method" << method.name() << "on object" << object << '.';
        return QJsonValue();
    } else if (args.size() > 10) {
        qWarning() << "Cannot invoke method" << method.name() << "on object" << object << "with more than 10 arguments, as that is not supported by QMetaMethod::invoke.";
        return QJsonValue();
    } else if (args.size() > method.parameterCount()) {
        qWarning() << "Ignoring additional arguments while invoking method" << method.name() << "on object" << object << ':'
                   << args.size() << "arguments given, but method only takes" << method.parameterCount() << '.';
    }

    // construct converter objects of QVariant to QGenericArgument
    VariantArgument arguments[10];
    for (int i = 0; i < qMin(args.size(), method.parameterCount()); ++i) {
        QVariant arg = args.at(i).toVariant();
        if (method.parameterType(i) != QMetaType::QVariant && !arg.convert(method.parameterType(i))) {
            qWarning() << "Could not convert argument" << args.at(i) << "to target type" << method.parameterTypes().at(i) << '.';
        }
        arguments[i].value = arg;
    }

    // construct QGenericReturnArgument
    QVariant returnValue;
    if (method.returnType() != qMetaTypeId<QVariant>() && method.returnType() != qMetaTypeId<void>()) {
        // Only init variant with return type if its not a variant itself, which would
        // lead to nested variants which is not what we want.
        // Also, skip void-return types for obvious reasons (and to prevent a runtime warning inside Qt).
        returnValue = QVariant(method.returnType(), 0);
    }
    QGenericReturnArgument returnArgument(method.typeName(), returnValue.data());

    // now we can call the method
    method.invoke(object, returnArgument,
                  arguments[0], arguments[1], arguments[2], arguments[3], arguments[4],
                  arguments[5], arguments[6], arguments[7], arguments[8], arguments[9]);

    return wrapResult(returnValue);
}
示例#7
0
int toQPSqlConnectionSub::nativeSessionId()
{
    QVariant v = Connection.driver()->handle();
    if (v.isValid() && v.typeName() == QString("PGconn*"))
    {
#ifdef HAVE_POSTGRESQL_LIBPQ_FE_H
        PGconn *handle = *static_cast<PGconn **>(v.data());
        if (handle)
            return PQbackendPID(handle);
#endif
    }
    return 0;
}
/*	taken from http://delta.affinix.com/2006/08/14/invokemethodwithvariants/
	thanks to Justin Karneges once again :) */
bool MaiaXmlRpcServerConnection::invokeMethodWithVariants(QObject *obj,
			const QByteArray &method, const QVariantList &args,
			QVariant *ret, Qt::ConnectionType type) {

	// QMetaObject::invokeMethod() has a 10 argument maximum
	if(args.count() > 10)
		return false;

	QList<QByteArray> argTypes;
	for(int n = 0; n < args.count(); ++n)
		argTypes += args[n].typeName();

	// get return type
	int metatype = 0;
	QByteArray retTypeName = getReturnType(obj->metaObject(), method, argTypes);
	if(!retTypeName.isEmpty()  && retTypeName != "QVariant") {
		metatype = QMetaType::type(retTypeName.data());
		if(metatype == 0) // lookup failed
			return false;
	}

	QGenericArgument arg[10];
	for(int n = 0; n < args.count(); ++n)
		arg[n] = QGenericArgument(args[n].typeName(), args[n].constData());

	QGenericReturnArgument retarg;
	QVariant retval;
	if(metatype != 0) {
		retval = QVariant(metatype, (const void *)0);
		retarg = QGenericReturnArgument(retval.typeName(), retval.data());
	} else { /* QVariant */
		retarg = QGenericReturnArgument("QVariant", &retval);
	}

	if(retTypeName.isEmpty()) { /* void */
		if(!QMetaObject::invokeMethod(obj, method.data(), type,
						arg[0], arg[1], arg[2], arg[3], arg[4],
						arg[5], arg[6], arg[7], arg[8], arg[9]))
			return false;
	} else {
		if(!QMetaObject::invokeMethod(obj, method.data(), type, retarg,
						arg[0], arg[1], arg[2], arg[3], arg[4],
						arg[5], arg[6], arg[7], arg[8], arg[9]))
			return false;
	}

	if(retval.isValid() && ret)
		*ret = retval;
	return true;
}
示例#9
0
/*!
    Invokes the slot represented by this object with the argument
    list \a args.  The slot's return value is returned from
    this method.  If the slot's return type is "void", then a
    QVariant instance of type QVariant::Invalid will be returned.

    If it is possible that the slot may throw an exception,
    it is the responsibility of the caller to catch and
    handle the exception.
    \since 1.1
*/
QVariant QSlotInvoker::invoke( const QList<QVariant>& args )
{
    int arg;
    QVariant returnValue;

    // Create a default instance of the return type for the result buffer.
    if ( d->returnType != (int)QVariant::Invalid ) {
        returnValue = QVariant( d->returnType, (const void *)0 );
    }

    // Bail out if the receiver object has already disappeared.
    if ( d->destroyed )
        return returnValue;

    // Check that the number of arguments is compatible with the slot.
    int numArgs = args.size();
    if ( numArgs < d->numArgs ) {
        qWarning( "QSlotInvoker::invoke: insufficient arguments for slot" );
        return returnValue;
    } else if ( numArgs > d->numArgs ) {
        // Drop extraneous arguments.
        numArgs = d->numArgs;
    }

    // Construct the raw argument list.
    QVarLengthArray<void *, 32> a( numArgs + 1 );
    if ( d->returnType == (int)QVariant::Invalid )
        a[0] = 0;
    else
        a[0] = returnValue.data();
    for ( arg = 0; arg < numArgs; ++arg ) {
        if ( d->types[arg] == QSignalIntercepter::QVariantId ) {
            a[arg + 1] = (void *)&( args[arg] );
        } else if ( args[arg].userType() != d->types[arg] ) {
            qWarning( "QSlotInvoker::invoke: argument %d has incorrect type",
                      arg );
            return QVariant();
        } else {
            a[arg + 1] = (void *)( args[arg].data() );
        }
    }

    // Invoke the specified slot.
    d->receiver->qt_metacall( QMetaObject::InvokeMetaMethod,
                                     d->memberIndex, a.data() );
    return returnValue;
}
void QQmlVMEMetaObject::writeProperty(int id, const QVariant &value)
{
    if (id >= firstVarPropertyIndex) {
        if (!ensureVarPropertiesAllocated())
            return;

        QV4::Scope scope(varProperties.engine());

        // Importantly, if the current value is a scarce resource, we need to ensure that it
        // gets automatically released by the engine if no other references to it exist.
        QV4::ScopedObject vp(scope, varProperties.value());
        QV4::Scoped<QV4::VariantObject> oldv(scope, vp->getIndexed(id - firstVarPropertyIndex));
        if (!!oldv)
            oldv->removeVmePropertyReference();

        // And, if the new value is a scarce resource, we need to ensure that it does not get
        // automatically released by the engine until no other references to it exist.
        QV4::ScopedValue newv(scope, QQmlEnginePrivate::get(ctxt->engine)->v8engine()->fromVariant(value));
        QV4::Scoped<QV4::VariantObject> v(scope, newv);
        if (!!v)
            v->addVmePropertyReference();

        // Write the value and emit change signal as appropriate.
        QVariant currentValue = readPropertyAsVariant(id);
        vp->putIndexed(id - firstVarPropertyIndex, newv);
        if ((currentValue.userType() != value.userType() || currentValue != value))
            activate(object, methodOffset() + id, 0);
    } else {
        bool needActivate = false;
        if (value.userType() == QMetaType::QObjectStar) {
            QObject *o = *(QObject **)value.data();
            needActivate = (data[id].dataType() != QMetaType::QObjectStar || data[id].asQObject() != o);
            data[id].setValue(o, this, id);
        } else {
            needActivate = (data[id].dataType() != qMetaTypeId<QVariant>() ||
                            data[id].asQVariant().userType() != value.userType() ||
                            data[id].asQVariant() != value);
            data[id].setValue(value);
        }

        if (needActivate)
            activate(object, methodOffset() + id, 0);
    }
}
示例#11
0
void testQVariant2()
{
    QVariant value;
    QVariant::Type t = QVariant::String;
    value = QVariant(t, (void*)0);
    *(QString*)value.data() = QString("XXX");

    int i = 1;
    Q_UNUSED(i);
#if 1
    QVariant var;
    var.setValue(1);
    var.setValue(2);
    var.setValue(3);
    var.setValue(QString("Hello"));
    var.setValue(QString("World"));
    var.setValue(QString("Hello"));
    var.setValue(QStringList() << "World");
    var.setValue(QStringList() << "World" << "Hello");
    var.setValue(QStringList() << "Hello" << "Hello");
    var.setValue(QStringList() << "World" << "Hello" << "Hello");
#endif
#if 1
    QVariant var3;
    QHostAddress ha("127.0.0.1");
    var.setValue(ha);
    var3 = var;
    var3 = var;
    var3 = var;
    var3 = var;
    QHostAddress ha1 = var.value<QHostAddress>();
    typedef QMap<uint, QStringList> MyType;
    MyType my;
    my[1] = (QStringList() << "Hello");
    my[3] = (QStringList() << "World");
    var.setValue(my);
    // FIXME: Known to break
    QString type = var.typeName();
    var.setValue(my);
    var.setValue(my);
    var.setValue(my);
    var.setValue(my);
#endif
}
示例#12
0
SqliteTrainerModel::SqliteTrainerModel(QObject *parent, QString fileName) :
    TrainerModel(parent)
{

    m_cardItemModel = new CardItemModel(this);
    m_cardItemModel->setObjectName("card_items");

    QSqlError err;
    QSqlDatabase db = QSqlDatabase::database(fileName);
    if(!db.isValid()) {
        db = QSqlDatabase::addDatabase("QSQLITE", fileName);
        db.setDatabaseName(fileName);
    }
    if (!db.open()) {
        err = db.lastError();
        db = QSqlDatabase();
        QSqlDatabase::removeDatabase(fileName);
    }
    if(err.isValid()) {
        qWarning() << err.text();
    } else {
        qDebug() << fileName << "opened";

        m_db = db;

        QVariant v = db.driver()->handle();
        if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0) {
            // v.data() returns a pointer to the handle
            sqlite3 *handle = *static_cast<sqlite3 **>(v.data());
            if (handle != 0) { // check that it is not NULL
                sqlite3_trace(handle,trace,NULL);
            }
        }

        initCardItemModel();

        initModels();

    }

}
示例#13
0
/*!
    \internal
    Fills in the QDBusReply data \a error and \a data from the reply message \a reply.
*/
void qDBusReplyFill(const QDBusMessage &reply, QDBusError &error, QVariant &data)
{
    error = reply;

    if (error.isValid()) {
        data = QVariant();      // clear it
        return;
    }

    if (reply.arguments().count() >= 1 && reply.arguments().at(0).userType() == data.userType()) {
        data = reply.arguments().at(0);
        return;
    }

    const char *expectedSignature = 0;
    QByteArray receivedSignature;

    if (reply.arguments().count() >= 1 &&
        reply.arguments().at(0).userType() == QDBusMetaTypeId::argument) {
        // compare signatures instead
        QDBusArgument arg = qvariant_cast<QDBusArgument>(reply.arguments().at(0));
        expectedSignature = QDBusMetaType::typeToSignature(data.userType());
        receivedSignature = arg.currentSignature().toLatin1();
        if (receivedSignature == expectedSignature) {
            // matched. Demarshall it
            QDBusMetaType::demarshall(arg, data.userType(), data.data());
            return;
        }
    }

    // error
    QString errorMsg = QLatin1String("Unexpected reply signature: got \"%1\", "
                                     "expected \"%2\" (%3)");
    if (receivedSignature.isEmpty())
        receivedSignature = "no signature";
    error = QDBusError(QDBusError::InvalidSignature,
                      errorMsg.arg(QLatin1String(receivedSignature),
                                   QLatin1String(expectedSignature),
                                   QLatin1String(data.typeName())));
    data = QVariant();      // clear it
}
示例#14
0
void toQPSqlConnectionSub::nativeCancel()
{
    QVariant v = Connection.driver()->handle();
    if (v.isValid() && v.typeName() == QString("PGconn*"))
    {
#ifdef LIBPQ_DECL_CANCEL
        PGconn *handle = *static_cast<PGconn **>(v.data());
        if (!handle)
            return;

        PGcancel *cancel = PQgetCancel(handle);
        if (!cancel)
            return;

        char *errbuf = new char[1024];
        PQcancel(cancel, errbuf, 1024);
        PQfreeCancel(cancel);
        delete[] errbuf;
#endif
    }
}
示例#15
0
// Author & Date: Ehsan Azar       19 April 2012
// Purpose: Add list iteratively
// Inputs:
//   list     - list to add to current node
//   nodeName - last node name
// Outputs:
//   Returns true if this is an array added
bool XmlFile::AddList(QVariantList & list, QString nodeName)
{
    if (list.isEmpty())
        return false;
    QMap<QString, int> mapItemCount;
    int count = 0, subcount = 1;
    // itemize the list
    for (int j = 0; j < list.size(); ++j)
    {
        QVariant subval = list[j];
        if (!subval.isValid())
            continue;
        count++; // count all valid items
        QString strSubKey;
        QMap<QString, QVariant> attribs;
        if (subval.type() == QVariant::UserType)
        {
            const XmlItem * item = static_cast<const XmlItem *>(subval.data());
            strSubKey = item->XmlName();
            attribs = item->XmlAttribs();
        }
        if (strSubKey.isEmpty())
            strSubKey = nodeName + "_item";
        subcount = mapItemCount[strSubKey];
        mapItemCount[strSubKey] = subcount + 1;
        if (subcount)
            strSubKey = strSubKey + QString("<%1>").arg(subcount);
        // Recursively add this item
        beginGroup(strSubKey, attribs, subval);
        endGroup();
    } // end for (int j
    // If all items had same tag name, it is an array
    if (count > 1 && count == subcount + 1)
        return true;
    return false;
}
示例#16
0
//writeEnumProperty MIRRORS the relelvant bit of QMetaProperty::write AND MUST BE KEPT IN SYNC!
bool QDeclarativePropertyPrivate::writeEnumProperty(const QMetaProperty &prop, int idx, QObject *object, const QVariant &value, int flags)
{
    if (!object || !prop.isWritable())
        return false;

    QVariant v = value;
    if (prop.isEnumType()) {
        QMetaEnum menum = prop.enumerator();
        if (v.userType() == QVariant::String
#ifdef QT3_SUPPORT
            || v.userType() == QVariant::CString
#endif
            ) {
            if (prop.isFlagType())
                v = QVariant(menum.keysToValue(value.toByteArray()));
            else
                v = QVariant(menum.keyToValue(value.toByteArray()));
        } else if (v.userType() != QVariant::Int && v.userType() != QVariant::UInt) {
            int enumMetaTypeId = QMetaType::type(QByteArray(menum.scope()) + "::" + menum.name());
            if ((enumMetaTypeId == 0) || (v.userType() != enumMetaTypeId) || !v.constData())
                return false;
            v = QVariant(*reinterpret_cast<const int *>(v.constData()));
        }
        v.convert(QVariant::Int);
    }

    // the status variable is changed by qt_metacall to indicate what it did
    // this feature is currently only used by QtDBus and should not be depended
    // upon. Don't change it without looking into QDBusAbstractInterface first
    // -1 (unchanged): normal qt_metacall, result stored in argv[0]
    // changed: result stored directly in value, return the value of status
    int status = -1;
    void *argv[] = { v.data(), &v, &status, &flags };
    QMetaObject::metacall(object, QMetaObject::WriteProperty, idx, argv);
    return status;
}
示例#17
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;
}
示例#18
0
QObject *QDeclarativeVME::run(QDeclarativeVMEObjectStack &stack, 
                              QDeclarativeContextData *ctxt, 
                              QDeclarativeCompiledData *comp, 
                              int start, int count, 
                              const QBitField &bindingSkipList)
{
    Q_ASSERT(comp);
    Q_ASSERT(ctxt);
    const QList<QDeclarativeCompiledData::TypeReference> &types = comp->types;
    const QList<QString> &primitives = comp->primitives;
    const QList<QByteArray> &datas = comp->datas;
    const QList<QDeclarativeCompiledData::CustomTypeData> &customTypeData = comp->customTypeData;
    const QList<int> &intData = comp->intData;
    const QList<float> &floatData = comp->floatData;
    const QList<QDeclarativePropertyCache *> &propertyCaches = comp->propertyCaches;
    const QList<QDeclarativeParser::Object::ScriptBlock> &scripts = comp->scripts;
    const QList<QUrl> &urls = comp->urls;

    QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding> bindValues;
    QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus> parserStatus;

    QDeclarativeVMEStack<ListInstance> qliststack;

    vmeErrors.clear();
    QDeclarativeEnginePrivate *ep = QDeclarativeEnginePrivate::get(ctxt->engine);

    int status = -1;    //for dbus
    QDeclarativePropertyPrivate::WriteFlags flags = QDeclarativePropertyPrivate::BypassInterceptor |
                                                    QDeclarativePropertyPrivate::RemoveBindingOnAliasWrite;

    for (int ii = start; !isError() && ii < (start + count); ++ii) {
        const QDeclarativeInstruction &instr = comp->bytecode.at(ii);

        switch(instr.type) {
        case QDeclarativeInstruction::Init:
            {
                if (instr.init.bindingsSize) 
                    bindValues = QDeclarativeEnginePrivate::SimpleList<QDeclarativeAbstractBinding>(instr.init.bindingsSize);
                if (instr.init.parserStatusSize)
                    parserStatus = QDeclarativeEnginePrivate::SimpleList<QDeclarativeParserStatus>(instr.init.parserStatusSize);
                if (instr.init.contextCache != -1) 
                    ctxt->setIdPropertyData(comp->contextCaches.at(instr.init.contextCache));
                if (instr.init.compiledBinding != -1) 
                    ctxt->optimizedBindings = new QDeclarativeCompiledBindings(datas.at(instr.init.compiledBinding).constData(), ctxt, comp);
            }
            break;

        case QDeclarativeInstruction::CreateObject:
            {
                QBitField bindings;
                if (instr.create.bindingBits != -1) {
                    const QByteArray &bits = datas.at(instr.create.bindingBits);
                    bindings = QBitField((const quint32*)bits.constData(),
                                         bits.size() * 8);
                }
                if (stack.isEmpty())
                    bindings = bindings.united(bindingSkipList);

                QObject *o = 
                    types.at(instr.create.type).createInstance(ctxt, bindings, &vmeErrors);

                if (!o) {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create object of type %1").arg(QString::fromLatin1(types.at(instr.create.type).className)));
                }

                QDeclarativeData *ddata = QDeclarativeData::get(o);
                Q_ASSERT(ddata);

                if (stack.isEmpty()) {
                    if (ddata->context) {
                        Q_ASSERT(ddata->context != ctxt);
                        Q_ASSERT(ddata->outerContext);
                        Q_ASSERT(ddata->outerContext != ctxt);
                        QDeclarativeContextData *c = ddata->context;
                        while (c->linkedContext) c = c->linkedContext;
                        c->linkedContext = ctxt;
                    } else {
                        ctxt->addObject(o);
                    }

                    ddata->ownContext = true;
                } else if (!ddata->context) {
                    ctxt->addObject(o);
                }

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                if (instr.create.data != -1) {
                    QDeclarativeCustomParser *customParser =
                        types.at(instr.create.type).type->customParser();
                    customParser->setCustomData(o, datas.at(instr.create.data));
                }
                if (!stack.isEmpty()) {
                    QObject *parent = stack.top();
                    if (o->isWidgetType()) { 
                        QWidget *widget = static_cast<QWidget*>(o); 
                        if (parent->isWidgetType()) { 
                            QWidget *parentWidget = static_cast<QWidget*>(parent); 
                            widget->setParent(parentWidget); 
                        } else { 
                            // TODO: parent might be a layout 
                        } 
                    } else { 
			    QDeclarative_setParent_noEvent(o, parent);
                    } 
                }
                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::CreateSimpleObject:
            {
                QObject *o = (QObject *)operator new(instr.createSimple.typeSize + 
                                                     sizeof(QDeclarativeData));   
                ::memset(static_cast<void *>(o), 0, instr.createSimple.typeSize + sizeof(QDeclarativeData));
                instr.createSimple.create(o);

                QDeclarativeData *ddata = (QDeclarativeData *)(((const char *)o) + instr.createSimple.typeSize);
                const QDeclarativeCompiledData::TypeReference &ref = types.at(instr.createSimple.type);
                if (!ddata->propertyCache && ref.typePropertyCache) {
                    ddata->propertyCache = ref.typePropertyCache;
                    ddata->propertyCache->addref();
                }
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.createSimple.column;

                QObjectPrivate::get(o)->declarativeData = ddata;                                                      
                ddata->context = ddata->outerContext = ctxt;
                ddata->nextContextObject = ctxt->contextObjects; 
                if (ddata->nextContextObject) 
                    ddata->nextContextObject->prevContextObject = &ddata->nextContextObject; 
                ddata->prevContextObject = &ctxt->contextObjects; 
                ctxt->contextObjects = ddata; 

                QObject *parent = stack.top();                                                                    
                QDeclarative_setParent_noEvent(o, parent);                                                        

                stack.push(o);
            }
            break;

        case QDeclarativeInstruction::SetId:
            {
                QObject *target = stack.top();
                ctxt->setIdProperty(instr.setId.index, target);
            }
            break;


        case QDeclarativeInstruction::SetDefault:
            {
                ctxt->contextObject = stack.top();
            }
            break;

        case QDeclarativeInstruction::CreateComponent:
            {
                QDeclarativeComponent *qcomp = 
                    new QDeclarativeComponent(ctxt->engine, comp, ii + 1, instr.createComponent.count,
                                              stack.isEmpty() ? 0 : stack.top());

                QDeclarativeData *ddata = QDeclarativeData::get(qcomp, true);
                Q_ASSERT(ddata);

                ctxt->addObject(qcomp);

                if (stack.isEmpty()) 
                    ddata->ownContext = true;

                ddata->setImplicitDestructible();
                ddata->outerContext = ctxt;
                ddata->lineNumber = instr.line;
                ddata->columnNumber = instr.create.column;

                QDeclarativeComponentPrivate::get(qcomp)->creationContext = ctxt;

                stack.push(qcomp);
                ii += instr.createComponent.count;
            }
            break;

        case QDeclarativeInstruction::StoreMetaObject:
            {
                QObject *target = stack.top();

                QMetaObject mo;
                const QByteArray &metadata = datas.at(instr.storeMeta.data);
                QMetaObjectBuilder::fromRelocatableData(&mo, 0, metadata);

                const QDeclarativeVMEMetaData *data = 
                    (const QDeclarativeVMEMetaData *)datas.at(instr.storeMeta.aliasData).constData();

                (void)new QDeclarativeVMEMetaObject(target, &mo, data, comp);

                if (instr.storeMeta.propertyCache != -1) {
                    QDeclarativeData *ddata = QDeclarativeData::get(target, true);
                    if (ddata->propertyCache) ddata->propertyCache->release();
                    ddata->propertyCache = propertyCaches.at(instr.storeMeta.propertyCache);
                    ddata->propertyCache->addref();
                }
            }
            break;

        case QDeclarativeInstruction::StoreVariant:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                // XXX - can be more efficient
                QVariant v = QDeclarativeStringConverters::variantFromString(primitives.at(instr.storeString.value));
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeInteger.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeDouble.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVariantBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                QVariant v(instr.storeBool.value);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreString:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeString.propertyIndex);

                void *a[] = { (void *)&primitives.at(instr.storeString.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreUrl:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeUrl.propertyIndex);

                void *a[] = { (void *)&urls.at(instr.storeUrl.value), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeUrl.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreFloat:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeFloat.propertyIndex);

                float f = instr.storeFloat.value;
                void *a[] = { &f, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeFloat.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDouble:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDouble.propertyIndex);

                double d = instr.storeDouble.value;
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDouble.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreBool:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeBool.propertyIndex);

                void *a[] = { (void *)&instr.storeBool.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeBool.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInteger:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeInteger.propertyIndex);

                void *a[] = { (void *)&instr.storeInteger.value, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeInteger.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreColor:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeColor.propertyIndex);

                QColor c = QColor::fromRgba(instr.storeColor.value);
                void *a[] = { &c, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeColor.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDate:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDate.propertyIndex);

                QDate d = QDate::fromJulianDay(instr.storeDate.value);
                void *a[] = { &d, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeDate.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeTime.valueIndex),
                         intData.at(instr.storeTime.valueIndex+1),
                         intData.at(instr.storeTime.valueIndex+2),
                         intData.at(instr.storeTime.valueIndex+3));
                void *a[] = { &t, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreDateTime:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeDateTime.propertyIndex);

                QTime t;
                t.setHMS(intData.at(instr.storeDateTime.valueIndex+1),
                         intData.at(instr.storeDateTime.valueIndex+2),
                         intData.at(instr.storeDateTime.valueIndex+3),
                         intData.at(instr.storeDateTime.valueIndex+4));
                QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t);
                void *a[] = { &dt, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty,
                                      instr.storeDateTime.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePoint:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex),
                                   floatData.at(instr.storeRealPair.valueIndex+1)).toPoint();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StorePointF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QPointF p(floatData.at(instr.storeRealPair.valueIndex),
                          floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSize:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex),
                                 floatData.at(instr.storeRealPair.valueIndex+1)).toSize();
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreSizeF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRealPair.propertyIndex);

                QSizeF s(floatData.at(instr.storeRealPair.valueIndex),
                         floatData.at(instr.storeRealPair.valueIndex+1));
                void *a[] = { &s, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRealPair.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRect:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRect r = QRectF(floatData.at(instr.storeRect.valueIndex),
                                 floatData.at(instr.storeRect.valueIndex+1),
                                 floatData.at(instr.storeRect.valueIndex+2),
                                 floatData.at(instr.storeRect.valueIndex+3)).toRect();
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreRectF:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeRect.propertyIndex);

                QRectF r(floatData.at(instr.storeRect.valueIndex),
                         floatData.at(instr.storeRect.valueIndex+1),
                         floatData.at(instr.storeRect.valueIndex+2),
                         floatData.at(instr.storeRect.valueIndex+3));
                void *a[] = { &r, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeRect.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreVector3D:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeVector3D.propertyIndex);

                QVector3D p(floatData.at(instr.storeVector3D.valueIndex),
                            floatData.at(instr.storeVector3D.valueIndex+1),
                            floatData.at(instr.storeVector3D.valueIndex+2));
                void *a[] = { &p, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeVector3D.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreObject:
            {
                QObject *assignObj = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                void *a[] = { (void *)&assignObj, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;


        case QDeclarativeInstruction::AssignCustomType:
            {
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.assignCustomType.propertyIndex);

                QDeclarativeCompiledData::CustomTypeData data = customTypeData.at(instr.assignCustomType.valueIndex);
                const QString &primitive = primitives.at(data.index);
                QDeclarativeMetaType::StringConverter converter = 
                    QDeclarativeMetaType::customStringConverter(data.type);
                QVariant v = (*converter)(primitive);

                QMetaProperty prop = 
                        target->metaObject()->property(instr.assignCustomType.propertyIndex);
                if (v.isNull() || ((int)prop.type() != data.type && prop.userType() != data.type)) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign value %1 to property %2").arg(primitive).arg(QString::fromUtf8(prop.name())));

                void *a[] = { (void *)v.data(), 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.assignCustomType.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::AssignSignalObject:
            {
                // XXX optimize

                QObject *assign = stack.pop();
                QObject *target = stack.top();
                int sigIdx = instr.assignSignalObject.signal;
                const QByteArray &pr = datas.at(sigIdx);

                QDeclarativeProperty prop(target, QString::fromUtf8(pr));
                if (prop.type() & QDeclarativeProperty::SignalProperty) {

                    QMetaMethod method = QDeclarativeMetaType::defaultMethod(assign);
                    if (method.signature() == 0)
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object type %1 with no default method").arg(QString::fromLatin1(assign->metaObject()->className())));

                    if (!QMetaObject::checkConnectArgs(prop.method().signature(), method.signature()))
                        VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot connect mismatched signal/slot %1 %vs. %2").arg(QString::fromLatin1(method.signature())).arg(QString::fromLatin1(prop.method().signature())));

                    QDeclarativePropertyPrivate::connect(target, prop.index(), assign, method.methodIndex());

                } else {
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign an object to signal property %1").arg(QString::fromUtf8(pr)));
                }


            }
            break;

        case QDeclarativeInstruction::StoreSignal:
            {
                QObject *target = stack.top();
                QObject *context = stack.at(stack.count() - 1 - instr.storeSignal.context);

                QMetaMethod signal = target->metaObject()->method(instr.storeSignal.signalIndex);

                QDeclarativeBoundSignal *bs = new QDeclarativeBoundSignal(target, signal, target);
                QDeclarativeExpression *expr = 
                    new QDeclarativeExpression(ctxt, context, primitives.at(instr.storeSignal.value));
                expr->setSourceLocation(comp->name, instr.line);
                static_cast<QDeclarativeExpressionPrivate *>(QObjectPrivate::get(expr))->name = datas.at(instr.storeSignal.name);
                bs->setExpression(expr);
            }
            break;

        case QDeclarativeInstruction::StoreImportedScript:
            {
                ctxt->addImportedScript(scripts.at(instr.storeScript.value));
            }
            break;

        case QDeclarativeInstruction::StoreScriptString:
            {
                QObject *target = stack.top();
                QObject *scope = stack.at(stack.count() - 1 - instr.storeScriptString.scope);
                QDeclarativeScriptString ss;
                ss.setContext(ctxt->asQDeclarativeContext());
                ss.setScopeObject(scope);
                ss.setScript(primitives.at(instr.storeScriptString.value));

                void *a[] = { &ss, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeScriptString.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::BeginObject:
            {
                QObject *target = stack.top();
                QDeclarativeParserStatus *status = reinterpret_cast<QDeclarativeParserStatus *>(reinterpret_cast<char *>(target) + instr.begin.castValue);
                parserStatus.append(status);
                status->d = &parserStatus.values[parserStatus.count - 1];

                status->classBegin();
            }
            break;

        case QDeclarativeInstruction::StoreBinding:
        case QDeclarativeInstruction::StoreBindingOnAlias:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *context = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                QDeclarativeProperty mp = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignBinding.property), target, ctxt);

                int coreIndex = mp.index();

                if ((stack.count() - instr.assignBinding.owner) == 1 && bindingSkipList.testBit(coreIndex)) 
                    break;

                QDeclarativeBinding *bind = new QDeclarativeBinding((void *)datas.at(instr.assignBinding.value).constData(), comp, context, ctxt, comp->name, instr.line, 0);
                bindValues.append(bind);
                bind->m_mePtr = &bindValues.values[bindValues.count - 1];
                bind->setTarget(mp);

                if (instr.type == QDeclarativeInstruction::StoreBindingOnAlias) {
                    QDeclarativeAbstractBinding *old = QDeclarativePropertyPrivate::setBindingNoEnable(target, coreIndex, QDeclarativePropertyPrivate::valueTypeCoreIndex(mp), bind);
                    if (old) { old->destroy(); }
                } else {
                    bind->addToObject(target, QDeclarativePropertyPrivate::bindingIndex(mp));
                }
            }
            break;

        case QDeclarativeInstruction::StoreCompiledBinding:
            {
                QObject *target = 
                    stack.at(stack.count() - 1 - instr.assignBinding.owner);
                QObject *scope = 
                    stack.at(stack.count() - 1 - instr.assignBinding.context);

                int property = instr.assignBinding.property;
                if (stack.count() == 1 && bindingSkipList.testBit(property & 0xFFFF))  
                    break;

                QDeclarativeAbstractBinding *binding = 
                    ctxt->optimizedBindings->configBinding(instr.assignBinding.value, target, scope, property);
                bindValues.append(binding);
                binding->m_mePtr = &bindValues.values[bindValues.count - 1];
                binding->addToObject(target, property);
            }
            break;

        case QDeclarativeInstruction::StoreValueSource:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueSource *vs = reinterpret_cast<QDeclarativePropertyValueSource *>(reinterpret_cast<char *>(obj) + instr.assignValueSource.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueSource.owner);

                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueSource.property), target, ctxt);
                obj->setParent(target);
                vs->setTarget(prop);
            }
            break;

        case QDeclarativeInstruction::StoreValueInterceptor:
            {
                QObject *obj = stack.pop();
                QDeclarativePropertyValueInterceptor *vi = reinterpret_cast<QDeclarativePropertyValueInterceptor *>(reinterpret_cast<char *>(obj) + instr.assignValueInterceptor.castValue);
                QObject *target = stack.at(stack.count() - 1 - instr.assignValueInterceptor.owner);
                QDeclarativeProperty prop = 
                    QDeclarativePropertyPrivate::restore(datas.at(instr.assignValueInterceptor.property), target, ctxt);
                obj->setParent(target);
                vi->setTarget(prop);
                QDeclarativeVMEMetaObject *mo = static_cast<QDeclarativeVMEMetaObject *>((QMetaObject*)target->metaObject());
                mo->registerInterceptor(prop.index(), QDeclarativePropertyPrivate::valueTypeCoreIndex(prop), vi);
            }
            break;

        case QDeclarativeInstruction::StoreObjectQList:
            {
                QObject *assign = stack.pop();

                const ListInstance &list = qliststack.top();
                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, assign);
            }
            break;

        case QDeclarativeInstruction::AssignObjectList:
            {
                // This is only used for assigning interfaces
                QObject *assign = stack.pop();
                const ListInstance &list = qliststack.top();

                int type = list.type;

                void *ptr = 0;

                const char *iid = QDeclarativeMetaType::interfaceIId(type);
                if (iid) 
                    ptr = assign->qt_metacast(iid);
                if (!ptr) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to list"));


                list.qListProperty.append((QDeclarativeListProperty<void>*)&list.qListProperty, ptr);
            }
            break;

        case QDeclarativeInstruction::StoreVariantObject:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                QVariant v = QVariant::fromValue(assign);
                void *a[] = { &v, 0, &status, &flags };
                QMetaObject::metacall(target, QMetaObject::WriteProperty, 
                                      instr.storeObject.propertyIndex, a);
            }
            break;

        case QDeclarativeInstruction::StoreInterface:
            {
                QObject *assign = stack.pop();
                QObject *target = stack.top();
                CLEAN_PROPERTY(target, instr.storeObject.propertyIndex);

                int coreIdx = instr.storeObject.propertyIndex;
                QMetaProperty prop = target->metaObject()->property(coreIdx);
                int t = prop.userType();
                const char *iid = QDeclarativeMetaType::interfaceIId(t);
                bool ok = false;
                if (iid) {
                    void *ptr = assign->qt_metacast(iid);
                    if (ptr) {
                        void *a[] = { &ptr, 0, &status, &flags };
                        QMetaObject::metacall(target, 
                                              QMetaObject::WriteProperty,
                                              coreIdx, a);
                        ok = true;
                    }
                } 

                if (!ok) 
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot assign object to interface property"));
            }
            break;
            
        case QDeclarativeInstruction::FetchAttached:
            {
                QObject *target = stack.top();

                QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target);

                if (!qmlObject)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Unable to create attached object"));

                stack.push(qmlObject);
            }
            break;

        case QDeclarativeInstruction::FetchQList:
            {
                QObject *target = stack.top();

                qliststack.push(ListInstance(instr.fetchQmlList.type));

                void *a[1];
                a[0] = (void *)&(qliststack.top().qListProperty);
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetchQmlList.property, a);
            }
            break;

        case QDeclarativeInstruction::FetchObject:
            {
                QObject *target = stack.top();

                QObject *obj = 0;
                // NOTE: This assumes a cast to QObject does not alter the 
                // object pointer
                void *a[1];
                a[0] = &obj;
                QMetaObject::metacall(target, QMetaObject::ReadProperty, 
                                      instr.fetch.property, a);

                if (!obj)
                    VME_EXCEPTION(QCoreApplication::translate("QDeclarativeVME","Cannot set properties on %1 as it is null").arg(QString::fromUtf8(target->metaObject()->property(instr.fetch.property).name())));

                stack.push(obj);
            }
            break;

        case QDeclarativeInstruction::PopQList:
            {
                qliststack.pop();
            }
            break;

        case QDeclarativeInstruction::Defer:
            {
                if (instr.defer.deferCount) {
                    QObject *target = stack.top();
                    QDeclarativeData *data = 
                        QDeclarativeData::get(target, true);
                    comp->addref();
                    data->deferredComponent = comp;
                    data->deferredIdx = ii;
                    ii += instr.defer.deferCount;
                }
            }
            break;

        case QDeclarativeInstruction::PopFetchedObject:
            {
                stack.pop();
            }
            break;

        case QDeclarativeInstruction::FetchValueType:
            {
                QObject *target = stack.top();

                if (instr.fetchValue.bindingSkipList != 0) {
                    // Possibly need to clear bindings
                    QDeclarativeData *targetData = QDeclarativeData::get(target);
                    if (targetData) {
                        QDeclarativeAbstractBinding *binding = 
                            QDeclarativePropertyPrivate::binding(target, instr.fetchValue.property, -1);

                        if (binding && binding->bindingType() != QDeclarativeAbstractBinding::ValueTypeProxy) {
                            QDeclarativePropertyPrivate::setBinding(target, instr.fetchValue.property, -1, 0);
                            binding->destroy();
                        } else if (binding) {
                            QDeclarativeValueTypeProxyBinding *proxy = 
                                static_cast<QDeclarativeValueTypeProxyBinding *>(binding);
                            proxy->removeBindings(instr.fetchValue.bindingSkipList);
                        }
                    }
                }

                QDeclarativeValueType *valueHandler = ep->valueTypes[instr.fetchValue.type];
                valueHandler->read(target, instr.fetchValue.property);
                stack.push(valueHandler);
            }
            break;

        case QDeclarativeInstruction::PopValueType:
            {
                QDeclarativeValueType *valueHandler = 
                    static_cast<QDeclarativeValueType *>(stack.pop());
                QObject *target = stack.top();
                valueHandler->write(target, instr.fetchValue.property, 
                                    QDeclarativePropertyPrivate::BypassInterceptor);
            }
            break;

        default:
            qFatal("QDeclarativeCompiledData: Internal error - unknown instruction %d", instr.type);
            break;
        }
    }

    if (isError()) {
        if (!stack.isEmpty()) {
            delete stack.at(0); // ### What about failures in deferred creation?
        } else {
            ctxt->destroy();
        }

        QDeclarativeEnginePrivate::clear(bindValues);
        QDeclarativeEnginePrivate::clear(parserStatus);
        return 0;
    }

    if (bindValues.count)
        ep->bindValues << bindValues;
    else if (bindValues.values)
        bindValues.clear();

    if (parserStatus.count)
        ep->parserStatus << parserStatus;
    else if (parserStatus.values)
        parserStatus.clear();

    Q_ASSERT(stack.count() == 1);
    return stack.top();
}
示例#19
0
bool qtSDLTreeModel::setData(const QModelIndex &index, const QVariant &value, int role) {
    if(role != Qt::EditRole || value.type() != QVariant::String || index.column() != 0)
        return false;
    QString* strVal = (QString*)value.data();
    SDLModelIndex myIndex = indices[index.internalId()];
    if(myIndex.type != kVal)
        return false;
    plSimpleStateVariable* var = (plSimpleStateVariable*)myIndex.ptr.sv;
    switch(var->getDescriptor()->getType()) {
    case plVarDescriptor::kBool:
        if(*strVal == "True")
            var->Bool(index.row()) = true;
        else if(*strVal == "False")
            var->Bool(index.row()) = false;
        else
            return false;
        break;
    case plVarDescriptor::kInt:
    {
        bool result;
        int value = strVal->toInt(&result);
        if(result)
            var->Int(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kByte:
    {
        bool result;
        int value = strVal->toInt(&result);
        if(result && value >= 0 && value < 256)
            var->Byte(index.row()) = (unsigned char)value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kChar:
    {
        char* str = strVal->toLocal8Bit().data();
        if(strlen(str) == 1)
            var->Char(index.row()) = str[0];
        else
            return false;
        break;
     }
    case plVarDescriptor::kFloat:
    {
        bool result;
        float value = strVal->toFloat(&result);
        if(result)
            var->Float(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kDouble:
    {
        bool result;
        double value = strVal->toDouble(&result);
        if(result)
            var->Double(index.row()) = value;
        else
            return false;
        break;
    }
    case plVarDescriptor::kString:
        var->String(index.row()) = plString(strVal->toLocal8Bit().data());
        break;
    default:
        return false;
    }
    emit sdlChanged(sdl);
    return true;
}
void TabbedMainWindow::findUsers(QString hostname, QString usernamepassword, int condition1, QString condition2, QString argument, QListWidget * list, QListWidget * list2) {
    //First maybe we clear the dang list?!
    QString condition1String, condition2String;

    if (condition1 == 0) {
        condition1String = "enduser.firstname";
    } else if (condition1 == 1) {
        condition1String = "enduser.middlename";
    } else if (condition1 == 2) {
        condition1String = "enduser.lastname";
    } else if (condition1 == 3) {
        condition1String = "enduser.userid";
    } else if (condition1 == 4) {
        condition1String = "enduser.islocaluser";
    } else if (condition1 == 5) {
        condition1String = "enduser.telephonenumber";
    }

    if (condition2 == "Equals") {
        condition2String = "= '" + argument.toLower() + "'";
    } else if (condition2 == "Contains") {
        condition2String = "LIKE '%" + argument.toLower() + "%'";
    } else if (condition2 == "Begins with") {
        condition2String = "LIKE '" + argument.toLower() + "%'";
    } else if (condition2 == "Ends with") {
        condition2String = "LIKE '%" + argument.toLower() + "'";
    } else if (condition2 == "Is Empty") {
        condition2String = "IS NULL";
    } else if (condition2 == "Is not Empty") {
        condition2String = "IS NOT NULL";
    } else if (condition2 == "True") {
        condition2String = "= 't'";
    } else if (condition2 == "False") {
        condition2String = "= 'f'";
    }

    ProgressDialog progbar("CMClusters - Connecting...", "Please wait while a connection to the selected clusters are established!");
    progbar.show();
    QByteArray jsonString = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://www.cisco.com/AXL/API/8.5\">";
    if (condition1 == 4) {
        jsonString += "<soapenv:Body><ns:executeSQLQuery><sql>SELECT enduser.userid,enduser.firstname,enduser.middlename,enduser.lastname,enduser.islocaluser,enduser.telephonenumber from enduser where "
                + condition1String + condition2String + "</sql></ns:executeSQLQuery></SOAP-ENV:Envelope>";
    } else {
    jsonString += "<soapenv:Body><ns:executeSQLQuery><sql>SELECT enduser.userid,enduser.firstname,enduser.middlename,enduser.lastname,enduser.islocaluser,enduser.telephonenumber from enduser where lower("
            + condition1String + ") " + condition2String + "</sql></ns:executeSQLQuery></SOAP-ENV:Envelope>";
    }
    QByteArray postDataSize = QByteArray::number(jsonString.size());
    QUrl req("https://" + hostname.toLocal8Bit() + ":8443/axl/");
    QNetworkRequest request(req);

    request.setRawHeader("SOAPAction", "\"CUCM:DB ver=8.5 executeSQLQuery\"");
    request.setRawHeader("Authorization", "Basic " + usernamepassword.toLocal8Bit());
    request.setRawHeader("Content-Type", "text/xml");
    request.setRawHeader("Content-Length", postDataSize);

    QNetworkAccessManager test;
    QEventLoop loop;
    connect(&test, SIGNAL(finished(QNetworkReply*)), &loop, SLOT(quit()));
    QNetworkReply * reply = test.post(request, jsonString);
    reply->ignoreSslErrors(); // Ignore only unsigned later on
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
    loop.exec();

    QByteArray response = reply->readAll();
    QVariant statusCode = reply->attribute( QNetworkRequest::HttpStatusCodeAttribute );

    if ( !statusCode.isValid() ) {
        qDebug() << "Failed...";
        qDebug() << statusCode.data();
    }

    int status = statusCode.toInt();

    if ( status != 200 ) {
        QString reason = reply->attribute( QNetworkRequest::HttpReasonPhraseAttribute ).toString();
        qDebug() << reason;
    } else {
        qDebug() << "Good reply";
        //qDebug() << response;
        QDomDocument doc;
        doc.setContent(response);
            QDomNodeList rates = doc.elementsByTagName("row");
            for (int i = 0; i < rates.size(); i++) {
                QString finalString;
                QDomNode n = rates.item(i);
                QDomElement firstname = n.firstChildElement("firstname");
                if (firstname.text() != "")
                    finalString = firstname.text() + " ";
                QDomElement middlename = n.firstChildElement("middlename");
                if (middlename.text() != "")
                    finalString += middlename.text() + " ";
                QDomElement lastname = n.firstChildElement("lastname");
                if (lastname.text() != " ")
                    finalString += lastname.text();
                QDomElement userid = n.firstChildElement("userid");
                finalString += " (" + userid.text() + ") ";
                QDomElement islocaluser = n.firstChildElement("islocaluser");
                QDomElement telephonenumber = n.firstChildElement("telephonenumber");
                    if (telephonenumber.text() != "") {
                        finalString += " [" + telephonenumber.text() + "]";
                    } else {
                        finalString += " [No Telephone Number]";
                    }
                QListWidgetItem* user = new QListWidgetItem(finalString);
                if (islocaluser.text() == "t") {
                    user->setBackground(QColor(0, 170, 255));
                    list2->addItem(user);
                } else {
                    user->setBackground(QColor(170, 0, 0));
                    list->addItem(user);
                }
            }
    }
}
示例#21
0
static void writeAttribute(QXmlStreamWriter *stream, const QVariant &attribute)
{
    const QString unsignedFormat(QStringLiteral("0x%1"));

    switch (int(attribute.type())) {
    case QMetaType::Void:
        stream->writeEmptyElement(QStringLiteral("nil"));
        break;
    case QMetaType::UChar:
        stream->writeEmptyElement(QStringLiteral("uint8"));
        stream->writeAttribute(QStringLiteral("value"),
                               unsignedFormat.arg(attribute.value<quint8>(), 2, 16,
                                                  QLatin1Char('0')));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::UShort:
        stream->writeEmptyElement(QStringLiteral("uint16"));
        stream->writeAttribute(QStringLiteral("value"),
                               unsignedFormat.arg(attribute.value<quint16>(), 4, 16,
                                                  QLatin1Char('0')));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::UInt:
        stream->writeEmptyElement(QStringLiteral("uint32"));
        stream->writeAttribute(QStringLiteral("value"),
                               unsignedFormat.arg(attribute.value<quint32>(), 8, 16,
                                                  QLatin1Char('0')));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::Char:
        stream->writeEmptyElement(QStringLiteral("int8"));
        stream->writeAttribute(QStringLiteral("value"),
                               QString::number(attribute.value<uchar>(), 16));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::Short:
        stream->writeEmptyElement(QStringLiteral("int16"));
        stream->writeAttribute(QStringLiteral("value"),
                               QString::number(attribute.value<qint16>(), 16));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::Int:
        stream->writeEmptyElement(QStringLiteral("int32"));
        stream->writeAttribute(QStringLiteral("value"),
                               QString::number(attribute.value<qint32>(), 16));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
    case QMetaType::QString:
        stream->writeEmptyElement(QStringLiteral("text"));
        if (/* require hex encoding */ false) {
            stream->writeAttribute(QStringLiteral("value"), QString::fromLatin1(
                                       attribute.value<QString>().toUtf8().toHex().constData()));
            stream->writeAttribute(QStringLiteral("encoding"), QStringLiteral("hex"));
        } else {
            stream->writeAttribute(QStringLiteral("value"), attribute.value<QString>());
            stream->writeAttribute(QStringLiteral("encoding"), QStringLiteral("normal"));
        }
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
            case QMetaType::Bool:
        stream->writeEmptyElement(QStringLiteral("boolean"));
        if (attribute.value<bool>())
            stream->writeAttribute(QStringLiteral("value"), QStringLiteral("true"));
        else
            stream->writeAttribute(QStringLiteral("value"), QStringLiteral("false"));
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
            case QMetaType::QUrl:
        stream->writeEmptyElement(QStringLiteral("url"));
        stream->writeAttribute(QStringLiteral("value"), attribute.value<QUrl>().toString());
        //stream->writeAttribute(QStringLiteral("name"), foo);
        break;
            case QVariant::UserType:
        if (attribute.userType() == qMetaTypeId<QBluetoothUuid>()) {
            stream->writeEmptyElement(QStringLiteral("uuid"));

            QBluetoothUuid uuid = attribute.value<QBluetoothUuid>();
            switch (uuid.minimumSize()) {
            case 0:
                stream->writeAttribute(QStringLiteral("value"),
                                       unsignedFormat.arg(quint16(0), 4, 16, QLatin1Char('0')));
                break;
            case 2:
                stream->writeAttribute(QStringLiteral("value"),
                                       unsignedFormat.arg(uuid.toUInt16(), 4, 16,
                                                          QLatin1Char('0')));
                break;
            case 4:
                stream->writeAttribute(QStringLiteral("value"),
                                       unsignedFormat.arg(uuid.toUInt32(), 8, 16,
                                                          QLatin1Char('0')));
                break;
            case 16:
                stream->writeAttribute(QStringLiteral("value"), uuid.toString().mid(1, 36));
                break;
            default:
                stream->writeAttribute(QStringLiteral("value"), uuid.toString().mid(1, 36));
            }
        } else if (attribute.userType() == qMetaTypeId<QBluetoothServiceInfo::Sequence>()) {
            stream->writeStartElement(QStringLiteral("sequence"));
            const QBluetoothServiceInfo::Sequence *sequence =
                    static_cast<const QBluetoothServiceInfo::Sequence *>(attribute.data());
            foreach (const QVariant &v, *sequence)
                writeAttribute(stream, v);
            stream->writeEndElement();
        } else if (attribute.userType() == qMetaTypeId<QBluetoothServiceInfo::Alternative>()) {
示例#22
0
/*!
    Client side method call that directly accesses the object through the DBus interface.
    All arguments and return types are processed and converted accordingly so that all functions
    satisfy the QtDBus type system.
*/
QVariant ObjectEndPoint::invokeRemote(int metaIndex, const QVariantList& args, int returnType)
{
    QMetaMethod method = service->metaObject()->method(remoteToLocal[metaIndex]);

    Q_ASSERT(d->endPointType == ObjectEndPoint::Client);

    // Check is this is a signal relay
    if (method.methodType() == QMetaMethod::Signal) {
        // Convert custom arguments
        QVariantList convertedList;
        QList<QByteArray> params = method.parameterTypes();
        for (int i = 0; i < params.size(); i++) {
            const QByteArray& type = params[i];
            int variantType = QMetaType::type(type);
            if (variantType >= QMetaType::User || variantType == QMetaType::QVariant) {
                QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(args[i]);
                QVariant variant = dbusVariant.variant();

                if (variantType == QMetaType::QVariant) {
                    convertedList << variant;
                } else {
                    QByteArray buffer = variant.toByteArray();
                    QDataStream stream(&buffer, QIODevice::ReadWrite);
                    QVariant *customType = new QVariant(variantType, (const void*)0);
                    QMetaType::load(stream, QMetaType::QVariant, customType);
                    convertedList << *customType;
                }
            } else {
                convertedList << args[i];
            }
        }

        // Signal relay
        const int numArgs = convertedList.size();
        QVarLengthArray<void *, 32> a( numArgs+1 );
        a[0] = 0;

        const QList<QByteArray> pTypes = method.parameterTypes();
        for ( int arg = 0; arg < numArgs; ++arg ) {
            if (pTypes.at(arg) == "QVariant") {
                a[arg+1] = (void *)&( convertedList[arg] );
            } else {
                a[arg+1] = (void *)( convertedList[arg].data() );
            }
        }

        // Activate the service proxy signal call
        QMetaObject::activate(service, remoteToLocal[metaIndex], a.data());
        return QVariant();
    }

    // Method call so process arguments and convert if not a supported DBus type
    QVariantList convertedList;
    QList<QByteArray> params = method.parameterTypes();
    for (int i = 0; i < params.size(); i++) {
        QVariant converted = toDBusVariant(params[i], args[i]);
        convertedList << converted;
    }

    bool validDBus = false;
    QDBusMessage msg;

    // Find the method name and try a direct DBus call
    QString methodName(QLatin1String(method.methodSignature().constData()));
    methodName.truncate(methodName.indexOf(QLatin1String("(")));

    if (method.methodType() == QMetaMethod::Slot || method.methodType() == QMetaMethod::Method) {
        // Slot or Invokable method
        msg = iface->callWithArgumentList(QDBus::Block, methodName, convertedList);
        if (msg.type() == QDBusMessage::ReplyMessage) {
            validDBus = true;
        }
    }

    // DBus call should only fail for methods with invalid type definitions
    if (validDBus) {
        if (returnType == QMetaType::Void) {
            // Void method call
            return QVariant();
        }
        else {
            // Use DBus message return value
            QVariantList retList = msg.arguments();

            // Process return
            const QByteArray& retType = QByteArray(method.typeName());
            int variantType = QMetaType::type(retType);
            if (variantType == QMetaType::QVariant) {
                // QVariant return from QDBusVariant wrapper
                QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(retList[0]);
                return dbusVariant.variant();
            } else if (variantType >= QMetaType::User) {
                // Custom return type
                QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(retList[0]);
                QVariant convert = dbusVariant.variant();

                QServiceUserTypeDBus customType = qdbus_cast<QServiceUserTypeDBus>(convert);
                QByteArray buffer = customType.variantBuffer;
                QDataStream stream(&buffer, QIODevice::ReadWrite);

                // Load our buffered variant-wrapped custom return
                QVariant *customReturn = new QVariant(variantType, (const void*)0);
                QMetaType::load(stream, QMetaType::QVariant, customReturn);

                return QVariant(variantType, customReturn->data());
            } else {
                // Standard return type
                return retList[0];
            }
        }
    } else {
        qWarning( "%s::%s cannot be called.", service->metaObject()->className(), method.methodSignature().constData());
    }

    return QVariant();
}
示例#23
0
// Author & Date: Ehsan Azar       3 April 2012
// Purpose: Begin a new Xml group or navigate to it if it exists
// Inputs:
//   nodeName  - the node tag (it can be in the form of relative/path/to/node)
//                node index (0-based) is enclosed (relative/path/to/node<2>/subnode)
//             Note: nodeName tags are always created if they do not exist
//   attribs   - attribute name, attribute value pairs
//   value     - new node value, if non-empty
// Outputs:
//  Returns true if nodeName is created
bool XmlFile::beginGroup(QString nodeName, const QMap<QString, QVariant> attribs, const QVariant & value)
{
    bool bRet = false;
    QDomElement set;

    if (nodeName.isEmpty())
        nodeName = firstChildKey();
    if (nodeName.isEmpty())
        nodeName = "XmlItem";
    // Get the node path
    QStringList nodepath = nodeName.split("/");
    int level = nodepath.count();
    m_levels.append(level);
    for (int i = 0; i < level; ++i)
    {
        QString strTagName = nodepath[i];
        // Extract index
        int index = 0;
        {
            int idx = strTagName.indexOf("<");
            if (idx >= 0)
            {
                index = strTagName.mid(idx + 1, strTagName.length() - idx - 2).toInt();
                strTagName = strTagName.left(idx);
                nodepath[i] = strTagName;
            }
        }
        // Look if the element (with given index) exists then get it
        QDomNode parent;
        if (!m_nodes.isEmpty())
        {
            // Get the current node
            parent = m_nodes.last();
        } else {
            parent = m_doc;
        }
        int count = 0;
        for(QDomElement elem = parent.firstChildElement(strTagName); !elem.isNull(); elem = elem.nextSiblingElement(strTagName))
        {
            count++;
            if (count == index + 1)
            {
                set = elem;
                break;
            }
        }
        // Create all new subnodes
        for (int j = 0; j < (index + 1 - count); ++j)
        {
            bRet = true;
            set = m_doc.createElement(strTagName);
            parent.appendChild(set);
        }
        // Add all the parent nodes without attribute or value
        if (i < level - 1)
            m_nodes.append(set);
    }
    
    // Now add the node to the end of the list
    m_nodes.append(set);

    // if there is some text/value to set
    if (value.isValid())
    {
        bool bTextLeaf = false;
        QVariantList varlst;
        switch (value.type())
        {
        case QVariant::StringList:
        case QVariant::List:
            varlst = value.toList();
            if (AddList(varlst, nodepath.last()))
                set.setAttribute("Type", "Array");
            break;
        default:
            QString text;
            if (value.type() == QVariant::UserType)
            {
                const XmlItem * item = static_cast<const XmlItem *>(value.data());
                QVariant subval = item->XmlValue();
                
                if (subval.type() == QVariant::UserType)
                {
                    const XmlItem * subitem = static_cast<const XmlItem *>(subval.data());
                    QString strSubKey = subitem->XmlName();
                    QMap<QString, QVariant> attribs = subitem->XmlAttribs();
                    // Recursively add this item
                    beginGroup(strSubKey, attribs, subval);
                    endGroup();
                } 
                else if (subval.type() == QVariant::List || subval.type() == QVariant::StringList)
                {
                    varlst = subval.toList();
                    if (AddList(varlst, nodepath.last()))
                        set.setAttribute("Type", "Array");
                } else {
                    text = subval.toString();
                    bTextLeaf = true;
                }
            } else {
                text = value.toString();
                bTextLeaf = true;
            }
            if (bTextLeaf)
            {
                // Remove all the children
                while (set.hasChildNodes())
                    set.removeChild(set.lastChild());
                // See if this is Xml fragment string
                XmlFile xml;
                if (!xml.setContent(text))
                {
                    QDomNode frag = m_doc.importNode(xml.getFragment(), true);
                    set.appendChild(frag);
                } else {
                    QDomText domText = m_doc.createTextNode(text);
                    set.appendChild(domText);
                }
            }
        }
    }

    // Add all the additional attributes
    QMap<QString, QVariant>::const_iterator iterator;
    for (iterator = attribs.begin(); iterator != attribs.end(); ++iterator)
    {
        QString attrName = iterator.key();
        QVariant attrValue = iterator.value();
        switch (attrValue.type())
        {
        case QVariant::String:
            set.setAttribute(attrName, attrValue.toString());
            break;
        case QVariant::Int:
            set.setAttribute(attrName, attrValue.toInt());
            break;
        case QVariant::UInt:
            set.setAttribute(attrName, attrValue.toUInt());
            break;
        case QVariant::LongLong:
            set.setAttribute(attrName, attrValue.toLongLong());
            break;
        case QVariant::ULongLong:
            set.setAttribute(attrName, attrValue.toULongLong());
            break;
        default:
            // everything else is treated as double floating point
            set.setAttribute(attrName, attrValue.toDouble());
            break;
        }
    }
    return bRet;
}
示例#24
0
文件: goqml.cpp 项目: chai2010/qml
void packDataValue(QVariant_ *var, DataValue *value)
{
    QVariant *qvar = reinterpret_cast<QVariant *>(var);

    // Some assumptions are made below regarding the size of types.
    // There's apparently no better way to handle this since that's
    // how the types with well defined sizes (qint64) are mapped to
    // meta-types (QMetaType::LongLong).
    switch ((int)qvar->type()) {
    case QVariant::Invalid:
        value->dataType = DTInvalid;
        break;
    case QMetaType::QUrl:
        *qvar = qvar->value<QUrl>().toString();
        // fallthrough
    case QMetaType::QString:
        {
            value->dataType = DTString;
            QByteArray ba = qvar->toByteArray();
            *(char**)(value->data) = local_strdup(ba.constData());
            value->len = ba.size();
            break;
        }
    case QMetaType::Bool:
        value->dataType = DTBool;
        *(qint8*)(value->data) = (qint8)qvar->toInt();
        break;
    case QMetaType::LongLong:
        // Some of these entries will have to be fixed when handling platforms
        // where sizeof(long long) != 8 or sizeof(int) != 4.
        value->dataType = DTInt64;
        *(qint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::ULongLong:
        value->dataType = DTUint64;
        *(quint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::Int:
        value->dataType = DTInt32;
        *(qint32*)(value->data) = qvar->toInt();
        break;
    case QMetaType::UInt:
        value->dataType = DTUint32;
        *(quint32*)(value->data) = qvar->toUInt();
        break;
    case QMetaType::VoidStar:
        value->dataType = DTUintptr;
        *(uintptr_t*)(value->data) = (uintptr_t)qvar->value<void *>();
        break;
    case QMetaType::Double:
        value->dataType = DTFloat64;
        *(double*)(value->data) = qvar->toDouble();
        break;
    case QMetaType::Float:
        value->dataType = DTFloat32;
        *(float*)(value->data) = qvar->toFloat();
        break;
    case QMetaType::QColor:
        value->dataType = DTColor;
        *(unsigned int*)(value->data) = qvar->value<QColor>().rgba();
        break;
    case QMetaType::QVariantList:
        {
            QVariantList varlist = qvar->toList();
            int len = varlist.size();
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            for (int i = 0; i < len; i++) {
                packDataValue((void*)&varlist.at(i), &dvlist[i]);
            }
            value->dataType = DTValueList;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    case QMetaType::QVariantMap:
        {
            QVariantMap varmap = qvar->toMap();
            int len = varmap.size() * 2;
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            QMapIterator<QString, QVariant> it(varmap);
            for (int i = 0; i < len; i += 2) {
                if (!it.hasNext()) {
                    panicf("QVariantMap mutated during iteration");
                }
                it.next();
                QVariant key = it.key();
                QVariant val = it.value();
                packDataValue((void*)&key, &dvlist[i]);
                packDataValue((void*)&val, &dvlist[i+1]);
            }
            value->dataType = DTValueMap;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    default:
        if (qvar->type() == (int)QMetaType::QObjectStar || qvar->canConvert<QObject *>()) {
            QObject *qobject = qvar->value<QObject *>();
            GoValue *goValue = dynamic_cast<GoValue *>(qobject);
            if (goValue) {
                value->dataType = DTGoAddr;
                *(void **)(value->data) = goValue->addr;
                break;
            }
            GoPaintedValue *goPaintedValue = dynamic_cast<GoPaintedValue *>(qobject);
            if (goPaintedValue) {
                value->dataType = DTGoAddr;
                *(void **)(value->data) = goPaintedValue->addr;
                break;
            }
            value->dataType = DTObject;
            *(void **)(value->data) = qobject;
            break;
        }
        {
            QQmlListReference ref = qvar->value<QQmlListReference>();
            if (ref.isValid() && ref.canCount() && ref.canAt()) {
                int len = ref.count();
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(ref.at(i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        if (qstrncmp(qvar->typeName(), "QQmlListProperty<", 17) == 0) {
            QQmlListProperty<QObject> *list = reinterpret_cast<QQmlListProperty<QObject>*>(qvar->data());
            if (list->count && list->at) {
                int len = list->count(list);
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(list->at(list, i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        panicf("unsupported variant type: %d (%s)", qvar->type(), qvar->typeName());
        break;
    }
}
void QpBelongsToOneBase::setObject(const QSharedPointer<QObject> newObject) const
{
    QSharedPointer<QObject> previousObject = object();
    data->cleared = newObject.isNull();
    if(previousObject == newObject)
        return;

    QpMetaProperty reverse = data->metaProperty.reverseRelation();
    data->object = newObject.toWeakRef();
    QSharedPointer<QObject> shared = Qp::sharedFrom(data->parent);

    if(previousObject) {
        if(reverse.isToOneRelationProperty()) {
            QString className = data->metaProperty.metaObject().className();
            reverse.write(previousObject.data(), Qp::Private::variantCast(QSharedPointer<QObject>(), className));
        }
        else {
            QVariant wrapper = Qp::Private::variantCast(shared);

            const QMetaObject *mo = previousObject->metaObject();
            QByteArray methodName = reverse.metaObject().removeObjectMethod(reverse).methodSignature();
            int index = mo->indexOfMethod(methodName);

            Q_ASSERT_X(index > 0, Q_FUNC_INFO,
                       QString("You have to add a public slot with the signature '%1' to your '%2' class!")
                       .arg(QString::fromLatin1(methodName))
                       .arg(mo->className())
                       .toLatin1());

            QMetaMethod method = mo->method(index);

            Q_ASSERT(method.invoke(previousObject.data(), Qt::DirectConnection,
                                   QGenericArgument(data->metaProperty.typeName().toLatin1(), wrapper.data())));
        }
    }

    if(newObject) {
        if(reverse.isToOneRelationProperty()) {
            reverse.write(newObject.data(), Qp::Private::variantCast(shared));
        }
        else {
            QVariant wrapper = Qp::Private::variantCast(shared);

            const QMetaObject *mo = newObject->metaObject();
            QByteArray methodName = reverse.metaObject().addObjectMethod(reverse).methodSignature();
            int index = mo->indexOfMethod(methodName);

            Q_ASSERT_X(index > 0, Q_FUNC_INFO,
                       QString("You have to add a public slot with the signature '%1' to your '%2' class!")
                       .arg(QString::fromLatin1(methodName))
                       .arg(mo->className())
                       .toLatin1());

            QMetaMethod method = mo->method(index);

            Q_ASSERT(method.invoke(newObject.data(), Qt::DirectConnection,
                                   QGenericArgument(data->metaProperty.typeName().toLatin1(), wrapper.data())));
        }
    }

    // Set again, because it may happen, that resetting the previousObjects relation has also reset this value.
    data->object = newObject.toWeakRef();
}
示例#26
0
 foreach (const QVariant &ar, args) {
     vargs.append(QGenericArgument(ar.typeName(), ar.data()));
 }
示例#27
0
QT_BEGIN_NAMESPACE

/*!
    \class QDBusReply
    \inmodule QtDBus
    \since 4.2

    \brief The QDBusReply class stores the reply for a method call to a remote object.

    A QDBusReply object is a subset of the QDBusMessage object that represents a method call's
    reply. It contains only the first output argument or the error code and is used by
    QDBusInterface-derived classes to allow returning the error code as the function's return
    argument.

    It can be used in the following manner:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 0

    If the remote method call cannot fail, you can skip the error checking:
    \snippet doc/src/snippets/code/src_qdbus_qdbusreply.cpp 1

    However, if it does fail under those conditions, the value returned by QDBusReply::value() is
    a default-constructed value. It may be indistinguishable from a valid return value.

    QDBusReply objects are used for remote calls that have no output
    arguments or return values (i.e., they have a "void" return
    type). Use the isValid() function to test if the reply succeeded.

    \sa QDBusMessage, QDBusInterface
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusMessage &reply)
    Automatically construct a QDBusReply object from the reply message \a reply, extracting the
    first return value from it if it is a success reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingReply<T> &reply)
    Constructs a QDBusReply object from the pending reply message, \a reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusPendingCall &pcall)
    Automatically construct a QDBusReply object from the asynchronous
    pending call \a pcall. If the call isn't finished yet, QDBusReply
    will call QDBusPendingCall::waitForFinished(), which is a blocking
    operation.

    If the return types patch, QDBusReply will extract the first
    return argument from the reply.
*/

/*!
    \fn QDBusReply::QDBusReply(const QDBusError &error)
    Constructs an error reply from the D-Bus error code given by \a error.
*/

/*!
    \fn QDBusReply::operator=(const QDBusReply &other)
    Makes this object be a copy of the object \a other.
*/

/*!
    \fn QDBusReply::operator=(const QDBusError &error)
    Sets this object to contain the error code given by \a error. You
    can later access it with error().
*/

/*!
    \fn QDBusReply::operator=(const QDBusMessage &message)

    Makes this object contain the reply specified by message \a
    message. If \a message is an error message, this function will
    copy the error code and message into this object

    If \a message is a standard reply message and contains at least
    one parameter, it will be copied into this object, as long as it
    is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn QDBusReply::operator=(const QDBusPendingCall &pcall)

    Makes this object contain the reply specified by the pending
    asynchronous call \a pcall. If the call is not finished yet, this
    function will call QDBusPendingCall::waitForFinished() to block
    until the reply arrives.

    If \a pcall finishes with an error message, this function will
    copy the error code and message into this object

    If \a pcall finished with a standard reply message and contains at
    least one parameter, it will be copied into this object, as long
    as it is of the correct type. If it's not of the same type as this
    QDBusError object, this function will instead set an error code
    indicating a type mismatch.
*/

/*!
    \fn bool QDBusReply::isValid() const

    Returns true if no error occurred; otherwise, returns false.

    \sa error()
*/

/*!
    \fn QDBusReply::error()

    Returns the error code that was returned from the remote function call. If the remote call did
    not return an error (i.e., if it succeeded), then the QDBusError object that is returned will
    not be a valid error code (QDBusError::isValid() will return false).

    \sa isValid()
*/

/*!
    \fn QDBusReply::value() const
    Returns the remote function's calls return value. If the remote call returned with an error,
    the return value of this function is undefined and may be undistinguishable from a valid return
    value.

    This function is not available if the remote call returns \c void.
*/

/*!
    \fn QDBusReply::operator Type() const
    Returns the same as value().

    This function is not available if the remote call returns \c void.
*/

/*!
    \internal
    Fills in the QDBusReply data \a error and \a data from the reply message \a reply.
*/
void qDBusReplyFill(const QDBusMessage &reply, QDBusError &error, QVariant &data)
{
    error = reply;

    if (error.isValid()) {
        data = QVariant();      // clear it
        return;
    }

    if (reply.arguments().count() >= 1 && reply.arguments().at(0).userType() == data.userType()) {
        data = reply.arguments().at(0);
        return;
    }

    const char *expectedSignature = QDBusMetaType::typeToSignature(data.userType());
    const char *receivedType = 0;
    QByteArray receivedSignature;

    if (reply.arguments().count() >= 1) {
        if (reply.arguments().at(0).userType() == QDBusMetaTypeId::argument) {
            // compare signatures instead
            QDBusArgument arg = qvariant_cast<QDBusArgument>(reply.arguments().at(0));
            receivedSignature = arg.currentSignature().toLatin1();
            if (receivedSignature == expectedSignature) {
                // matched. Demarshall it
                QDBusMetaType::demarshall(arg, data.userType(), data.data());
                return;
            }
        } else {
            // not an argument and doesn't match?
            int type = reply.arguments().at(0).userType();
            receivedType = QVariant::typeToName(QVariant::Type(type));
            receivedSignature = QDBusMetaType::typeToSignature(type);
        }
    }

    // error
    if (receivedSignature.isEmpty())
        receivedSignature = "no signature";
    QString errorMsg;
    if (receivedType) {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\" (%4), "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()),
                        QLatin1String(receivedType));
    } else {
        errorMsg = QString::fromLatin1("Unexpected reply signature: got \"%1\", "
                                         "expected \"%2\" (%3)")
                   .arg(QLatin1String(receivedSignature),
                        QLatin1String(expectedSignature),
                        QLatin1String(data.typeName()));
    }

    error = QDBusError(QDBusError::InvalidSignature, errorMsg);
    data = QVariant();      // clear it
}
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());
  const QVariant value = prop.read(m_obj.data());
  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 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(value);
    }
  } else if (role == Qt::EditRole) {
    if (index.column() == 1 && prop.isWritable()) {
      return value;
    }
  } else if (role == Qt::ToolTipRole) {
    return detailString(prop);
  } else if (role == PropertyModel::ActionRole) {
    return (prop.isResettable() ? PropertyModel::Reset : PropertyModel::NoAction)
         | ((MetaObjectRepository::instance()->metaObject(value.typeName()) && *reinterpret_cast<void* const*>(value.data())) || value.value<QObject*>()
            ? PropertyModel::NavigateTo
            : PropertyModel::NoAction);
  } else if (role == PropertyModel::ValueRole) {
    return value;
  } else if (role == PropertyModel::AppropriateToolRole) {
    ToolModel *toolModel = Probe::instance()->toolModel();
    ToolFactory *factory;
    if (value.canConvert<QObject*>())
      factory = toolModel->data(toolModel->toolForObject(value.value<QObject*>()), ToolModelRole::ToolFactory).value<ToolFactory*>();
    else
      factory = toolModel->data(toolModel->toolForObject(*reinterpret_cast<void* const*>(value.data()), value.typeName()), ToolModelRole::ToolFactory).value<ToolFactory*>();
    if (factory) {
      return factory->name();
    }
    return QVariant();
  }

  return QVariant();
}
void QpBelongsToManyBase::remove(QSharedPointer<QObject> object)
{
    QList<QSharedPointer<QObject>> obj = objects(); Q_UNUSED(obj); // resolve and keep a strong ref, while we're working here

    int removeCount = data->objects.removeAll(object.toWeakRef());
    Q_ASSERT(removeCount <= 1);

    if(removeCount == 0)
        return;

    QpMetaProperty reverse = data->metaProperty.reverseRelation();

    if(object){
        if(reverse.isToOneRelationProperty()) {
            QString className = data->metaProperty.metaObject().className();
            reverse.write(object.data(), Qp::Private::variantCast(QSharedPointer<QObject>(), className));
        }
        else {

            QSharedPointer<QObject> shared = Qp::sharedFrom(data->parent);
            QVariant wrapper = Qp::Private::variantCast(shared);

            const QMetaObject *mo = object->metaObject();
            QByteArray methodName = reverse.metaObject().removeObjectMethod(reverse).methodSignature();
            int index = mo->indexOfMethod(methodName);

            Q_ASSERT_X(index > 0, Q_FUNC_INFO,
                       QString("You have to add a public slot with the signature '%1' to your '%2' class!")
                       .arg(QString::fromLatin1(methodName))
                       .arg(mo->className())
                       .toLatin1());

            QMetaMethod method = mo->method(index);

            Q_ASSERT(method.invoke(object.data(), Qt::DirectConnection,
                                   QGenericArgument(data->metaProperty.typeName().toLatin1(), wrapper.data())));
        }
    }
}
示例#30
0
void WebInterface::action(const QVariantMap &actionData)
{
    qDebug()<<actionData.value("action").toString();
    QString action = actionData.value("action").toString();
    QVariant data = actionData.value("data");
    qDebug()<<"Traitement action";
    if(data.isNull()){
        this->metaObject()->invokeMethod(this,action.toUtf8().data());
    }else{
        this->metaObject()->invokeMethod(this,action.toUtf8().data(),QGenericArgument("QVariant",data.data()));
    }
}