28
votes

How can I maintain an aspect ratio between two QHBoxLayouts?

For instance I want a QHBoxLayout to be one third of the entire window width and the other to be two thirds of the entire window width: enter image description here

How can I achieve this? I tried messing with the size hints of the controls in them but that didn't work out

4

4 Answers

36
votes

void QSizePolicy::setHorizontalStretch(uchar stretchFactor)

Example:

QHBoxLayout* layout = new QHBoxLayout(form);

QWidget* left = new QWidget(form);
QSizePolicy spLeft(QSizePolicy::Preferred, QSizePolicy::Preferred);
spLeft.setHorizontalStretch(1);
left->setSizePolicy(spLeft);
layout->addWidget(left);

QWidget* right = new QWidget(form);
QSizePolicy spRight(QSizePolicy::Preferred, QSizePolicy::Preferred);
spRight.setHorizontalStretch(2);
right->setSizePolicy(spRight);
layout->addWidget(right);
11
votes

The answer of york.beta is working, but I prefer much less code.

At least the sizePolicy is by default Prefered/Prefered.

The default policy is Preferred/Preferred, which means that the widget can be freely resized, but prefers to be the size sizeHint() returns.

You can simply use the second parameter of addWidget to stretch the widgets.

QHBoxLayout *layout = new QHBoxLayout( this );
layout->setContentsMargins( 0, 0, 0, 0 );
layout->setSpacing( 0 );

QPushButton *left = new QPushButton( "133px", this );
left->setStyleSheet( "QPushButton{border: 1px solid red;}" );
QPushButton *right = new QPushButton( "267px", this );
right->setStyleSheet( "QPushButton{border: 1px solid blue;}" );

layout->addWidget( left, 33 );
layout->addWidget( right, 66 );

this->setLayout( layout );
this->setFixedWidth( 400 );

enter image description here

See http://doc.qt.io/qt-5/qboxlayout.html#addWidget

and http://doc.qt.io/qt-5/qwidget.html#sizePolicy-prop

3
votes

You can also use the layoutStretch property:

https://doc.qt.io/qt-5/layout.html#stretch-factors

In your case it'd be

<layout class="QHBoxLayout" name="horizontalLayout" stretch="1,2">
1
votes

You can edit the sizePolicy for the widgets and set a higher horizontalStretch for the widget in the right.