When generally we need to use QMetaobject class?
-
Another common use case is introspection. QMetaObject allows you to retrieve various information about a class or an object, like its name, base class, methods, signals, slots, properties or enums at runtime. In addition, it allows you to call methods by name (see QMetaObject::invokeMethod()).
Besides that, it is - as Gerolf already mentioned - the glue for Qts signal / slot system and QMLs properties.
-
I find I mostly use it for the QMetaObject::invokeMethod function. It allows you to invoke a slot (ok, a Q_INVOKABLE) in an object just like you would with a signal-slot connection, only you can call it without actually having a signal and without knowing what kind of object it is. You can also get return values that way, and choose the connection type to use. That can be very handy at times.
-
I use QMetaObject extensively to get information about an object's properties in a scheme to load and save objects to an XML structure.
Thanks to that system, I can automatically generate XML key names from the property names, as well as the type.
I can then read the XML, and automatically convert the contained strings to the correct type, and set them as a property.
I the other direction, I read the properties, convert them to a locale-independent string, and write them to the XML.
The scheme took a while to set up, but now adding a new object to the scheme is a breeze, and changes to name or type of an XML parameter happens in exactly one place.
Thanks to QMetaEnum, I can even save enum value names, which makes the XML more user-readable.