开发者

How I can get QMetaObject from just class name?

开发者 https://www.devze.com 2023-03-11 08:10 出处:网络
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 the开发者_Go百科n I can use QObject::staticMetaO

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 the开发者_Go百科n 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 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.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号