Qt alignment in QGridLayout eliminates resizing of its elements

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 this is a QWidget, a viewcontainer that changes when the user resizes the window, while the height of the buttons remains unchanged. But by default for gridlayout you need to align the content to the left. If I changed this with:

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

It does what I want, but the graphic is no longer changing (it remains a small constant size). I would like to save the resizing just by tying the widget to the center. Thanks.

+4
source share
2 answers

I think the simplest solution that provides a clean solution is to place two layouts.

Your appearance (parent) should be a QHBoxLayout , and you can add your QGridLayout to it as an β€œinternal” (child) with addLayout () .

Based on my experience, you should avoid installing Qt :: Alignment whenever you can. This can ruin your layout. For simple layouts, it may work, but for more complex ones, you should avoid it. And you never know that you should expand your layout in the future or not, so I suggest using nested layouts.

Of course, you can create a QWidget for the "external" layout and for the "innser" layout, but in most cases this should be good to just nest 2 layouts.

You can also use QSpacerItem to fine tune the layout.

+4
source

Take a look at this sample 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(); } 
+2
source

Source: https://habr.com/ru/post/1414814/


All Articles