user1159290
user1159290

Reputation: 1003

Qt widget size recalculation at runtime

I have a problem with size calculation in Qt when adding new widgets at run time. I have tried to illustrate the problem with the pruned program down there. Hopefully, it shows the same problem than my other (more complex) program:

When a widget has been shown, using:

w->show();

...and some new widgets are added to it later on (possibly w has a layout), what should I do to redisplay w and its parents so that the size of the newly added child widgets is taken into account? The behaviour I want is that the size recalculation propagates upward to the nearest scrolled object (or the main window if there is no scrolled objects)

In the example below, I create a little widget structure: if the call to show() (commented SHOW1) is removed, then the whole widget structure is defined before the first call to show() and everything works. BUT: if I do call show() (at SHOW1), then the last show does not display the right things: the frame is still too small

 #include <QApplication>
 #include <QtCore>
 #include <QMainWindow>
 #include <QTabWidget>
 #include <QWidget>
 #include <QGroupBox>
 #include <QVBoxLayout>
 #include <QLabel>

 #include <stdlib.h>


 int main(int argc, char *argv[])
 {
    QApplication app(argc, argv);
    QMainWindow* main_window = new(QMainWindow);
    main_window->setObjectName("main_window");
    main_window->resize(800, 600);
    main_window->setWindowTitle("Hello");

    QTabWidget* node_tab_widget = new QTabWidget(main_window);
    node_tab_widget->setObjectName(QString::fromUtf8("tab_widget"));

    QWidget* w= new QWidget(node_tab_widget);
    node_tab_widget->addTab(w, "TAB");

    QGroupBox* group_widget = new QGroupBox("GROUPNAME", w);
    QVBoxLayout*  group_layout = new QVBoxLayout;
    group_widget->setLayout(group_layout);
    group_layout->addWidget((QLabel*)new QLabel(">>>>>>>>>>>>>>>>>>>>>>>>>here1"));

    main_window->show();  // SHOW1: If this one is commented, then OK!

    group_layout->addWidget((QLabel*)new QLabel("here2"));
    group_layout->addWidget((QLabel*)new QLabel("here2"));
    group_layout->addWidget((QLabel*)new QLabel("here2"));
    group_layout->addWidget((QLabel*)new QLabel("here2"));

    main_window->setCentralWidget(node_tab_widget);

    // main_window->update();
    // main_window->hide();

    main_window->show(); // How to I get that to recaclulate the size of its contents?
    return app.exec();
 }

Upvotes: 2

Views: 2865

Answers (1)

Paolo Capriotti
Paolo Capriotti

Reputation: 4072

Your w widget doesn't have a layout. Try adding the following lines after creating group_widget:

QVBoxLayout *wlayout = new QVBoxLayout(w);
wlayout->addWidget(group_widget);
wlayout->addStretch();

You can get rid of addStretch if you actually want w to span the entire parent.

Upvotes: 2

Related Questions