14

I am using PyQt5 on Python 3.5.

I want to make a QLabel widget with a centered text. Therefore, I call the setAlignment method with the AlignCenter flag.

Here is an MWE:

import sys
from PyQt5 import QtWidgets, Qt

app = QtWidgets.QApplication(sys.argv)

label = QtWidgets.QLabel()
label.setAlignment(Qt.AlignCenter)

However, I get the following error:

label.setAlignment(Qt.AlignCenter)

AttributeError: module 'PyQt5.Qt' has no attribute 'AlignCenter'

But the Qt.AlignCenter, as well as other alignment flags, are referenced in PyQt's documentation, as well as Qt's documentation.

What am I doing wrong?

Community
  • 1
  • 1
Right leg
  • 16,080
  • 7
  • 48
  • 81
  • I am posting this question along with the solution I found. This might be a really specific case, and I probably got in this situation because I read the documentation too hastily. However, I do believe that the naming is confusing, and I want to help people who might get in the same situation. – Right leg Jan 26 '17 at 15:40

1 Answers1

20

The AttributeError that is raised tells that PyQt5.Qt has no attribute called AlignCenter.

This can easily be confirmed in Python's interactive help:

>>> from PyQt5 import Qt
>>> help(Qt)

help will display a bunch of methods, but a quick search of "alignment" will give zero results.

As a matter of fact, the AlignCenter flag does not belong to the PyQt5.Qt module, but to the PyQt5.QtCore.Qt class.

Therefore, changing

label.setAlignment(Qt.AlignCenter)

into

label.setAlignment(QtCore.Qt.AlignCenter)

along with the right import will do the work.


The following code shows that this actually works. I had to add some details to the original code to make the centering visible.

import sys
from PyQt5 import QtWidgets, QtCore

app = QtWidgets.QApplication(sys.argv)

label = QtWidgets.QLabel()
label.setGeometry(100, 100, 200, 100)
label.setText("Hello world!")
label.setAlignment(QtCore.Qt.AlignCenter)

label.show()

exit(app.exec_())

Centered text label

With the alignment commented out:

import sys
from PyQt5 import QtWidgets, QtCore

app = QtWidgets.QApplication(sys.argv)

label = QtWidgets.QLabel()
label.setGeometry(100, 100, 200, 100)
label.setText("Hello world!")
# label.setAlignment(QtCore.Qt.AlignCenter)

label.show()

exit(app.exec_())

Untouched label

Right leg
  • 16,080
  • 7
  • 48
  • 81
  • 15
    Leaving this here as a comment for any confused PyQt6 porters: `QtCore.Qt.AlignmentFlag.AlignCenter` would be the syntax for PyQt6 – The-Duck Jul 22 '21 at 12:20
  • 'Cursors' object has no attribute 'RESIZE_HORIZONTAL' is what I get with %matplotlib qt. It seems similar. Could you advise me ? – zazoupile May 11 '22 at 11:23
  • Thanks, this was a really confusing snag. – Angelo Sep 07 '22 at 13:32