Qt QHBoxLayout percentage size

前端 未结 4 2012
盖世英雄少女心
盖世英雄少女心 2020-12-29 21:58

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 thi

相关标签:
4条回答
  • 2020-12-29 22:26

    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);
    
    0 讨论(0)
  • 2020-12-29 22:31

    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">
    
    0 讨论(0)
  • 2020-12-29 22:44

    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

    0 讨论(0)
  • 2020-12-29 22:49

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

    0 讨论(0)
提交回复
热议问题