Search code examples
qtpointerslayoutreferenceoverlapping

Why do the next two code sequences behave differently?


I don't understand why the first code sequence creates a QWidget where the elements overlap, while the second one behaves correctly. The only difference is that in the first one there is a QVBoxLayout pointer, while in the second one it's an object. It's about passing by reference vs passing by pointer? I really don't get the subtle difference.

First one:

QVBoxLayout vbox;
vbox.setSpacing(2);

QPushButton* quitButton = new QPushButton("Qsdfsuit");
QFont fnt = quitButton->font();
fnt.setPointSize(18);
fnt.setBold(true);
fnt.setFamily("Arial");
quitButton->setFont(fnt);

connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));

QLCDNumber* lcd = new QLCDNumber(2);

QSlider* slider = new QSlider(Qt::Horizontal);
slider->setRange(0, 99);
slider->setValue(0);

connect(slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)));

vbox.addWidget(quitButton);
vbox.addWidget(lcd);
vbox.addWidget(slider);

this->setLayout(&vbox);

The second one:

QVBoxLayout* vbox = new QVBoxLayout();
vbox->setSpacing(2);

QPushButton* quitButton = new QPushButton("Qsdfsuit");
QFont fnt = quitButton->font();
fnt.setPointSize(18);
fnt.setBold(true);
fnt.setFamily("Arial");
quitButton->setFont(fnt);

connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));

QLCDNumber* lcd = new QLCDNumber(2);

QSlider* slider = new QSlider(Qt::Horizontal);
slider->setRange(0, 99);
slider->setValue(0);

connect(slider, SIGNAL(valueChanged(int)), lcd, SLOT(display(int)));

vbox->addWidget(quitButton);
vbox->addWidget(lcd);
vbox->addWidget(slider);

this->setLayout(vbox);

Solution

  • In the first segment QVBoxLayout vbox; is created on the stack.
    It is destroyed as soon as the method execution if finished.

    In the second segment QVBoxLayout* box is created in a heap and it's not destroyed until the widget is alive.

    Layouts in Qt do their job when a widget is shown or resized that's why they should exist until a widget exists.

    More information:
    The stack and the heap
    Blocks and local variables