Python PyQt5:居中对齐标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25638261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:25:01  来源:igfitidea点击:

PyQt5: Center align a label

pythonpyqtpyqt5

提问by Lachlan Shoesmith

This should be really simple but I just can't find an answer for this. I've tried this PyQt4 code:

这应该很简单,但我找不到答案。我试过这个 PyQt4 代码:

label.setAlignment(Qt.AlignCenter)

But that gives me no luck.

但这没有给我带来任何运气。

Thanks

谢谢

采纳答案by Fenikso

I think the problem may be that the label is centered, but it does not fill the space you think it does. You can verify by changing the label background color. The following example works for me on Windows 7:

我认为问题可能是标签居中,但它没有填充您认为的空间。您可以通过更改标签背景颜色来验证。以下示例适用于 Windows 7:

import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Window(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)

        self.label = QLabel("Test", self)
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setStyleSheet("QLabel {background-color: red;}")

        self.button = QPushButton("Test", self)

        self.layout = QGridLayout()
        self.layout.addWidget(self.label, 0, 0)
        self.layout.addWidget(self.button, 0, 1)

        self.setLayout(self.layout)
        self.show()

app = QApplication(sys.argv)
win = Window()
sys.exit(app.exec_())

回答by Lachlan Shoesmith

I've got a workaround with HTML translating!

我有一个解决 HTML 翻译的方法!

self.smallPWDisp.setText(_translate('Window', '<html><head/><body><p align=\'center\'>%s is your new password!</p></body></html>' % smallPassword))

回答by 91cobra

I had the same problem.

我有同样的问题。

Try using:

尝试使用:

Qt.Qt.AlignCenter.

回答by Caching

The value of AlignCenter was defined at PyQt5.QtCore.Qt.AlignCenter, the other Align value was also define at QtCore.Qt. QtCore.QtModule also contain core value such as keyboard value CTRL, SHIFT, ALT etc.

AlignCenter 的值定义在PyQt5.QtCore.Qt.AlignCenter,另一个 Align 值也定义在QtCore.QtQtCore.Qt模块还包含核心值,例如键盘值 CTRL、SHIFT、ALT 等。

回答by Mujeeb Ishaque

from PyQt5 import QtCore

# to center align a label 

self.your_label.setAlignment(QtCore.Qt.AlignCenter)

For more information, please follow the following StackOverflow thread: Qt has no attribute 'AlignCenter'

有关更多信息,请遵循以下 StackOverflow 线程: Qt has no attribute 'AlignCenter'