Search code examples
c++qtqgridlayout

Qt QGridLayout setRowStretch not working


I am new to Qt. I am trying to create a window with following layout,

--------------------------
| Button1 | Button2|
|------------------------|
|------- Image--------|
-------------------------

I am able to create this layout using QGridlayout. See the following code,

  QPushButton *button = new QPushButton(this);
  QPushButton *nextButton = new QPushButton(this);
  button->setText("Select new Image");
  nextButton->setText("Next Image >>");
  button->setMinimumSize(100,50);
  nextButton->setMaximumSize(500,50);

  button->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
  nextButton->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);
  this->centralWidget = new QWidget(this);
  this->centralWidget->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
  this->centralWidget->setGeometry(0,0,800,800);
  QPalette Pal(palette());
  Pal.setColor(QPalette::Background, Qt::black);
  this->centralWidget->setAutoFillBackground(true);
  this->centralWidget->setPalette(Pal);

  this->layout = new QGridLayout (centralWidget);
  this->layout->addWidget(button,0,0,1,1);
  this->layout->addWidget(nextButton,0,1,1,1);
  this->layout->addWidget(this->imageLabel,1,0,1,1);
  this->layout->setRowStretch(0,1);
  this->layout->setRowStretch(1,10);

But what I want is the image should occupy more space but image is displayed only is the lower half the window. Please See the image You can see the space between buttons and Image. I want to remove the space.

I tried using setRowStretch but this doesn't help.

PS: I am using eclipse with Qt plugin. Also some choices I have made maybe Poor. I am new to Qt. Thanks a lot


Solution

  • Change

    this->layout->addWidget(this->imageLabel,1,0,1,1);

    to

    this->layout->addWidget(this->imageLabel,1,0,1,2,Qt::AlignCenter);

    The 5th parameter is the column span, this means that the new layout item spans both cells (1,0) and (1,1). Have a look at: addWidget. You also want the image centered, the 6th parameter is an alignment parameter which is 0 by default.

    If you also want to have a bigger Image you should scale it. (I am assuming the rest of your code is correct.)

    The row stretch is working, what it does is that the first row only gets the minimum space it needs and the second row takes all the rest of the space, so your buttons are pushed to the top: your layout