问题
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:
How can I achieve this? I tried messing with the size hints of the controls in them but that didn't work out
回答1:
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);
回答2:
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 );
See http://doc.qt.io/qt-5/qboxlayout.html#addWidget
and http://doc.qt.io/qt-5/qwidget.html#sizePolicy-prop
回答3:
You can edit the sizePolicy for the widgets and set a higher horizontalStretch for the widget in the right.
回答4:
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">
来源:https://stackoverflow.com/questions/14561516/qt-qhboxlayout-percentage-size