Qt QHBoxLayout percentage size

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">

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

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

Tags:

C++

Qt

Qt4