Qt Forum

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Unsolved

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

    General and Desktop
    4
    5
    10070
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • C
      Charles.qt last edited by

      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.

      1 Reply Last reply Reply Quote 0
      • G
        giesbert last edited by

        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]

        Nokia Certified Qt Specialist.
        Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

        1 Reply Last reply Reply Quote 0
        • C
          Charles.qt last edited by

          Thankyou Gerolf..

          1 Reply Last reply Reply Quote 0
          • A
            Anticross last edited by

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

            1 Reply Last reply Reply Quote 0
            • Jeroentjehome
              Jeroentjehome last edited by

              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??

              Greetz, Jeroen

              1 Reply Last reply Reply Quote 0
              • First post
                Last post