繁体   English   中英

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

[英]PyQt5. How to center buttons within 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM