pythonlayoutpyqtspacingqvboxlayout

How to adjust space between layouts in a QVBoxLayout


I've seen how to adjust the space between widgets in a layout: Space between widgets in QVBoxLayout. However, I want to know how to adjust space between layouts added to a layout.

For example:

layout = QVBoxLayout()
h1_layout = QHBoxLayout()
h2_layout = QHBoxLayout()
layout.addLayout(h1_layout)
layout.addLayout(h2_layout)

I would like the contents of h1_layout and h2_layout to be placed close to each other rather than spaced across the vertical layout.


Solution

  • I assume you want the contents of the two horizontal layouts to be aligned at the top of the vertical layout, and not stretched out to fill the entire space available. If so, you can achieve this by adding an expanding spacer to the bottom of the vertical layout:

    layout = QVBoxLayout()
    h1_layout = QHBoxLayout()
    h2_layout = QHBoxLayout()
    layout.addLayout(h1_layout)
    layout.addLayout(h2_layout)
    # add expanding spacer
    layout.addStretch()
    

    Another way to achieve a similar effect, is to set the alignment of the parent layout:

    layout.setAlignment(QtCore.Qt.AlignTop)