3

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
user3731622
  • 4,844
  • 8
  • 45
  • 84

1 Answers1

6

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)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • Thanks. I actually found this method too. However, for completeness, do you know of another way to achieve the desired effect? – user3731622 Nov 13 '17 at 22:14
  • 1
    @user3731622. I added an alternative solution – ekhumoro Nov 13 '17 at 23:07
  • Both `addStretch` and `setAlighment` will put two layouts right next to each other. May I know if there is a way to set custom spacing? Thank you. – Zhuokai Zhao Feb 17 '22 at 18:04
  • 3
    @ZhuokaiZhao Use `layout.setSpacing(10)` ([docs](https://doc.qt.io/qt-5/qboxlayout.html#setSpacing)), or add a fixed-width [spacer-item](https://doc.qt.io/qt-5/qspaceritem.html). – ekhumoro Feb 17 '22 at 18:10