Reputation: 2561
I have a QWidget (window) with QHBoxLayout which contains two QPushButtons. If I make the window bigger (very wide) two things happen:
But I need another behavior:
How to reach the above behavior?
UPD:
I propose the following code:
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();
}
I need that layout should be restricted from min to max (cant be less than min and cant be larger than max) + without stretching the space (it must have fixed size) between and around the buttons.
Upvotes: 1
Views: 366
Reputation: 8399
When the window is resized, something must take the available space up. Since the buttons themselves are restricted in size, the space between them grows.
I would suggest you to add an invisible widget to serve as a placeholder. Then adjust the spacing of the layout accordingly.
Here is an example I have prepared for you of how to change your code in order to achieve the desired effect:
QHBoxLayout* pLayout = new QHBoxLayout(&wgt);
pLayout->addWidget(button1);
pLayout->addSpacing(6);
pLayout->addWidget(button2);
pLayout->addWidget(new QWidget());
pLayout->setSpacing(0);
In order to restrict the widget's size, use QWidget::setMinimumSize
and 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());
If you know the exact dimensions in advance, this could be simplified to:
wgt.setMinimumWidth(324);
wgt.setMaximumWidth(524);
wgt.setFixedHeight(118);
Upvotes: 1