Python PyQt6 Module
PyQt6 is a set of Python bindings for the Qt application framework. It allows you to create modern, professional, and cross-platform desktop applications.
Installation
pip install PyQt6
Basic Application
Every PyQt6 application must create an application object (QApplication).
import sys
from PyQt6.QtWidgets import QApplication, QWidget
# 1. Create the Application
app = QApplication(sys.argv)
# 2. Create the main window (QWidget is the base class of all UI objects)
window = QWidget()
window.setWindowTitle("PyQt6 App")
window.resize(400, 300)
# 3. Show the window
window.show()
# 4. Start the event loop
sys.exit(app.exec())
Main Window (QMainWindow)
For a standard application window with a menu bar, toolbars, and a status bar, use QMainWindow.
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
label = QLabel("Hello World!")
# Set the central widget of the Window
self.setCentralWidget(label)
app = QApplication([])
window = MainWindow()
window.show()
app.exec()
Layouts
Layouts manage the positioning of widgets automatically.
QVBoxLayout: Vertical arrangement.QHBoxLayout: Horizontal arrangement.QGridLayout: Grid arrangement.
from PyQt6.QtWidgets import QWidget, QVBoxLayout, QPushButton
window = QWidget()
layout = QVBoxLayout()
layout.addWidget(QPushButton("Top"))
layout.addWidget(QPushButton("Center"))
layout.addWidget(QPushButton("Bottom"))
window.setLayout(layout)
window.show()
Signals and Slots
Qt uses a mechanism called signals and slots for event handling. A signal is emitted when a particular event occurs. A slot is a function that is called in response to a particular signal.
from PyQt6.QtWidgets import QApplication, QPushButton
def on_button_clicked():
print("Button was clicked!")
app = QApplication([])
button = QPushButton("Click Me")
# Connect the signal to the slot
button.clicked.connect(on_button_clicked)
button.show()
app.exec()