首页 > 解决方案 > 如何限制 QLayout 增长?

问题描述

我有一个带有 QHBoxLayout 的 QWidget(窗口),其中包含两个 QPushButton。如果我使窗口更大(非常宽),会发生两件事:

  1. 按钮增长到最大宽度
  2. 按钮之间和周围的空间也增加了。

但我需要另一种行为:

  1. 小部件可以像往常一样增长和缩小
  2. 按钮之间和周围的空间不应该增加(它必须是恒定的)。
  3. 当按钮达到最大宽度时,必须限制小部件的进一步增长

如何达到上述行为?

升级版:

我建议以下代码:

int main(int argc, char* argv[])
{
    QApplication app(argc, argv);

    QWidget wgt;

    QPushButton* button1 = new QPushButton("Button1");
    QPushButton* button2 = new QPushButton("Button2");

    button1->setMinimumSize(150, 100);
    button1->setMaximumSize(250, 100);
    button2->setMinimumSize(150, 100);
    button2->setMaximumSize(250, 100);

    QHBoxLayout* pLayout = new QHBoxLayout(&wgt);
    pLayout->addWidget(button1);
    pLayout->addWidget(button2);

    wgt.setLayout(pLayout);

    wgt.setGeometry(400, 400, 800, 300);
    wgt.show();

    return app.exec();
}

我需要将布局从最小值限制到最大值(不能小于最小值并且不能大于最大值)+而不拉伸按钮之间和周围的空间(它必须具有固定大小)。

标签: c++qtlayoutqt5

解决方案


原因

调整窗口大小时,某些东西必须占用可用空间。由于按钮本身的大小受到限制,因此它们之间的空间会增加。

解决方案

我建议您添加一个不可见的小部件作为占位符。然后相应地调整布局的间距。

例子

这是我为您准备的示例,说明如何更改代码以达到预期的效果:

QHBoxLayout* pLayout = new QHBoxLayout(&wgt);
pLayout->addWidget(button1);
pLayout->addSpacing(6);
pLayout->addWidget(button2);
pLayout->addWidget(new QWidget());
pLayout->setSpacing(0);

替代解决方案

为了限制小部件的大小,请使用QWidget::setMinimumSizeQWidget::setMaximumSize

wgt.setMinimumSize(button1->minimumWidth()
                   + button2->minimumWidth()
                   + pLayout->contentsMargins().left()
                   + pLayout->contentsMargins().right()
                   + pLayout->spacing(),
                   button1->minimumHeight()
                   + pLayout->contentsMargins().top()
                   + pLayout->contentsMargins().bottom()
                   + pLayout->spacing());
wgt.setMaximumSize(button1->maximumWidth()
                   + button2->maximumWidth()
                   + pLayout->contentsMargins().left()
                   + pLayout->contentsMargins().right()
                   + pLayout->spacing(),
                   button1->maximumHeight()
                   + pLayout->contentsMargins().top()
                   + pLayout->contentsMargins().bottom()
                   + pLayout->spacing());

如果您事先知道确切的尺寸,这可以简化为:

wgt.setMinimumWidth(324);
wgt.setMaximumWidth(524);
wgt.setFixedHeight(118);

推荐阅读