user152508
user152508

Reputation: 3131

Qt invoke method with QVariant

I have the following function :

class TestClass: public QObject
{
  Q_OBJECT
public:      
  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)
     );

Upvotes: 2

Views: 1772

Answers (2)

user152508
user152508

Reputation: 3131

this is my working example

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

TestClass obj;    

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

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

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

Upvotes: 0

Archie
Archie

Reputation: 2672

You can inspect method return type via QMetaMethod::returnType(), and then construct the return value receptor using QGenericReturnArgument.

Here is some code for inspiration

Upvotes: 3

Related Questions