Home » Tutorial on PyQt6 QLabel Widget

Tutorial on PyQt6 QLabel Widget

Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Java SE 11 Developer (Upgrade) [1Z0-817]

QLabel is a versatile widget in PyQt6 used to display text, images, or rich content like HTML. It is one of the simplest yet most powerful widgets for presenting information in a GUI application.

In this tutorial, we will cover:

1. Basics of QLabel

To create a QLabel, instantiate the class and set its content using the setText() or setPixmap() methods. Add the label to a layout or set it as a central widget.

Example: Basic QLabel Setup

from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Basic QLabel Example")
    window.setGeometry(100, 100, 300, 200)

    label = QLabel("Hello, PyQt6!", window)
    label.move(50, 50)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A window displaying the text “Hello, PyQt6!” at the specified position.

2. Displaying Text

The setText() method allows you to display plain or rich text.

Example: Plain Text Display

label = QLabel("This is plain text.", window)

Example: Dynamic Text Update

label = QLabel("Initial Text", window)
label.setText("Updated Text")

3. Using Rich Text and HTML

You can display formatted text using HTML or rich text tags.

Example: Displaying Rich Text

label = QLabel("<h1 style='color:blue;'>Hello, <i>PyQt6</i>!</h1>", window)
label.setTextFormat(Qt.TextFormat.RichText)

Example: Displaying Bulleted List

label = QLabel("""
<ul>
    <li>PyQt6</li>
    <li>QLabel</li>
    <li>Rich Text</li>
</ul>
""", window)
label.setTextFormat(Qt.TextFormat.RichText)

4. Displaying Images

Use setPixmap() to display images in a QLabel. You need to use QPixmap to load and manipulate the image.

Example: Displaying an Image

from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt6.QtGui import QPixmap

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("QLabel Image Example")
    window.setGeometry(100, 100, 400, 300)

    label = QLabel(window)
    pixmap = QPixmap("path/to/image.png")
    label.setPixmap(pixmap)
    label.resize(pixmap.size())

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A window displaying the image.

5. Adjusting Alignment and Scaling

You can align text or images using setAlignment() and scale images with setScaledContents().

Example: Center Align Text

label.setAlignment(Qt.AlignmentFlag.AlignCenter)

Example: Scale Image to Fit QLabel

label.setScaledContents(True)
label.resize(300, 200)  # Resize QLabel to see the effect

6. Interactive Features (Mouse Events)

You can make QLabel interactive by enabling mouse events.

Example: Detecting Mouse Clicks

from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt6.QtCore import Qt

class InteractiveLabel(QLabel):
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.setText("Mouse clicked!")

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Interactive QLabel Example")
    window.setGeometry(100, 100, 300, 200)

    label = InteractiveLabel("Click me!", window)
    label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    label.setGeometry(50, 50, 200, 100)

    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • Clicking on the label updates its text.

7. Styling QLabel with CSS

You can style QLabel using CSS-like syntax with setStyleSheet().

Example: Styling Text

label.setStyleSheet("color: red; font-size: 20px; background-color: yellow; border: 2px solid black;")

Example: Adding Hover Effect

label.setStyleSheet("""
QLabel {
    color: black;
}
QLabel:hover {
    color: blue;
    font-weight: bold;
}
""")

8. Practical Examples

Example: Displaying a Digital Clock

from PyQt6.QtWidgets import QApplication, QLabel, QMainWindow
from PyQt6.QtCore import QTimer, QTime

def update_time(label):
    current_time = QTime.currentTime().toString("hh:mm:ss")
    label.setText(current_time)

def main():
    app = QApplication([])
    window = QMainWindow()
    window.setWindowTitle("Digital Clock")
    window.setGeometry(100, 100, 200, 100)

    label = QLabel("", window)
    label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    label.setStyleSheet("font-size: 24px;")
    label.setGeometry(20, 20, 160, 60)

    timer = QTimer()
    timer.timeout.connect(lambda: update_time(label))
    timer.start(1000)

    update_time(label)
    window.show()
    app.exec()

if __name__ == "__main__":
    main()

Output:

  • A real-time digital clock updates every second.

Summary

In this tutorial, we explored:

  1. Basics of QLabel: Displaying text.
  2. Rich Text and HTML: Formatting content with HTML.
  3. Displaying Images: Using QPixmap with QLabel.
  4. Alignment and Scaling: Aligning and resizing content.
  5. Interactive Features: Detecting mouse events.
  6. Styling with CSS: Customizing appearance.
  7. Practical Examples: Building a digital clock.

QLabel is a highly flexible widget, capable of handling diverse use cases like text, images, or even interactive displays. Mastering it will allow you to build visually appealing and functional PyQt6 applications.

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More