Solved Check if method existed in subclassed QObject. How?
-
Hello all!
Is there any option to determine object method existance in class that subclassing QObject?
Need something like this:SomeObject* oObject = new SomeObject(); if (oObject has method) { ... } else { ... }
-
@bogong there is the QMetaObject of your QObject based class, that has for example
https://doc.qt.io/qt-6/qmetaobject.html#indexOfMethodis that what you're looking for ?
-
@bogong said in Check if method existed in subclassed QObject. How?:
Is there any option to determine object method existance in class that subclassing QObject?
This sounds like weird design. Aren't there any other options to do want you want to achieve? Like checking what (sub-)class your current object actually is and then handle it?!
-
@bogong said in Check if method existed in subclassed QObject. How?:
if (oObject has method) {
Change over to Python instead of C++ ;-)
And note that with C++ you won't be able to call it even if it does
SomeObject* oObject = new SomeObject(); if (oObject has method) { oObject call method
C++ can only call methods known at compile-time. And either
SomeObject
does or doesn't have a given method. -
@JonB Since we're talking about QObjects there is runtime reflection, so you can do:
int idx = object->metaObject()->indexOfMethod("someMethod()"); if (idx >= 0) { QMetaMethod method = object->metaObject()->method(idx); method.invoke(object); }
but I agree that it smells like bad design. That's something you should probably handle with templates e.g. CRTP or dynamic dispatch. Using runtime reflection in C++ is usually a sign of things going wrong.
-
@Chris-Kawa
I know. But I was trying to avoid this/keep it simple for OP. Or change to Python where this is fine :) The OP may genuinely be in a case where he is looking for reflection, or he may not be....Certainly the example of
SomeObject* oObject = new SomeObject();
is not the usual case where you would be looking for reflection. I assume that would be more likely where you don't know exactly what the object is which is handed to you. It might become clearer what the OP has in mind if he comments. -
@J-Hilk Thx that's what been seeking. Issue closed