How to find an instance of a Qt meta object from a class name?

Is there a way to find an instance of a QMetaObject class given the name of the class? what I like to do is load objects from disk, but for this I need a way to get an instance of QMetaObject using the class name to use the QMetaObject to create the instance.

+6
reflection qt classname metadata qmetaobject
source share
5 answers

You must do this with QMetaType . You may need Q_DECLARE_META_TYPE() and / or qRegisterMetaType() so that your types are known. Then it should work something like in this example, using the link:

  int id = QMetaType::type("MyClass"); if (id == 0) { void *myClassPtr = QMetaType::construct(id); ... QMetaType::destroy(id, myClassPtr); myClassPtr = 0; } 
+1
source share

Recently, I have encountered the same problem. I need a meta object without having to instantiate the class itself. Best of all, I could create a global / static function that retrieves qmetaobject with the class name. I achieved this 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 anyone has a better option, please share!

+1
source share

You can store the instances of MetaClass that you need in Hash or Map, and then retrieve them through any name that you stored them in

0
source share

In your case, a suitable solution might be to use the Qt plugin mechanism. It offers functionality to easily load a shared / dynamic library and check if it contains an implementation of any desired interface, if so, create an instance. Details can be found here: How to create Qt plugins

0
source share

You can also take a look at the function: QMetaType::metaObjectForType , which

returns QMetaType :: metaObject for type

Refresh . This is my code, it creates a class by the name of the class. (Note that the class must be registered with qRegisterMetaType (or is a QObject base)

 int typeId = QMetaType::type("MyClassName"); const QMetaObject *metaObject = QMetaType::metaObjectForType(typeId); QObject *o = metaObject->newInstance(); MyClassName *myObj = qobject_cast<MyClassName*>(o); 

Update 2: I forgot to say. The constructor of the Yout class should be marked as Q_INVOKABLE

-one
source share

All Articles