My Qt5/C program creates a method name (string) on the fly and then if the method is invokable will call it (using invokemethod). And if not invokable/does not exist, then it will no attempt to invoke it. My methods would be defined like this:
Q_INVOKABLE void m1();
void m2();
Q_INVOKABLE void m3();
So m1 and m3 would be directly invokable using "invokemethod". But m2 would not. Since my code will determine on the fly which method to invoke (creating a string with the method name), I need to test if a method is invokable at runtime. How can I do that? I want something like:
bool invokable = QMetaObject::isInvokable(classptr,"m2");
would return false,
bool invokable = QMetaObject::isInvokable(classptr,"m1");
would return true,
bool invokable = QMetaObject::isInvokable(classptr,"nosuchmethod");
would return false. I found a method called:
int QMetaObject::indexOfMethod(const char *method) const
But it doesn't seem to care about the class, just the method name. How can that be usefull, some class A might have an "M1" defined will class B might not have an "M1" method defined.
CodePudding user response:
AFAIK, there is no such function available but you can easily write your own by taking advantage of QMetaObject::indexOfMethod()
(as proposed by @Igor Tandetnik).
It returns -1
if the method is not found (it returns its index otherwise).
Something like:
bool isInvokable(QObject * obj, const char * method)
{
return obj->metaObject()->indexOfMethod(method) != -1;
}