创建具有固定高度的Qt布局

时间:2012-08-17 14:35:29

标签: qt layout

我想创建一个Qt窗口,其中包含两个布局,一个固定高度,包含顶部的按钮列表,另一个填充重新生成空间,其布局使窗口小部件垂直和水平居中,如下图所示。

Example Qt layout

我应该如何布置我的布局/小部件。我尝试了一些嵌套水平和垂直布局的选项无济于事

1 个答案:

答案 0 :(得分:19)

尝试使用QHBoxLayout制作粉红色的盒子QWidget(而不仅仅是制作布局)。原因是QLayouts不提供固定大小的功能,但QWidgets可以。

// 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);

如果你真的想要有两个独立的布局 - 一个用于粉色框,一个用于蓝色框 - 除了你将蓝色框放入自己的QVBoxLayout之外,这个想法基本相同,然后使用:

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