PyQt5: Center Label Alignment

It should be very simple, but I just can't find the answer for this. I tried this PyQt4 code:

label.setAlignment(Qt.AlignCenter) 

But I’m out of luck.

thanks

+5
source share
4 answers

I think the problem may be that the label is centered, but it does not fill the space that you think it makes. You can check by changing the background color of the label. The following example works for me on 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_()) 
+5
source

I had the same problem.

Try using Qt.Qt.AlignCenter.

+3
source

I have a workaround ... HTML translation!

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

It worked for me. Thanks again!

0
source

The AlignCenter value was defined in PyQt5.QtCore.Qt.AlignCenter , another Align value was also defined in QtCore.Qt . QtCore.Qt The module also contains a kernel value, such as the value of the CTRL, SHIFT, ALT keys, etc.

0
source

Source: https://habr.com/ru/post/1201704/


All Articles