简体   繁体   中英

In QT, How to define the geometry for the Layout in a custom Widget

In a custom QWidget (say MyWidget ) I include a layout to manage children widgets:

MyWidget window;
QPushButton button;
QVBoxLayout layout(window);
layout.addWidget(button);
window.show();

I would like the layout to be in a specific position and size, by default, QWidget set it to the whole geometry.

How can I set the geometry the layout will consider for managing his space?

As an indirect question: Which function the layout use to set children geometries?

QPushButton *button = new QPushButton;
verticalLayout->addSpacing(300);
verticalLayout->addWidget(button);
button->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
button->setMinimumSize(500, 200);
button->setMaximumSize(500, 200);

If you need both vertical and horizontal spacing - use QGridLayout .

The QLayout use as margins the summary of both:

  • The parent widget contents margins.
  • The layout contents margins.

The solution is to set the contents margins to the required value in the custom widget constructor. And when creating the layout, to set his contents margins to 0.

this->setContentsMargins(left, top, right, bottom);
// ...
layout->setContentsMargins(0,0,0,0);

The Layout setGeometry is called by QWidget resize event, and set children widgets size according with it. As all functions are not virtual, it is not possible (or at least difficult) to modify in this behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM