python - PyQt5。如何在 QHBoxLayout 中居中按钮?

标签 python pyqt5

我希望按钮保持尽可能小,并聚集到 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 循环之后)来拉伸(stretch)按钮后面的空间。左侧的单个拉伸(stretch)将展开并将按钮推到右侧:

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

关于python - PyQt5。如何在 QHBoxLayout 中居中按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49267604/

相关文章:

python - 神经网络似乎无法学习简单的关系TensorFlow

python - 在Linux上安装PyQt5 5.14.1

python - PyQt5如何将QLabel更新为动画

python - 多重继承元类冲突

python - 为什么使用 PyQt5 的 Python 在创建大量 QPushButton 时速度很慢?

python - 从字符串中提取数字的最 Pythonic 方法

python - 如何使用Python从Json文件的嵌套列表中提取对象?

python - PySide2 相当于 PyQt5 的 loadUiType(),可在 UI 设计中动态混合

python - 如何在matplotlib中调整暂停动画的坐标范围?

python - 如何通过gmail api获取内容['payload' ] ['body' ] ['data' ] first mail