Python PyQt
PyQt is a powerful Python library for creating graphical user interfaces (GUIs), which can be used to replace Python's built-in Tkinter.
PyQt is the Python binding for the Qt framework, widely used in desktop application development.
Qt is a cross-platform C++ application development framework.
PyQt allows Python developers to leverage the Qt library to create powerful GUI applications.
PyQt has the following major versions:
- PyQt4: Bindings based on Qt4
- PyQt5: Bindings based on Qt5
- PyQt6: Bindings based on Qt6 (latest version)
Installing PyQt
Install PyQt5 with pip:
# 安装PyQt5 pip install PyQt5 # 安装Qt设计师和其他工具(可选) pip install PyQt5-tools
First PyQt Program
Create a Simple Window
The following is a basic PyQt program that creates an empty window:
Example
# Create application instance
app = QApplication([])
# Create main window
window = QWidget()
window.setWindowTitle("My first PyQt program")
window.setGeometry(100, 100, 400, 300) # (x, y, width, height)
# Show window
window.show()
# Run application
app.exec_()

Code Explanation
QApplicationManages the control flow and main settings of GUI applications.QWidgetThe most basic window class, all UI components inherit from it.setWindowTitle()Sets the window title.setGeometry()Sets the window position and size.show()Shows the window.app.exec_()Starts the event loop and waits for user interaction.
A typical PyQt application consists of the following parts:
- QApplication objectEvery PyQt application needs a QApplication instance.
- Windows and widgetsUser interface components.
- Event loopA loop that handles user input and system events.
- Event handlersFunctions or methods that respond to events.
Example
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# Set window title and size
self.setWindowTitle("My first PyQt application")
self.setGeometry(100, 100, 400, 300) # x, y, width, height
# Create button
self.button = QPushButton("Click me", self)
self.button.setGeometry(150, 150, 100, 30)
self.button.clicked.connect(self.button_clicked)
def button_clicked(self):
print("Button was clicked!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

Common PyQt Widgets
Button (QPushButton)
Example
button = QPushButton("Click me", window)
button.move(150, 150) # Set button position
Label (QLabel)
Example
label = QLabel("Hello PyQt!", window)
label.move(100, 100)
Text Box (QLineEdit)
Example
textbox = QLineEdit(window)
textbox.move(100, 50)
For more common widgets, see:https://www.example.com/python3/python-pyqt-widgets.html
Layout Management (QVBoxLayout)
Using layout managers can automatically adjust widget positions:
Example
layout = QVBoxLayout()
layout.addWidget(QLabel("Username"))
layout.addWidget(QLineEdit())
layout.addWidget(QPushButton("Login"))
window.setLayout(layout)
For more layout management content, see:https://www.example.com/python3/python-pyqt-layout.html
Signal and Slot Mechanism
PyQt usesSignalandSlotmechanism to handle events.
PyQt's signal and slot mechanism is the core mechanism for communication between objects.
- Signal: A notification emitted when a specific event occurs.
- Slot: A function or method that responds to signals.
Example
def on_button_click():
print("Button was clicked!")
button = QPushButton("Click me", window)
button.clicked.connect(on_button_click) # Connect signal and slot
Custom Signals
Example
class MyEmitter(QObject):
my_signal = pyqtSignal(str) # Define a signal
emitter = MyEmitter()
emitter.my_signal.connect(lambda x: print(f"Received signal: {x}"))
emitter.my_signal.emit("Hello") # Emit signal
For more layout management content, see:https://www.example.com/python3/python-pyqt-signals-and-slots.html
Using Qt Designer
Qt Designer is a visual design tool that allows you to drag and drop widgets to design interfaces:
- Launch Designer (usually located in the Lib\site-packages\qt5_applications\Qt\bin directory of your Python installation)
- Design the interface and save it as.uifile
will.uiConvert the file to Python code:
pyuic5 input.ui -o output.py
Use the generated interface in code:
Example
# Load UI file
Form, Window = uic.loadUiType("output.ui")
# Use UI
app = QApplication(sys.argv)
window = Window()
form = Form()
form.setupUi(window)
window.show()
sys.exit(app.exec_())
Hands-on: Simple Notepad Application
Interface Design
Example
from PyQt5.QtWidgets import (QApplication, QMainWindow, QTextEdit,
QAction, QFileDialog, QMessageBox)
class Notepad(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.text_edit = QTextEdit(self)
self.setCentralWidget(self.text_edit)
self.create_actions()
self.create_menus()
self.setWindowTitle('Simple Notepad')
self.setGeometry(100, 100, 800, 600)
def create_actions(self):
# File menu actions
self.new_action = QAction('New', self)
self.new_action.setShortcut('Ctrl+N')
self.new_action.triggered.connect(self.new_file)
self.open_action = QAction('Open', self)
self.open_action.setShortcut('Ctrl+O')
self.open_action.triggered.connect(self.open_file)
self.save_action = QAction('Save', self)
self.save_action.setShortcut('Ctrl+S')
self.save_action.triggered.connect(self.save_file)
self.exit_action = QAction('Exit', self)
self.exit_action.setShortcut('Ctrl+Q')
self.exit_action.triggered.connect(self.close)
# Edit menu actions
self.copy_action = QAction('Copy', self)
self.copy_action.setShortcut('Ctrl+C')
self.copy_action.triggered.connect(self.text_edit.copy)
self.paste_action = QAction('Paste', self)
self.paste_action.setShortcut('Ctrl+V')
self.paste_action.triggered.connect(self.text_edit.paste)
self.cut_action = QAction('Cut', self)
self.cut_action.setShortcut('Ctrl+X')
self.cut_action.triggered.connect(self.text_edit.cut)
def create_menus(self):
menubar = self.menuBar()
# File menu
file_menu = menubar.addMenu('File')
file_menu.addAction(self.new_action)
file_menu.addAction(self.open_action)
file_menu.addAction(self.save_action)
file_menu.addSeparator()
file_menu.addAction(self.exit_action)
# Edit menu
edit_menu = menubar.addMenu('Edit')
edit_menu.addAction(self.copy_action)
edit_menu.addAction(self.paste_action)
edit_menu.addAction(self.cut_action)
def new_file(self):
self.text_edit.clear()
def open_file(self):
filename, _ = QFileDialog.getOpenFileName(self, 'Open File')
if filename:
try:
with open(filename, 'r') as f:
self.text_edit.setText(f.read())
except Exception as e:
QMessageBox.warning(self, 'Error', f'Unable to open file: {e}')
def save_file(self):
filename, _ = QFileDialog.getSaveFileName(self, 'Save File')
if filename:
try:
with open(filename, 'w') as f:
f.write(self.text_edit.toPlainText())
except Exception as e:
QMessageBox.warning(self, 'Error', f'Unable to save file: {e}')
if __name__ == '__main__':
app = QApplication(sys.argv)
notepad = Notepad()
notepad.show()
sys.exit(app.exec_())

PyQt5 Core Widgets
Most widgets are located in PyQt5.QtWidgets.
Advanced features (such as multimedia, networking) may require other modules (e.g., QtCore, QtGui, QtNetwork, etc.).
QListView/QTableView/QTreeView need to be used with a data model (such as QStandardItemModel) for greater flexibility.
Other installation extensions:
pip install PyQtWebEngine # 网页支持 pip install PyQtChart # 图表支持
| Widget Category | Widget Name | Module | Description |
|---|---|---|---|
| Basic Window Widgets | QWidget | QtWidgets | Base class for all user interface objects, can be used as an empty window or container. |
QMainWindow | QtWidgets | Main window framework, containing menu bar, toolbar, status bar, etc. | |
QDialog | QtWidgets | Base class for dialogs, used for pop-up windows. | |
| Layout Management | QVBoxLayout | QtWidgets | Vertical layout manager |
QHBoxLayout | QtWidgets | Horizontal layout manager | |
QGridLayout | QtWidgets | Grid layout manager | |
QFormLayout | QtWidgets | Form layout manager (label + input field pairs) | |
| Button Classes | QPushButton | QtWidgets | Normal button |
QRadioButton | QtWidgets | Radio button | |
QCheckBox | QtWidgets | Checkbox | |
QToolButton | QtWidgets | Toolbar button (can have icon) | |
| Input Widgets | QLineEdit | QtWidgets | Single-line text input box |
QTextEdit | QtWidgets | Multi-line rich text editor (supports HTML) | |
QPlainTextEdit | QtWidgets | Multi-line plain text editor | |
QSpinBox | QtWidgets | Spin box (integer) | |
QDoubleSpinBox | QtWidgets | Spin box (float) | |
QComboBox | QtWidgets | Dropdown selection box | |
QDateEdit | QtWidgets | Date selection box | |
QTimeEdit | QtWidgets | Time selection box | |
QDateTimeEdit | QtWidgets | Date-time selection box | |
QSlider | QtWidgets | Slider (horizontal/vertical) | |
QDial | QtWidgets | Circular knob control | |
| Display Widgets | QLabel | QtWidgets | Text/image label |
QLCDNumber | QtWidgets | LCD digital display | |
QProgressBar | QtWidgets | Progress bar | |
QStatusBar | QtWidgets | Status bar (usually used forQMainWindow) | |
| Container Classes | QGroupBox | QtWidgets | Group box (container with title) |
QTabWidget | QtWidgets | Tab container | |
QStackedWidget | QtWidgets | Stacked container (displays one child widget at a time) | |
QScrollArea | QtWidgets | Scroll area container | |
QMdiArea | QtWidgets | MDI (Multiple Document Interface) area | |
| List/Table/Tree | QListWidget | QtWidgets | List control (with item management) |
QTreeWidget | QtWidgets | Tree widget | |
QTableWidget | QtWidgets | Table widget | |
QListView | QtWidgets | List view (requires a data model) | |
QTableView | QtWidgets | Table view (requires a data model) | |
QTreeView | QtWidgets | Tree view (requires a data model) | |
| Menu/Toolbar | QMenuBar | QtWidgets | Menu bar |
QMenu | QtWidgets | Menu (can contain submenus and actions) | |
QToolBar | QtWidgets | Toolbar | |
QAction | QtWidgets | Action (used for menu items, toolbar buttons, etc.) | |
| Dialog | QFileDialog | QtWidgets | File selection dialog |
QColorDialog | QtWidgets | Color selection dialog | |
QFontDialog | QtWidgets | Font selection dialog | |
QInputDialog | QtWidgets | Input dialog (text, numbers, etc.) | |
QMessageBox | QtWidgets | Message box (warning, error, question, etc.) | |
| Graphics view | QGraphicsView | QtWidgets | Graphics View Framework (for 2D graphics) |
QGraphicsScene | QtWidgets | Graphics scene (for combinedQGraphicsViewuse) | |
| Other functional components | QCalendarWidget | QtWidgets | Calendar widget |
QSplashScreen | QtWidgets | Splash screen | |
QSystemTrayIcon | QtWidgets | System tray icon | |
QWebEngineView | QtWebEngineWidgets | Web browser component (requires separate installationPyQtWebEngine) |