Search code examples
c++qtuser-interfaceqtwidgets

Qt How to add custom widgets to a vertical layout to occupy the least amount of vertical space (no space between custom widgets)


I've created a custom widget containing a few widgets in a horizontal layout:

custom widget

enter image description here

And the goal is to display several of these in a list so I've added them dynamically to a parent vertical layout. The problem I'm having is that there's too much space in between my custom widgets when they're added to the vertical layout: too much space

I want them to be tightly packed so that there's only a small space in between. I've added a spacer at the bottom and played around with the size policies etc but to no avail. Below is the code to add the widgets. Any and all help appreciated.

    // Draw the nodes area
QVBoxLayout* nodeVLayout = new QVBoxLayout;
NodeWidget* node1 = new NodeWidget;
NodeWidget* node2 = new NodeWidget;
QSpacerItem* spacer = new QSpacerItem(1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding);

nodeVLayout->setSpacing(1);
nodeVLayout->addWidget(node1);
nodeVLayout->addWidget(node2);
nodeVLayout->addSpacerItem(spacer);

ui->scrNodes->setLayout(nodeVLayout);

Solution

  • In the layout options check that the margins and spacing are set appropriately.

    By default the margins on the top and bottom were set to 9 pixels which was causing the problem.