Creating a Simple PyQt5 Window with Label

  • Share this:

Code introduction


This code defines a function that creates a simple PyQt5 window with a label. The window's layout is managed by a QVBoxLayout, and the label is added to the layout.


Technology Stack : PyQt5, QWidget, QVBoxLayout, QLabel

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
import random
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel

def create_random_widget():
    # Create a new QApplication instance, required for any GUI application.
    app = QApplication([])
    
    # Create a QWidget instance which will be our main window.
    window = QWidget()
    
    # Create a QVBoxLayout instance to manage the layout of the widgets.
    layout = QVBoxLayout()
    
    # Create a QLabel instance with some text.
    label = QLabel("Hello, PyQt5!")
    
    # Add the label to the layout.
    layout.addWidget(label)
    
    # Set the layout on the window.
    window.setLayout(layout)
    
    # Show the window.
    window.show()
    
    # Return the application instance to allow for further interaction.
    return app