[파이썬] PyQt 라벨 (`QLabel`) 위젯

In this blog post, we will explore the QLabel widget in PyQt, which is used to display text or images on a PyQt application’s user interface.

Introduction to QLabel

The QLabel widget is a versatile widget in PyQt that allows you to display text or images. It is commonly used to show labels or titles on buttons, windows, or other graphical user interface (GUI) components.

Creating a QLabel

To create a QLabel in PyQt, you need to import the necessary module and initialize an instance of the QLabel class. Here’s an example code snippet that demonstrates this:

from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow

# Create an instance of QApplication
app = QApplication([])

# Create a QMainWindow instance
window = QMainWindow()

# Create a QLabel instance with text
label = QLabel('Hello, PyQt!')

# Set the QLabel as the central widget of the QMainWindow
window.setCentralWidget(label)

# Show the QMainWindow
window.show()

# Start the event loop
app.exec_()

In the above code, we first import the necessary modules QApplication, QLabel, and QMainWindow from the PyQt5 module. Then, we create an instance of QApplication and QMainWindow.

Next, we create a QLabel instance and set its text to ‘Hello, PyQt!’. We then set the QLabel as the central widget of the QMainWindow using the setCentralWidget() method.

Finally, we show the QMainWindow and start the event loop by calling the app.exec_() method.

Customizing QLabel

You can customize the appearance of a QLabel by applying various properties such as font size, color, alignment, and more. Here’s an example that demonstrates some customization options:

label = QLabel('Hello, PyQt!')

# Set font size and color
label.setStyleSheet("font-size: 20px; color: #ff0000;")

# Set text alignment
label.setAlignment(Qt.AlignCenter)

In this code snippet, we set the font size to 20 pixels and the text color to red using the setStyleSheet() method. We also align the text to the center using the setAlignment() method.

Conclusion

The QLabel widget in PyQt is a versatile tool for displaying text or images on a PyQt application’s user interface. By leveraging its customization options, you can create visually appealing labels and titles for your GUI components.

In this blog post, we learned how to create a QLabel, set its text, and customize its appearance. Experiment with QLabel and explore more of its features to enhance your PyQt applications with informative and visually appealing labels.