Important: Please read the Qt Code of Conduct -

Qt invoke method with QVariant

  • I have the following function :

    @class TestClass: public QObject
    Q_INVOKABLE QString test() { return QString("test"); }

    And I want to invoke the test method, but get the return type as QVariant, not as QString. So I tried this :

    @TestClass obj;
    QVariant returnedValue;
    bool rslt= QMetaObject::invokeMethod(&obj, "test", Qt::DirectConnection,
    Q_RETURN_ARG(QVariant, returnedValue)
    QString strVar = returnedValue.toString();

    but it doesnot work, invoke returns false;
    If get the return type as QString it works, but unfortunately this will not be usable for me, cause I need to know the return type before calling the function.

    @QString r;
    bool rslt= QMetaObject::invokeMethod(&obj, "test", Qt::DirectConnection,
    Q_RETURN_ARG(QString, r)

  • Lifetime Qt Champion


    AFAIK, you can't call invokeMethod without knowing the signature of the method you are going to invoke.

    Can you describe a bit more your use case ?

  • Hi I found solution, but don't understand how it works, and whether it is ok , maybe you can explain :

    @class TestClass: public QObject
    Q_INVOKABLE MyStruct test() { return MyStruct(5); }
    int ttr=qRegisterMetaType<MyStruct> ();

    TestClass obj;

    int thetype = QMetaType::type("MyStruct");
    void v = NULL;
    QVariant returnedValue (thetype,v);
    data =;

    bool rslt= QMetaObject::invokeMethod(&obj, "test", Qt::DirectConnection,
    QGenericReturnArgument("MyStruct", data )

    bool can = returnedValue.canConvert<MyStruct> ();
    MyStruct structm = returnedValue.value<MyStruct>();@

  • Lifetime Qt Champion

    There's something not clear at all, why doing so ?

    Beware, you are using code that is explicitly discourage.

  • I want to iterate through methods of my class, and call them. The methods all are returning different types. These methods are Get methods that are returning the fields of my class. I am aware that maybe marking my fields with Q_PROPERTY may be more appropriate, but I find that more cumbersome.

    Can you elaborate why the code I posted is discouraged?
    Thank you

  • Lifetime Qt Champion

    The documentation of "QGenericArgument":

    You should still consider the property system, if will allow you to really iterate through the declared getters

Log in to reply