Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt has no attribute 'AlignCenter' [duplicate]

Tags:

python

pyqt5

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?

like image 759
Right leg Avatar asked Jan 26 '17 15:01

Right leg


1 Answers

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

like image 93
Right leg Avatar answered Nov 03 '22 01:11

Right leg