pythonpyqt5qvboxlayout

How to add custom space between widgets in QVboxLayout?


I am trying to move last 2 widgets (btn1, btn2) apart from the rest of widgets in vbox layout. I use insertSpacing with index of the widget below but it moves both widgets down by 500. How can I move down btn1 by 20 and btn2 by 500 ?

filter_layout = QVBoxLayout()

data_filters = [label1, combo1, label2, combo2, label3, combo3, label4, combo4, label5, combo5, btn1, btn2]
[filter_layout.addWidget(wg) for wg in data_filters]

filter_layout.insertSpacing(10, 20)
filter_layout.insertSpacing(11, 500)

filter_layout.addStretch()

Solution

  • Qt layout managers use abstract items called QLayoutItem in order to represent an element that is managed by a layout.

    Those items normally contain widgets, but they can also contain other layouts or spacers (QSpacerItem).

    What happens in your case is that when you call the following line:

    filter_layout.insertSpacing(10, 20)
    

    you're inserting a spacer item between element at index 10 and 11, so the next insertion is actually just after that spacer you added, because it's like you added an empty widget between the last two elements.
    As you probably had already figured out, knowing all this it's simple to find the solution: you either set the next spacer counting the index insertion, or you invert the insertion order.

    filter_layout.insertSpacing(10, 20)
    filter_layout.insertSpacing(12, 500)
    
    # or, alternatively:
    filter_layout.insertSpacing(11, 500)
    filter_layout.insertSpacing(10, 20)