When calling QMetaMethod::invoke() on a method that contains default arguments, the invoke fails.
class MyClass : public QObject
{
Q_OBJECT
public:
Q_INVOKABLE MyClass() : QObject(nullptr){}
public slots:
int MyMethod(int a = 0)
{
return a*2;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyClass* object = new MyClass();
QMetaObject *metaObject = object->metaObject();
for(int i=metaObject->methodOffset(); i<metaObject->methodCount(); i++)
{
if(metaObject->method(i).name() == "MyMethod")
{
int returnVal;
//returns false
metaObject->method(i).invoke(object,
Qt::DirectConnection,
Q_RETURN_ARG(int, returnVal));
break;
}
}
return a.exec();
}
If I pass an int as the first argument, then it runs fine. Is there any way to retrieve the default values of the arguments for the method so that way I can pass those instead of passing nothing?
I was about to manually store the defaults within the class for each method, but this is an ugly hack.
Thanks for your time.
If you review the generated .moc you see the following:
As you can see there are 2 methods generated and that can be verified by printing the methods with that name:
Output:
So what sets them apart? The number of parameters, so you must add a filter that is the
parameterCount().Output:
On the other hand if you want to avoid this kind of problems you can use
QMetaObject::invokeMethod()that makes that verification: