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?
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_())
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_())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With