我在水平居中的主窗口上有一个QVBoxLayout
,并在布局中添加了一个具有AlignCenter
对齐方式和自定义QFrame
的标签。当标签的尺寸小于自定义框架(英文框)时,一切按预期进行:
但是,当标签的尺寸大于自定义框架时,自定义框架将向左移动:
为什么会这样,我该如何解决?
这里是MCVE:
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication, QFrame, QLabel, QSizePolicy, \
QStackedLayout, QVBoxLayout, QWidget
app = QApplication([])
main_window = QWidget()
main_window.setMinimumSize(1280, 720)
layout = QVBoxLayout()
layout.setAlignment(Qt.AlignHCenter | Qt.AlignTop)
main_window.setLayout(layout)
label = QLabel()
label.setText("Select Language")
label.setAlignment(Qt.AlignCenter)
label.setFont(QFont("Arial", 40))
layout.addWidget(label)
class Button(QFrame):
def __init__(self):
super().__init__()
stacked_layout = QStackedLayout()
button = QWidget()
button_layout = QVBoxLayout()
text = QLabel()
text.setText("English")
text.setAlignment(Qt.AlignCenter)
button_layout.addWidget(text)
button_layout.setAlignment(Qt.AlignCenter)
button.setLayout(button_layout)
stacked_layout.addWidget(button)
self.setLayout(stacked_layout)
self.setFrameStyle(QFrame.Box)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.setFixedSize(260, 320)
layout.addSpacing(40)
layout.addWidget(Button())
main_window.show()
app.exec_()
您正在使用的setAlignment()
函数仅设置布局的对齐方式,而不设置其内容。
如果您使用最大尺寸的小部件并要指定对齐方式,则必须明确声明它:
layout.addWidget(Button(), alignment=Qt.AlignCenter)
否则,窗口小部件将尝试使用所有可用空间,但是由于您的空间超出了所需的空间,它将使用默认的系统对齐方式(左,上)。