Results 1 to 6 of 6

Thread: How to instantiate a class if I dont know its name?

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Nov 2010
    Location
    Cienfuegos, Cuba
    Posts
    16
    Thanks
    6
    Qt products
    Qt4
    Platforms
    Unix/X11 Windows

    Default How to instantiate a class if I dont know its name?

    Hi:

    The application I'm trying to develop must be extended using plugins. I have a XML file similar to this (I omitted some non important parts):

    <program>
    <component type="plugin1"/>
    <component type="plugin2"/>
    <component type="plugin1"/>
    <component type="plugin3"/>
    </program>

    So, for each <component> element that I read I create a new page on a QStackedWidget containing a custom widget defined by the classes Plugin1, Plugin2 and Plugin3. Is very easy when I know the names of all the plugins because I can do something like:

    Qt Code:
    1. class AbstractPlugin : public QObject{
    2. //...
    3. virtual QWidget* widget() = 0;
    4. };
    5.  
    6. //all these classes implements "widget()"
    7. class Plugin1 : public AbstractPlugin{/*...*/};
    8. class Plugin2 : public AbstractPlugin{/*...*/};
    9. class Plugin3 : public AbstractPlugin{/*...*/};
    10.  
    11. QList<AbstractPlugin* > components
    12. QString type //this value was readed from the XML in some moment
    13.  
    14. if(type == "Plugin1")
    15. components.append(new Plugin1());
    16. else if(type == "Plugin2")
    17. components.append(new Plugin2());
    18. else if(type == "Plugin3")
    19. components.append(new Plugin3());
    20.  
    21. foreach(AbstractPlugin* c, components){
    22. stackedWidget->addPage(c->widget());
    23. }
    To copy to clipboard, switch view to plain text mode 

    But, if I dont know the names of all the plugins because I don't write each one, how can I specify the correct constructor to call?
    Last edited by anoraxis; 12th March 2012 at 17:03.

Similar Threads

  1. Replies: 18
    Last Post: 11th March 2011, 13:21
  2. Replies: 7
    Last Post: 1st March 2011, 23:02
  3. Instantiate objects only having their class name
    By victor.fernandez in forum Qt Programming
    Replies: 1
    Last Post: 30th June 2009, 16:22
  4. wanted to re-instantiate two classes from a class
    By salmanmanekia in forum General Programming
    Replies: 2
    Last Post: 22nd August 2008, 08:59
  5. Replies: 2
    Last Post: 25th August 2006, 11:35

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.