Logo
Introduction to PyQt: A Simple Example

Introduction to PyQt: A Simple Example

August 28, 2024

PyQt is a set of Python bindings for Qt application framework, which is used to develop graphical user interfaces (GUIs) as well as multi-platform applications. PyQt brings together the Qt C++ cross-platform application framework and the cross-platform interpreted language Python. PyQt5 and PyQt6 are the most popular versions, with PyQt6 being the newer iteration that aligns with Qt6 features.

In this article, we will explore how to create a simple application using PyQt6, covering the basic components and steps to get you started with this powerful toolkit.

Setting Up PyQt6

Before diving into the coding part, you need to install PyQt6. It can be installed via pip:

pip install PyQt6

This command installs not only the PyQt6 library but also its dependencies, including Qt libraries.

Creating a Simple GUI Application

Let's create a basic application that includes a window with a button. When the button is clicked, it will display a message.

1. Import Necessary Modules

First, import the necessary modules from PyQt6:

from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
2. Create a Main Window Class

Define a class for your main window. This class will inherit from QMainWindow.

class AppWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('PyQt6 Simple Example')  # Set the window title
        self.setGeometry(300, 300, 400, 300)  # Set the window size

        # Add a button
        self.button = QPushButton('Click Me', self)
        self.button.setGeometry(100, 100, 200, 50)
        self.button.clicked.connect(self.on_click)

    def on_click(self):
    QMessageBox.information(self, 'Message', 'You clicked the button!')

In this class:

  • The __ __init __ __ method sets up the window, including its title and size.
  • A button is created, positioned, and connected to the on_click method, which is triggered when the button is clicked.
3. Initialize and Run the Application

After setting up the main window class, initialize and run the application by adding the following code outside of the class:

  • QApplication([]) initializes the application with sys.argv to allow command line arguments (empty list here for simplicity).
  • window.show() makes the window visible.
  • app.exec() starts the main event loop, ensuring that the application remains open until it is closed by the user.
Conclusion

You've just seen how to create a basic GUI application using PyQt6. This example introduces the fundamental concepts of window creation, widget use (like buttons), and event handling. PyQt provides a comprehensive set of tools to develop more complex applications, including dialogs, menus, and different types of widgets. With these basics, you can explore more features of PyQt to build sophisticated and modern graphical applications.

@2024 Easely, Inc. All rights reserved.