How can I find a Qt metaobject instance from a cla

2019-04-08 00:06发布

问题:

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.

回答1:

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;
 }


回答2:

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 !



回答3:

You can store the MetaClass instances you will need in a Hash or Map, and then retrieve them via whatever name you stored them under



回答4:

For your case the appropriate solution can be using Qt plugin mechanism. It offers functionality to easily load shared/dynamic library and check if it contains implementation of some desired interface, if so - create the instance. Details can be found here: How to Create Qt Plugins



回答5:

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

returns QMetaType::metaObject for type

Update: That's my code, it create a class by class name. (Note that the class must be registered with qRegisterMetaType (or is 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 have forgot to say. Yout class's constructor must be marked as Q_INVOKABLE