The QLabel Widget
Explore how to implement the QLabel widget in PyQt6 to display text and images within your GUI applications. Learn to position labels using absolute positioning and understand alignment flags for customizing the appearance of your widgets.
We'll cover the following...
We will now use QLabel widgets to add extra functionality to our projects. To display text, pictures, or movies, a QLabel object serves as a non-editable placeholder. It can also label other widgets so their functions or titles can be specified. Plain text, hyperlinks, and rich text can all be displayed with QLabel widgets.
Using the QLabel widget
First, we start by importing the necessary modules from QtWidgets (QApplication, QWidget and, QLabel), QtGui (QPixmap), and sys. We must import the QtWidgets class to create the window, and because we will be utilizing the QLabel widget this time, we must include it in our import line. The QtGui module needs to be imported this time as well. QtGui handles numerous graphical aspects. A Qt class called QPixmap is explicitly designed for displaying images on screens.
The window is then initialized and its contents are displayed on the screen by creating a class derived from the QWidget class. The next step is to make our application, create a class called HelloWorldWindow that derives from the QWidget base class, and initialize the window's size with setGeometry() and the GUI's title. The window is then displayed using the show() method.
After creating a new function displayLabels, we use it to display text and images using QLabel. Then we implement a check to see if image files exist. If not, throw an exception (lines 12 to 13).
Then we run the program and use exec instead of exec_ as this change is implemented in PyQt6. The event loop is launched using exec(). Finally, we utilize sys.exit() to terminate our program.
Explanation
We will utilize the displayLabels() function in the HelloWorldWindow class to show text and images. To begin, we construct a QLabel object and use setText() to indicate what the label will say. The text, in this case, is set to "Hello." We arrange the label in the window using move() function in the following line: text = QLabel(self) text.setText(“Hello”) text.move(260, 15). Horizontal layouts, grid layouts, and absolute positioning are just a few layout techniques in PyQt6. We will use move() and absolute positioning for the programs developed in this module. To position a widget in the window, all you need to do with the move() is define the pixel values of the widget's top-left corner. We enter x = 260 and y = 15 as the values for our text label.
Similar to how our image is loaded, a QLabel is produced and placed in the main window. The image is then built into a QPixmap, and using setPixmap() it is shown on the world_image label. Using move(), the label's precise location is set. However, move() isn't the only positioning method in PyQt6. Each of PyQt's different classes has methods that can be used to customize and change its look and functionality, which is great for us developers.
Try it yourself
import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QPixmap
class HelloWorldWindow(QWidget):
def __init__(self):
super().__init__()
self.initializeUI()
def initializeUI(self):
self.setGeometry(150, 50, 700, 700)
self.setWindowTitle('QLabel')
self.displayLabels()
self.show()
def displayLabels(self):
text = QLabel(self)
text.setText("Hello")
text.move(260, 15)
image = "world2.png"
try:
with open(image):
world_image = QLabel(self)
pixmap = QPixmap(image)
world_image.setPixmap(pixmap)
world_image.move(25, 40)
except FileNotFoundError:
print("Image not found.")
if __name__ == '__main__':
app = QApplication(sys.argv)
window = HelloWorldWindow()
sys.exit(app.exec())Changing alignment in PyQt
The alignment is defined through the use of a flag from the Qt.namespace. Flags that can be used for horizontal alignment include:
Alignment with PyQt
PyQt Flag | Behavior |
| Aligns with the left edge |
| Aligns with the right edge |
| Centers horizontally |
| Justifies the text |
Pipes (|) can be used to connect flags, but you can only use one of the two alignment flags at the same time:
align_top_left = Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop
Note: We need to use an OR pipe (|) to merge the two flags (not A & B). The fact that the flags are non-overlapping bitmasks explains this. As
Qt.AlignmentFlag.AlignLefthas the hexadecimal value of 0x0001, whileQt.AlignmentFlag.AlignBottomis 0x0040. We obtain the value 0x0041, which stands for "bottom left," by ORing the two. All other combinational Qt flags follow this rule.
Finally, there is a shorthand flag that simultaneously centers in both directions and is likely to be the most useful to us. Qt.AlignmentFlag.AlignCenter centers horizontally and vertically.