Reputation: 65
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
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