PyQt5。如何在QHBoxLayout中将按钮居中?

用户名

我希望按钮保持尽可能的小,并聚集到HBox的中心,而不是向右拖动。

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_()
萨博特

您可以使用setAlignment()布局上方法来调整位于父QFrame中心的按钮:

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

如果要使用该.addStretch()函数来填充空间,还可以再次使用它(在内部for循环之后),以在按钮之后也拉伸该空间。左侧的单个拉伸将扩展并向右推动按钮:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章