25

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

label.setAlignment(Qt.AlignCenter)

But that does not work.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Lachlan
  • 1,245
  • 5
  • 18
  • 34

5 Answers5

26

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:

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_())
Fenikso
  • 9,251
  • 5
  • 44
  • 72
8

I had the same problem.

Try using:

Qt.Qt.AlignCenter.
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
91cobra
  • 81
  • 1
  • 2
8
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'

Mujeeb Ishaque
  • 2,259
  • 24
  • 16
3

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

Caching
  • 31
  • 2
1

I've got a workaround with HTML translating!

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