19

I want to create a Qt window that contains two layouts, one fixed height that contains a list of buttons at the top and one that fills the remaning space with a layout that centers a widget vertically and horizontally as per the image below.

Example Qt layout

How should i be laying out my layouts/widgets. Ive tried a few options with nested horizontal and vertical layouts to no avail

1 Answer 1

30

Try making the pink box a QWidget with a QHBoxLayout (rather than just making it a layout). The reason is that QLayouts don't provide functionality to make fixed sizes, but QWidgets do.

// first create the four widgets at the top left,
// and use QWidget::setFixedWidth() on each of them.

// then set up the top widget (composed of the four smaller widgets):
QWidget *topWidget = new QWidget;
QHBoxLayout *topWidgetLayout = new QHBoxLayout(topWidget);
topWidgetLayout->addWidget(widget1);
topWidgetLayout->addWidget(widget2);
topWidgetLayout->addWidget(widget3);
topWidgetLayout->addWidget(widget4);
topWidgetLayout->addStretch(1); // add the stretch
topWidget->setFixedHeight(50);

// now put the bottom (centered) widget into its own QHBoxLayout
QHBoxLayout *hLayout = new QHBoxLayout;
hLayout->addStretch(1);
hLayout->addWidget(bottomWidget);
hLayout->addStretch(1);
bottomWidget->setFixedSize(QSize(50, 50));

// now use a QVBoxLayout to lay everything out
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(topWidget);
mainLayout->addStretch(1);
mainLayout->addLayout(hLayout);
mainLayout->addStretch(1);

If you really want to have two separate layouts--one for the pink box and one for the blue box--the idea is basically the same except you'd make the blue box into its own QVBoxLayout, and then use:

mainLayout->addWidget(topWidget);
mainLayout->addLayout(bottomLayout);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.