How to Create QLabel Widget in PyQt6?

As a Python developer with over a decade of experience building desktop applications for clients across the USA, I came across a situation while developing a healthcare application for a Boston medical center, a financial dashboard for Wall Street analysts I needed to use the QLabel widget. In this article, I will explain how to create QLabel widget in PyQt6 with appropriate examples.

Create QLabel Widget in PyQt6

QLabel is one of the most fundamental widgets in the PyQt6 framework. It serves as a display widget for text or images on your application’s interface and doesn’t provide any user interaction by default. Think of it as the digital equivalent of labels you see on physical products or signs – its purpose is to inform, identify, and provide context.

QLabel offers rich functionality that, when used effectively, can significantly improve your application’s user experience and visual appeal.

Read How to Install PyQt6 on Different Platforms?

Set Up Your Environment

Before getting into QLabel implementation, ensure you have PyQt6 installed on your development environment:

# Install PyQt6 if you haven't already
pip install PyQt6

Create Your First QLabel

Let’s start with a basic QLabel that displays text:

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtCore import Qt

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Create a simple text label
        label = QLabel("Welcome to my PyQt6 application", self)
        label.move(50, 50)  # Position the label

        self.setWindowTitle("Basic QLabel Example")
        self.setGeometry(100, 100, 500, 400)
        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

You can see the output in the screenshot below.

Create QLabel Widget in PyQt6

This creates a simple label with the text “Welcome to my PyQt6 application” positioned at coordinates (50, 50) from the top-left corner of the window.

Read QComboBox Widget in PyQt6

Text Formatting and Appearance

One of the strengths of QLabel is its ability to display formatted text. Here’s how to enhance your labels with different formatting options:

HTML Formatting

html_label = QLabel(self)
html_label.setText("<h1>HTML Formatting</h1>"
                   "<p>This label contains <b>bold</b>, <i>italic</i>, "
                   "and <span style='color: red;'>colored</span> text.</p>"
                   "<p>You can even add <a href='https://python.org'>hyperlinks</a>!</p>")
html_label.setTextFormat(Qt.TextFormat.RichText)
html_label.setOpenExternalLinks(True)  # Make hyperlinks clickable
html_label.move(50, 100)

You can see the output in the screenshot below.

How to Create QLabel Widget in PyQt6

Text Alignment

aligned_label = QLabel("This text is centered in the label", self)
aligned_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
aligned_label.setGeometry(50, 200, 400, 30)
aligned_label.setStyleSheet("background-color: #f0f0f0; padding: 5px;")

Style with CSS

styled_label = QLabel("Styled with CSS", self)
styled_label.setGeometry(50, 250, 400, 50)
styled_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
styled_label.setStyleSheet("""
    background-color: #2c3e50;
    color: white;
    font-family: 'Arial';
    font-size: 18px;
    font-weight: bold;
    border-radius: 10px;
    padding: 10px;
""")

Check out Create a Basic Window in PyQt6

Display Images with QLabel

QLabel isn’t just for text – it’s also perfect for displaying images in your application. Here’s how to implement image display:

from PyQt6.QtGui import QPixmap

def init_ui(self):
    # Create a label for displaying an image
    image_label = QLabel(self)
    pixmap = QPixmap("company_logo.png")
    image_label.setPixmap(pixmap)
    image_label.setGeometry(50, 50, pixmap.width(), pixmap.height())

    # Add a caption below the image
    caption = QLabel("Company Logo", self)
    caption.move(50, pixmap.height() + 60)

    self.setWindowTitle("Image QLabel Example")
    self.setGeometry(100, 100, max(500, pixmap.width() + 100), pixmap.height() + 150)
    self.show()

Scale Images

To ensure your images fit properly within your interface, you can scale them:

# Scale the image to fit a specific size
scaled_label = QLabel(self)
pixmap = QPixmap("product_photo.jpg")
scaled_pixmap = pixmap.scaled(300, 200, Qt.AspectRatioMode.KeepAspectRatio, 
                              Qt.TransformationMode.SmoothTransformation)
scaled_label.setPixmap(scaled_pixmap)
scaled_label.move(50, 300)

Put all the Code Together

import sys
from PyQt6.QtWidgets import QApplication, QWidget, QLabel
from PyQt6.QtGui import QPixmap
from PyQt6.QtCore import Qt

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        # Set window title and size
        self.setWindowTitle("QLabel - Displaying Images")
        self.setGeometry(100, 100, 500, 500)

        # Display Original Image
        image_label = QLabel(self)
        pixmap = QPixmap(r"C:\Users\Public\code\example\images\company_logo.png")  # Replace with your image
        if not pixmap.isNull():
            image_label.setPixmap(pixmap)
            image_label.setGeometry(50, 50, pixmap.width(), pixmap.height())

            # Add a caption below the image
            caption = QLabel("Company Logo", self)
            caption.move(50, pixmap.height() + 60)

        # Display Scaled Image
        scaled_label = QLabel(self)
        scaled_pixmap = QPixmap(r"C:\Users\Public\code\example\images\product_logo.png")  # Replace with your image
        if not scaled_pixmap.isNull():
            scaled_pixmap = scaled_pixmap.scaled(300, 200, Qt.AspectRatioMode.KeepAspectRatio, 
                                                 Qt.TransformationMode.SmoothTransformation)
            scaled_label.setPixmap(scaled_pixmap)
            scaled_label.move(50, 300)

        self.show()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

You can see the output in the screenshot below.

Create image QLabel Widget in PyQt6

Read Create a Random Number Generator with QLCDNumber in PyQt6

Create Interactive Labels

While QLabel is primarily a display widget, you can make it interactive through signals and event handling:

class InteractiveLabel(QLabel):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("background-color: #dff9fb; padding: 10px; border-radius: 5px;")

    def mousePressEvent(self, event):
        self.setStyleSheet("background-color: #c7ecee; padding: 10px; border-radius: 5px;")

    def mouseReleaseEvent(self, event):
        self.setStyleSheet("background-color: #dff9fb; padding: 10px; border-radius: 5px;")
        print(f"Label clicked: {self.text()}")

# In your init_ui method:
interactive_label = InteractiveLabel("Click me!", self)
interactive_label.setGeometry(50, 350, 200, 40)

Clickable Hyperlinks in QLabel

For applications that need to reference websites or documentation, enabling clickable hyperlinks in QLabel is incredibly useful:

hyperlink_label = QLabel(self)
hyperlink_label.setText("Visit our <a href='https://www.example.com'>website</a> for more information.")
hyperlink_label.setOpenExternalLinks(True)  # Open links in browser
hyperlink_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
hyperlink_label.setGeometry(50, 400, 400, 30)

You can also handle link clicks programmatically:

hyperlink_label = QLabel(self)
hyperlink_label.setText("Check our <a href='documentation'>documentation</a> or <a href='support'>contact support</a>.")
hyperlink_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
hyperlink_label.linkActivated.connect(self.handle_link)
hyperlink_label.setGeometry(50, 450, 400, 30)

# Link handler method
def handle_link(self, link):
    if link == "documentation":
        print("Opening documentation...")
        # Code to open documentation
    elif link == "support":
        print("Opening support...")
        # Code to open support page

Check out Build a Simple Digital Clock with QLCDNumber in PyQt6

Create a Multi-line QLabel

In PyQt6, QLabel is used to display text, and when you need to show longer text content, enabling word wrapping allows text to break across multiple lines instead of overflowing.

multiline_label = QLabel(self)
multiline_label.setText("This is a multi-line label.\nIt can display text across\nmultiple lines.")
multiline_label.setWordWrap(True)  # Enable word wrapping
multiline_label.setGeometry(50, 500, 400, 100)
multiline_label.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop)
multiline_label.setStyleSheet("background-color: #f5f6fa; padding: 10px;")

This is useful for displaying instructions, descriptions, or long messages in your PyQt6 applications.

Combine Text and Images

In PyQt6, you can use QPixmap and QPainter to create a custom QLabel that displays both text and images. This technique is particularly useful for notifications, alerts, or informative messages in GUI applications.

from PyQt6.QtGui import QPixmap, QPainter
from PyQt6.QtCore import QPoint, QRect

def create_text_image_label(self):
    # Create a pixmap to draw on
    pixmap = QPixmap(400, 100)
    pixmap.fill(Qt.GlobalColor.white)

    # Create a painter to draw on the pixmap
    painter = QPainter(pixmap)

    # Draw an image
    icon = QPixmap("info_icon.png").scaled(32, 32, Qt.AspectRatioMode.KeepAspectRatio)
    painter.drawPixmap(QPoint(10, 10), icon)

    # Draw text next to the image
    painter.drawText(QRect(50, 10, 340, 80), 
                    "This label combines text and an image.\n"
                    "Useful for notifications and information displays.")

    # End painting
    painter.end()

    # Create label with the pixmap
    combined_label = QLabel(self)
    combined_label.setPixmap(pixmap)
    combined_label.setGeometry(50, 620, 400, 100)
    combined_label.setStyleSheet("border: 1px solid #ddd; border-radius: 5px;")

Useful for warning messages, tooltips, and status indicators in GUI applications.

Read QSpinBox Widget in PyQt6

Animated Labels

In PyQt6, you can create a blinking/animated QLabel using QTimer. This method is useful for grabbing user attention in cases like warnings, notifications, or alerts.

from PyQt6.QtCore import QTimer

class AnimatedLabel(QLabel):
    def __init__(self, text, parent=None):
        super().__init__(text, parent)
        self.setStyleSheet("color: red; font-weight: bold; font-size: 16px;")

        # Set up the animation timer
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_animation)
        self.timer.start(500)  # Update every 500ms

        self.visible = True

    def update_animation(self):
        if self.visible:
            self.setStyleSheet("color: red; font-weight: bold; font-size: 16px;")
        else:
            self.setStyleSheet("color: transparent; font-weight: bold; font-size: 16px;")

        self.visible = not self.visible

# In your init_ui method:
animated_label = AnimatedLabel("IMPORTANT NOTICE", self)
animated_label.setGeometry(50, 740, 200, 30)

Comprehensive QLabel Methods Reference

Here’s a reference table of the most useful QLabel methods I regularly use in my professional projects:

MethodDescription
setText(text)Sets the label’s text content
text()Returns the current text content
setPixmap(pixmap)Sets an image to display
pixmap()Returns the current pixmap (if any)
setAlignment(alignment)Sets text alignment (e.

Conclusion

In this article, I explained how to create QLabel widget in PyQt6. I discussed QLabel, setting up the environment and creating our first QLabel, text formatting and appearance and displaying images with QLabel. I also explained how to create interactive labels, clickable links , create multi-line QLabel, combine text and images, and animated labels.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.