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

from PyQt5.QtWidgets import QApplication, QWidget

# 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

  1. QApplicationManages the control flow and main settings of GUI applications.
  2. QWidgetThe most basic window class, all UI components inherit from it.
  3. setWindowTitle()Sets the window title.
  4. setGeometry()Sets the window position and size.
  5. show()Shows the window.
  6. app.exec_()Starts the event loop and waits for user interaction.

A typical PyQt application consists of the following parts:

  1. QApplication objectEvery PyQt application needs a QApplication instance.
  2. Windows and widgetsUser interface components.
  3. Event loopA loop that handles user input and system events.
  4. Event handlersFunctions or methods that respond to events.

Example

import sys
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

from PyQt5.QtWidgets import QPushButton

button = QPushButton("Click me", window)
button.move(150, 150)  # Set button position

Label (QLabel)

Example

from PyQt5.QtWidgets import QLabel

label = QLabel("Hello PyQt!", window)
label.move(100, 100)

Text Box (QLineEdit)

Example

from PyQt5.QtWidgets import QLineEdit

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

from PyQt5.QtWidgets import QVBoxLayout, QLabel, QPushButton

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

from PyQt5.QtWidgets import QPushButton

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

from PyQt5.QtCore import pyqtSignal, QObject

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

from PyQt5 import uic

# 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

import sys
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 CategoryWidget NameModuleDescription
Basic Window WidgetsQWidgetQtWidgetsBase class for all user interface objects, can be used as an empty window or container.
QMainWindowQtWidgetsMain window framework, containing menu bar, toolbar, status bar, etc.
QDialogQtWidgetsBase class for dialogs, used for pop-up windows.
Layout ManagementQVBoxLayoutQtWidgetsVertical layout manager
QHBoxLayoutQtWidgetsHorizontal layout manager
QGridLayoutQtWidgetsGrid layout manager
QFormLayoutQtWidgetsForm layout manager (label + input field pairs)
Button ClassesQPushButtonQtWidgetsNormal button
QRadioButtonQtWidgetsRadio button
QCheckBoxQtWidgetsCheckbox
QToolButtonQtWidgetsToolbar button (can have icon)
Input WidgetsQLineEditQtWidgetsSingle-line text input box
QTextEditQtWidgetsMulti-line rich text editor (supports HTML)
QPlainTextEditQtWidgetsMulti-line plain text editor
QSpinBoxQtWidgetsSpin box (integer)
QDoubleSpinBoxQtWidgetsSpin box (float)
QComboBoxQtWidgetsDropdown selection box
QDateEditQtWidgetsDate selection box
QTimeEditQtWidgetsTime selection box
QDateTimeEditQtWidgetsDate-time selection box
QSliderQtWidgetsSlider (horizontal/vertical)
QDialQtWidgetsCircular knob control
Display WidgetsQLabelQtWidgetsText/image label
QLCDNumberQtWidgetsLCD digital display
QProgressBarQtWidgetsProgress bar
QStatusBarQtWidgetsStatus bar (usually used forQMainWindow)
Container ClassesQGroupBoxQtWidgetsGroup box (container with title)
QTabWidgetQtWidgetsTab container
QStackedWidgetQtWidgetsStacked container (displays one child widget at a time)
QScrollAreaQtWidgetsScroll area container
QMdiAreaQtWidgetsMDI (Multiple Document Interface) area
List/Table/TreeQListWidgetQtWidgetsList control (with item management)
QTreeWidgetQtWidgetsTree widget
QTableWidgetQtWidgetsTable widget
QListViewQtWidgetsList view (requires a data model)
QTableViewQtWidgetsTable view (requires a data model)
QTreeViewQtWidgetsTree view (requires a data model)
Menu/ToolbarQMenuBarQtWidgetsMenu bar
QMenuQtWidgetsMenu (can contain submenus and actions)
QToolBarQtWidgetsToolbar
QActionQtWidgetsAction (used for menu items, toolbar buttons, etc.)
DialogQFileDialogQtWidgetsFile selection dialog
QColorDialogQtWidgetsColor selection dialog
QFontDialogQtWidgetsFont selection dialog
QInputDialogQtWidgetsInput dialog (text, numbers, etc.)
QMessageBoxQtWidgetsMessage box (warning, error, question, etc.)
Graphics viewQGraphicsViewQtWidgetsGraphics View Framework (for 2D graphics)
QGraphicsSceneQtWidgetsGraphics scene (for combinedQGraphicsViewuse)
Other functional componentsQCalendarWidgetQtWidgetsCalendar widget
QSplashScreenQtWidgetsSplash screen
QSystemTrayIconQtWidgetsSystem tray icon
QWebEngineViewQtWebEngineWidgetsWeb browser component (requires separate installationPyQtWebEngine)

Learning Resources

Other extensions