Is there a way to find the QMetaObject instance of a class, given the class name? what I like to do is to load objects from disk, but for this to happen, I need a way to retrieve a QMetaObject instance using the name of a class, in order to use the QMetaObject to create an instance.
You should be able to do this with QMetaType. You might need Q_DECLARE_META_TYPE()
and/or qRegisterMetaType()
to make your types known. Then it should work roughly like in this example from the link:
int id = QMetaType::type("MyClass");
if (id == 0) {
void *myClassPtr = QMetaType::construct(id);
...
QMetaType::destroy(id, myClassPtr);
myClassPtr = 0;
}
I have been facing the same problem recently. I needed the metaobject without having to create an instance of the class itself. Best I could do is to create a global / static function that retrieves the qmetaobject given the class name. I achieved this by using QObject::staticMetaObject.
QMetaObject GetMetaObjectByClassName(QString strClassName)
{
QMetaObject metaObj;
if (strClassName.compare("MyClass1") == 0)
{
metaObj = MyClass1::staticMetaObject;
}
else if (strClassName.compare("MyClass2") == 0)
{
metaObj = MyClass2::staticMetaObject;
}
else if (strClassName.compare("MyClass3") == 0)
{
metaObj = MyClass3::staticMetaObject;
}
else if (strClassName.compare("MyClass4") == 0)
{
metaObj = MyClass4::staticMetaObject;
}
else if (strClassName.compare("MyClass5") == 0)
{
metaObj = MyClass5::staticMetaObject;
}
// and so on, you get the idea ...
return metaObj;
}
See : http://doc.qt.io/qt-5/qobject.html#staticMetaObject-var
If somebody has a better option, please share !
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