c++ - 如何限制 QLayout 增长?
问题描述
我有一个带有 QHBoxLayout 的 QWidget(窗口),其中包含两个 QPushButton。如果我使窗口更大(非常宽),会发生两件事:
- 按钮增长到最大宽度
- 按钮之间和周围的空间也增加了。
但我需要另一种行为:
- 小部件可以像往常一样增长和缩小
- 按钮之间和周围的空间不应该增加(它必须是恒定的)。
- 当按钮达到最大宽度时,必须限制小部件的进一步增长
如何达到上述行为?
升级版:
我建议以下代码:
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();
}
我需要将布局从最小值限制到最大值(不能小于最小值并且不能大于最大值)+而不拉伸按钮之间和周围的空间(它必须具有固定大小)。
解决方案
原因
调整窗口大小时,某些东西必须占用可用空间。由于按钮本身的大小受到限制,因此它们之间的空间会增加。
解决方案
我建议您添加一个不可见的小部件作为占位符。然后相应地调整布局的间距。
例子
这是我为您准备的示例,说明如何更改代码以达到预期的效果:
QHBoxLayout* pLayout = new QHBoxLayout(&wgt);
pLayout->addWidget(button1);
pLayout->addSpacing(6);
pLayout->addWidget(button2);
pLayout->addWidget(new QWidget());
pLayout->setSpacing(0);
替代解决方案
为了限制小部件的大小,请使用QWidget::setMinimumSize
和QWidget::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);
推荐阅读
- java - 为什么我在启动简单代码 (JavaFX) 时遇到问题?
- python - 在pyshark中计算TCP重传
- javascript - 从函数的结果中提取 TImestamp
- node.js - Node JS,快速会话,从客户端浏览器中删除 cookie
- c++ - 无法使用 std::exception 捕获异常
- python - 无法匹配python中的正则表达式模式
- ansible - 有没有办法确定哪些 Ansible 剧本或任务实际上正在使用收集到的事实?
- javascript - 如何检查对象的属性是getter还是setter?
- javascript - 显示微调器 onclick
- django - AttributeError:“元组”对象没有属性“stripe_customer_id”