Adrian Maire
Adrian Maire

Reputation: 14835

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?

Upvotes: 1

Views: 3424

Answers (2)

Adrian Maire
Adrian Maire

Reputation: 14835

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.

Upvotes: 0

Amartel
Amartel

Reputation: 4286

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.

Upvotes: 1

Related Questions