Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find a Qt metaobject instance from a class name?

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.

like image 333
axilmar Avatar asked Mar 23 '10 16:03

axilmar


2 Answers

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;
 }
like image 195
Steffen Avatar answered Oct 14 '22 20:10

Steffen


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 !

like image 45
Juan Gonzalez Burgos Avatar answered Oct 14 '22 21:10

Juan Gonzalez Burgos