Mastering QLabel in PySide6: Text, Images, Hyperlinks & More!

The QLabel widget in PySide6 is used to display text or images in a GUI application. It is one of the simplest and most versatile widgets, often used for displaying information, providing instructions, or as part of a form.
Key Features of QLabel
- Text Display: Displays plain or rich text.
- Image Display: Supports displaying images.
- Hyperlink Support: Can display and handle hyperlinks.
- Alignment Options: Allows text and image alignment.
- Scalable: Adjusts its size to fit the content.
Creating a QLabel
To create a QLabel in PySide6, instantiate the QLabel class and set its text or image. Here is a basic example:
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.label = QLabel("Hello, PySide6!")
layout.addWidget(self.label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
In this example, a simple QLabel with the text "Hello, PySide6!" is created and added to a vertical layout.
Displaying Images
You can display images using QLabel by setting a pixmap. Here’s how you can do it:
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QPixmap
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.image_label = QLabel()
pixmap = QPixmap("banner.png")
self.image_label.setPixmap(pixmap)
layout.addWidget(self.image_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
This sets an image to the QLabel and adds it to the layout.
Displaying Rich Text
QLabel supports rich text formatting using HTML tags. This allows you to create styled text with various fonts, colors, and other formatting options:
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QPixmap
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.rich_text_label = QLabel()
self.rich_text_label.setText("<b>Bold Text</b> <i>Italic Text</i> <u>Underlined Text</u>")
layout.addWidget(self.rich_text_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
Handling Hyperlinks
You can use QLabel to display hyperlinks, which can be made clickable by setting the openExternalLinks property:
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QPixmap
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.link_label = QLabel()
self.link_label.setText('<a href="<https://www.example.com>">Click here to visit Example</a>')
self.link_label.setOpenExternalLinks(True)
layout.addWidget(self.link_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
This makes the hyperlink in the label clickable, opening the link in the default web browser.
Alignment and Scaling
QLabel provides alignment options for text and images, and it can scale content to fit its size:
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.aligned_label = QLabel("Aligned Text")
self.aligned_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.aligned_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
To enable word wrapping for long text:
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
class LabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.wrapped_label = QLabel("This is a very long text that needs to be wrapped.")
self.wrapped_label.setWordWrap(True)
layout.addWidget(self.wrapped_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = LabelExample()
window.show()
app.exec()
Practical Example
Let’s create a more practical example where QLabel is used to display different types of content:
from PySide6.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide6.QtGui import QPixmap
from PySide6.QtCore import Qt
class QLabelExample(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
# Simple text label
self.text_label = QLabel("Hello, PySide6!")
layout.addWidget(self.text_label)
# Image label
self.image_label = QLabel()
pixmap = QPixmap("banner.png")
self.image_label.setPixmap(pixmap)
layout.addWidget(self.image_label)
# Rich text label
self.rich_text_label = QLabel()
self.rich_text_label.setText("<b>Bold Text</b> <i>Italic Text</i> <u>Underlined Text</u>")
layout.addWidget(self.rich_text_label)
# Hyperlink label
self.link_label = QLabel()
self.link_label.setText('<a href="<https://www.example.com>">Click here to visit Example</a>')
self.link_label.setOpenExternalLinks(True)
layout.addWidget(self.link_label)
# Aligned text label
self.aligned_label = QLabel("Aligned Text")
self.aligned_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.aligned_label)
# Word-wrapped text label
self.wrapped_label = QLabel("This is a very long text that needs to be wrapped.")
self.wrapped_label.setWordWrap(True)
layout.addWidget(self.wrapped_label)
self.setLayout(layout)
self.setWindowTitle('QLabel Example')
app = QApplication([])
window = QLabelExample()
window.show()
app.exec()
In this example, we demonstrate various uses of QLabel, including displaying simple text, images, rich text, hyperlinks, aligned text, and word-wrapped text.
Banner
import sys
from PySide6.QtWidgets import (
QApplication, QWidget, QVBoxLayout, QLabel, QPushButton, QMainWindow
)
from PySide6.QtGui import QResizeEvent, QCursor, QPixmap
from PySide6.QtCore import Qt
class BannerWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setFixedHeight(350)
self.image_label = QLabel(self)
self.pixmap = QPixmap("banner.png")
self.overlay = QWidget(self)
self.overlay.setStyleSheet("background-color: rgba(0, 0, 0, 200); border: none;")
layout = QVBoxLayout(self.overlay)
layout.setContentsMargins(50, 50, 50, 50)
layout.setAlignment(Qt.AlignmentFlag.AlignCenter)
title = QLabel("Unlock the Power of the Stock Market")
title.setStyleSheet("""
background-color: transparent;
color: #FFFFFF;
font-family: 'Segoe UI', Arial;
font-size: 42px;
font-weight: 900;
text-transform: uppercase;
letter-spacing: 2px;
""")
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
title.setWordWrap(True)
layout.addWidget(title)
layout.addSpacing(10)
subtitle = QLabel("Real-time tracking, insightful analysis, and seamless trading")
subtitle.setStyleSheet("""
background-color: transparent;
color: #DDDDDD;
font-size: 20px;
font-style: italic;
""")
subtitle.setAlignment(Qt.AlignmentFlag.AlignCenter)
subtitle.setWordWrap(True)
layout.addWidget(subtitle)
layout.addSpacing(30)
cta_button = QPushButton("Start Trading Now")
cta_button.setStyleSheet("""
QPushButton {
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #28a745, stop:1 #218838);
color: white;
font-size: 18px;
font-weight: bold;
text-transform: uppercase;
border: 1px solid #1e7e34;
border-radius: 25px;
padding: 12px 24px;
}
QPushButton:hover {
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #2fad4c, stop:1 #23943c);
border: 1px solid #23943c;
}
QPushButton:pressed {
background-color: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #218838, stop:1 #1e7e34);
padding-top: 14px;
padding-bottom: 10px;
}
""")
cta_button.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
cta_button.setFixedSize(280, 50)
layout.addWidget(cta_button, alignment=Qt.AlignmentFlag.AlignCenter)
def resizeEvent(self, event: QResizeEvent):
super().resizeEvent(event)
self.image_label.resize(self.size())
self.overlay.resize(self.size())
if not self.pixmap.isNull():
scaled_pixmap = self.pixmap.scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatioByExpanding,
Qt.TransformationMode.SmoothTransformation)
self.image_label.setPixmap(scaled_pixmap)
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Stock Market App")
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
banner = BannerWidget()
main_layout.addWidget(banner)
content_area = QLabel("Your application content goes here...")
content_area.setAlignment(Qt.AlignmentFlag.AlignCenter)
content_area.setStyleSheet("font-size: 24px; color: #333; padding: 20px;")
main_layout.addWidget(content_area)
main_layout.addStretch(1)
self.showMaximized()
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
sys.exit(app.exec())