How to create Label widget in PyQt5?

How to create Label widget in PyQt5?

Creating a QLabel widget in PyQt5 is straightforward. The QLabel widget provides a text or image display. Here's how you can create and use a QLabel in a PyQt5 application:

  • Install PyQt5 (if you haven't already):
pip install pyqt5 
  • Sample Code:

Here's a simple example demonstrating how to create and use a QLabel:

import sys from PyQt5.QtWidgets import QApplication, QLabel, QMainWindow, QVBoxLayout, QWidget class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle('QLabel Example') # Create a QVBoxLayout layout = QVBoxLayout() # Create a QLabel widget label = QLabel("Hello, PyQt5!") # Customize the QLabel if you wish # label.setAlignment(Qt.AlignCenter) # Center align the text # label.setFont(QFont('Arial', 20)) # Set font and size # Add the QLabel to the layout layout.addWidget(label) # Create a central widget for the main window central_widget = QWidget() central_widget.setLayout(layout) self.setCentralWidget(central_widget) app = QApplication(sys.argv) window = MainWindow() window.show() app.exec_() 

In this example:

  • We first import necessary modules from PyQt5.
  • We create a QMainWindow subclass and define our GUI within the __init__ method.
  • We create a QLabel with the text "Hello, PyQt5!".
  • We then add the QLabel to a vertical layout (QVBoxLayout).
  • Finally, we set this layout for the main window's central widget.

When you run the code, a window will pop up showing the label with the specified text.


More Tags

game-physics int reportlab subnet lua chromium non-alphanumeric vi blink sqlcommand

More Programming Guides

Other Guides

More Programming Examples