Search code examples
c++qtqwidgetqstring

Qt Dynamically create QWidget from QString


I am trying to create a program that reads information from a database, and accordingly set up the layout. Specifically, I want to read two date fields and depending on the difference between the days, create a day(s) number of elements. Have anyone got an idea on how this could be done? I have tried to create an element using the QString->text() property with no success for obvious reasons and I have managed to write a function to create an element, but my problem is that I cannot control the name of the element, making it impossible for me with my rubbish knowledge about c++ to then interact with the given element.

Thank you for your time,

Cheers.


Solution

  • I think a QHash would be the perfect tool for your needs. It allows storing and lookup of pretty much anything through a unique key. That means you can store the widgets with their title as a key and then later retrieve a widget with a certain title from that hash.

    Here is how to define such a hash:

    // .h file
    #include <QtCore/QHash>
    #include <QtGui/QWidget>
    
    class MyWidget : public QWidget
    {
        // ...
    private:
        QHash< QString, QWidget* > m_dynamicWidgetHash;
    };
    

    The Widgets (or any QWidget subclass) can then be stored in the hash like this, assuming the titles will always be unique:

    // .cpp file
    void MyWidget::someMethod()
    {
        QList< QString > widgetTitles = getWidgetTitlesFromSomewhere();
    
        foreach( QString title, widgetTitles )
        {
            SomeWidgetSubclass* widget = new SomeWidgetSubclass( this );
            widget->setTitle( title );
            // Note: This will not work if two widgets can have the same title
            Q_ASSERT( !m_dynamicWidgetHash.contains( title ) );
            m_dynamicWidgetHash.insert( title, widget );
        }
    }
    

    You can then later find your widgets knowing only the name like this:

    // .cpp file
    void MyWidget::someOtherMethod( const QString& title )
    {
        SomeWidgetSubclass* widget = m_dynamicWidgetHash.value( title );
        if( !widget )
        {
            // TODO: Error Handling
            return;
        }
    
        // Do whatever you want with the widget here
    }