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.
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.
Let's create a basic application that includes a window with a button. When the button is clicked, it will display a message.
First, import the necessary modules from PyQt6:
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QMessageBox
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:
After setting up the main window class, initialize and run the application by adding the following code outside of the class:
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.