Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can get QMetaObject from just class name?

Tags:

c++

qt

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?

like image 386
Sergey Skoblikov Avatar asked Jun 07 '11 00:06

Sergey Skoblikov


2 Answers

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 QMetaObjects 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.

like image 78
Dennis Zickefoose Avatar answered Sep 25 '22 17:09

Dennis Zickefoose


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:

  • QMetaObject::type(const char*)
  • QMetaObject::metaObjectForType(int)
like image 26
humbletim Avatar answered Sep 24 '22 17:09

humbletim