Qt alignment in QGridLayout eliminates the resizing of its elements

14.6k views Asked by At

Ok, so basically I have a simple table with a QWidget and two buttons as shown below:

QGridLayout *layout = new QGridLayout;
layout->addWidget(viewcontainer,0,0,1,2);
layout->addWidget(reset,1,0);
layout->addWidget(done,1,1);

This is basically what I want, where "reset" and "done" are buttons. Essentially it's a QWidget, viewcontainer, which resizes as the window size is changed by the user while the buttons' heights remains the same. But, the default for the gridlayout is to align the contents to the left. If I change this with:

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

It does sort of what I want, but the graphicsscene no longer resizes (remains a small constant size). I'd like to retain the resizing while just aligning the widget to the center. Thanks.

2

There are 2 answers

1
Viktor Benei On BEST ANSWER

I think the easiest solution which provides a clean solution is to nest 2 layouts.

Your 'outer' (parent) layout should be a QHBoxLayout and you can add your QGridLayout into it as an 'inner' (child) layout with addLayout().

Based on my experience you should avoid to set Qt::Alignment every time you can. It can really mess up your layout. For simple layouts it can work but for more complex ones you should avoid it. And you never know that you should extend your layout in the future or not so my suggestion is to use nested layouts.

Of course you can create a QWidget for the 'outer' layout and for the 'innser' layout as well but most of the times it should be fine to just nest 2 layouts.

Also you can use QSpacerItem to fine-tune your layout.

4
Jeremy Friesner On

Have a look at this example code, I think it does what you want:

#include <QApplication>
#include <QPushButton>
#include <QGraphicsView>
#include <QGridLayout>
#include <QPalette>

class MyWidget : public QWidget
{
public:
   MyWidget()
   {
       QGridLayout * layout = new QGridLayout(this);

       QGraphicsView * gv = new QGraphicsView;
       layout->addWidget(gv, 0,0, 1,2);
       layout->setRowStretch(0, 1);  // make the top row get more space than the second row

       layout->addWidget(new QPushButton("reset"), 1,0);
       layout->addWidget(new QPushButton("done"),  1,1);
   }
};

int main(int argc, char ** argv)
{
   QApplication app(argc, argv);

   MyWidget w;
   w.show();
   return app.exec();
}