【问题标题】:How to restrict QLayout from growing?如何限制 QLayout 增长?
【发布时间】:2019-03-06 23:08:13
【问题描述】:

我有一个带有 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++ qt layout qt5


    【解决方案1】:

    原因

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

    解决方案

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

    示例

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

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

    【讨论】:

    • 谢谢!但是,是否有任何方法可以将小部件宽度限制为 button1 最大宽度 + 按钮 2 最大宽度 + 间距 6 ?就我而言,我需要确切的尺寸限制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-04
    • 2016-12-28
    • 2018-08-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 2020-03-23
    相关资源
    最近更新 更多