Sergey Skoblikov
Sergey Skoblikov

Reputation: 5900

How I can get QMetaObject from just class name?

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?

Upvotes: 6

Views: 3798

Answers (2)

humbletim
humbletim

Reputation: 1158

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:

Upvotes: 2

Dennis Zickefoose
Dennis Zickefoose

Reputation: 10979

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.

Upvotes: 4

Related Questions