Wednesday, January 25, 2012

How to manage dynamically changing GUI in Qt?

Few days back I was developing a Qt based GUI, which had multiple widgets e.g. CheckBox, PushButton, TextEdit, Labels,...... but GUI was getting changed on certain conditions and because of that GUI was looking horrible.
Qt has a wonderful feature LayoutManager (automatic adjustment of child widgets which are available in main widget.) which was creating problem for me. I tired a lot but all my solutions was failing on some conditions so finally decided to disable the Layout manager and asked for help in one of the forum but all Qt experts suggested,layout manager is one of the nicest feature in Qt, play with it. So I was looking .........and finally found something which is really cool. So I thought of sharing this to the world.

When ever you are creating some GUI in Qt using Box Layout always add addStretch() as a last Widget into your Main Layout. It will consume the extra spaces getting created due to dynamically change in child widgets of the main widget.

To learn more about Qt Layout Manager you can visit the link: http://developer.qt.nokia.com/doc/qt-4.8/layout.html 

Code should look like below,

{
     QHBoxLayout *MainLayout = new QHBoxLayout();
     MainLayout->addWidget(MyCheckBox);

     if (condition == true)
         MainLayout->addWidget(MyTextEdit);

    MainLayout->addWidget(MyLabel1);
    MainLayout->addWidget(MyLAbel2);
    MainLayout->addStretch(); // you can add stretch factor as a parameter to addStretch function.
    ......
}

Note: Please let me know your feedback to improve my effort.

Thanks......

No comments:

Post a Comment