I need to get QMetaObject for dynamic creation of object instances. If I khow the object then QObject::metaObject() is what I need. If I know the class then I can use QObject::staticMetaObject variable. But what should I use if I know only class name as a string value?
You ask for a QMetaObject
, but say it is for creation purposes. If that's all you have to do, QMetaType may well be what you need. You have to register your types with it, but I'm pretty sure QT doesn't have a master list of QMetaObject
s just floating around by default, so such registration will be necessary no matter what you do.
QMetaType::Type id = QMetaType::type("ClassName");
if(id == 0)
throw something_or_whatever;
ClassName* p = (ClassName*)QMetaType::construct(id);
//act on p
QMetaType::destroy(id, p);
Cursory glance at the documentation isn't clear on how the memory for p
is allocated, but I assume destroy
takes care of that? Use at your own risk.
As of Qt5 getting the QMetaObject from just the class name became straightforward:
int typeId = QMetaType::type("MyClassName");
const QMetaObject *metaObject = QMetaType::metaObjectForType(typeId);
if (metaObject) {
// ...
}
See also these Qt5 API docs:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With