QGridLayout Spacing issue



  • Hello,

    please have a look at the following code:

    #include "MainWindow.h"
    #include "ui_MainWindow.h"
    #include <QGridLayout>
    #include <QGroupBox>
    #include <QLineEdit>
    
    MainWindow::MainWindow(QWidget *parent) :
       QMainWindow(parent),
       ui(new Ui::MainWindow)
    {
       ui->setupUi(this);
    
       QGridLayout* lay= new QGridLayout();
       lay->setSpacing(10);
       lay->setMargin(10);
       lay->setAlignment(Qt::AlignTop);
       lay->setOriginCorner(Qt::TopLeftCorner);
    
       QLineEdit* edit1 = new QLineEdit("edit1");
       edit1->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed );
    
       QLineEdit* edit2 = new QLineEdit("edit2");
       edit2->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::MinimumExpanding );
       edit2->setMaximumSize(400,300);
    
       QGroupBox* group = new QGroupBox("Group");
       group->setSizePolicy( QSizePolicy::Preferred, QSizePolicy::Fixed );
    
       QGridLayout* boxLay = new QGridLayout(group);
       boxLay->setSpacing(10);
       boxLay->setMargin(10);
    
       QLineEdit* edit3 = new QLineEdit("edit3");
       edit3->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed );
    
       boxLay->addWidget(edit3, 0,0);
    
       QLineEdit* edit4 = new QLineEdit("edit4");
       edit4->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed );
    
       lay->addWidget(edit1,0,0);
       lay->addWidget(edit2,1,0);
       lay->addWidget(group,3,0,2,1);
       lay->addWidget(edit4,5,0);
    
       this->centralWidget()->setLayout(lay);
    }
    

    If you expand the window, edit2 grows to its maximumSize.
    After the maximumSize is reached, a space between the other widgets will inserted.

    What can I do to prevent this behaviour and create the space at the end?


  • Moderators

    @markcurl
    since you have set the size-policy of all widgets accordingly.
    With a QVBoxLayout you could simply add a stretch to the layout after all widgets.

    Alternatively you can try adding a QSpacerItem at the end of the QGridLayout:

    QSpacerItem* vSpacerItem = new QSpacerItem( 0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding );
    
    lay->addWidget(edit1,0,0);
    lay->addWidget(edit2,1,0);
    lay->addWidget(group,3,0,2,1);
    lay->addWidget(edit4,5,0);
    lay->addItem(vSpacerItem, 5, 0);
    

    I haven't tested it, but thats basically what QBoxLayout does when adding a stretch.



  • @raven-worx

    Thanks, works fine :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.