user3529406
user3529406

Reputation: 65

PyQt5. How to center buttons within QHBoxLayout?

I want the buttons to remain as small as possible, and bunch up into the center of the HBox instead of gravitating right.

import sys
from random import randint
from PyQt5.QtWidgets import QApplication, QFrame, QHBoxLayout, QPushButton, QVBoxLayout, QWidget, QLabel

app = QApplication(sys.argv)
Frame = QFrame()

vbox = QVBoxLayout(Frame)
for i1 in range(5):
    hbox = QHBoxLayout()
    hbox.setContentsMargins(0, 0, 0, 0)
    hbox.addStretch()

    for i2 in range(randint(1,10)):
        bb = QPushButton(str(i2))
        hbox.addWidget(bb)
    vbox.addLayout(hbox)

Frame.show()
app.exec_()

Upvotes: 1

Views: 7313

Answers (1)

Lukr
Lukr

Reputation: 794

you can use the setAlignment() method on your layout to adjust the buttons centered in the parent QFrame:

hbox.setAlignment(Qt.AlignCenter)
vbox.setAlignment(Qt.AlignCenter)

If you want to use the .addStretch() function to fill the space before you may also use it again (after the inner for loop) to stretch the space after the buttons as well. A single stretch on the left side will expand and push the buttons to the right:

hbox.addStretch()  # epands and pushes to the right
for i2 in range(randint(1,10)):
    bb = QPushButton(str(i2))
    hbox.addWidget(bb)
hbox.addStretch()  # expands as well and compensates the first

Upvotes: 3

Related Questions