QMetaObject and QMetaProperty - why 2 times the same object?
-
Hi,
I would like to read a property from one object. I can do that, but I have to write:
const QMetaObject * metaObj = myObject->metaObject(); and in a loop: QVariant property = metaObj->property(i).read(myObject);
Why I have to add myObject param in
read()
too ?I use myObject here:
const QMetaObject * metaObj =myObject
->metaObject();
and here:
QVariant property = metaObj->property(i).read(myObject
);This looks very bad, that I have to use the same word in two places.
-
QMetaObject is a meta object for a class, not an instance.
myObject->metaObject()
is basically the same asMyObjectClass::staticMetaObject
. It's just a shortcut to look up the class of a given instance.Properties on the other hand have values per object. When you have a meta object , which, again, is a class descriptor and not related to any particular instance of it, you can use it to read a property. The "location" of the property in given class is described in the meta object, but to get a value from a particular instance of that class you need to pass that instance.
So, if you want to avoid using the instance pointer twice you can do it like this:
QVariant property = MyObjectClass::staticMetaObject.property(i).read(myObject);
If you don't know the class of the object you have to use
myObject->metaObject()
so that it gives you the meta object of the right class.