How can i dynamically instantiate a class using the class name?



  • I would like to instantiate a class dynamically,
    In java, Class.forName(String className) is used for instantiate the class dynamically.
    I searched on Google for Qt, something called QMetaObject ,QmetaType,etc is available ,
    using these classses i can instantiate the class dynamically.
    But i am not clear enough, how to implement this?

    Please someone can explain me or give me some examples ,that would be useful for me to understand this concept clearly.



  • Have a look at the "documentation of QMetaObject":http://qt-project.org/doc/qt-4.8/qmetatype.html

    [quote]
    ...
    It associates a type name to a type so that it can be created and destructed dynamically at run-time. Declare new types with Q_DECLARE_METATYPE() to make them available to QVariant and other template-based functions. Call qRegisterMetaType() to make type available to non-template based functions, such as the queued signal and slot connections.

    Any class or struct that has a public default constructor, a public copy constructor, and a public destructor can be registered.

    The following code allocates and destructs an instance of MyClass:

    @
    int id = QMetaType::type("MyClass");
    if (id != 0) {
    void *myClassPtr = QMetaType::construct(id);
    ...
    QMetaType::destroy(id, myClassPtr);
    myClassPtr = 0;
    }
    @
    [/quote]



  • Thankyou Gerolf..



  • What about Qt 5.3 ? It doesn't work there. :(



  • It should work, did you read the updated docs:
    "QMetaType":http://qt-project.org/doc/qt-5/qmetatype.html
    What code does not work for you??


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.