SoFunction
Updated on 2025-04-13

Detailed explanation of PyQt in Python GUI framework

PyQt is one of the most powerful and widely used GUI frameworks in the Python language, and is based on the Python binding implementation of the Qt library. ThatModular architectureandCross-platform features(Windows, macOS, Linux) makes it an ideal choice for developing desktop applications. This article will analyze the core modules of PyQt in depth and display its application scenarios through code examples.

1. Overview of PyQt core modules

PyQt divides the Qt function into multiple submodules, each focusing on functional implementations in a specific field. The following are the main modules and their functions:

Module name Function description Typical application scenarios
QtCore Core non-GUI features Signal slot, file processing, multi-threading
QtGui Graphics Component Basics Drawing, font, image processing
QtWidgets UI Control Library Window, buttons, input boxes and other controls
QtNetwork Network communication HTTP request, TCP/UDP communication
QtSql Database interaction SQL query, transaction management
QtMultimedia Multimedia processing Audio playback, video streaming processing
QtWebEngine Web Rendering Embed browser and web content display
QtCharts Data visualization Line chart, bar chart, pie chart

2. Detailed explanation and examples of core modules

1. QtCore - Core Basic Module

Provide basic functions such asObject communication mechanism (signal and slot)Event loopandFile processing

Key Category:

  • QObject: Base class of all Qt objects
  • QTimer: Timer
  • QFile: File operation
  • QThread: Multi-threaded support

Example: Timed update interface

from  import QTimer, QObject, pyqtSignal
class Worker(QObject):
    update_signal = pyqtSignal(str)
    def __init__(self):
        super().__init__()
         = QTimer()
        (self.update_time)
    def update_time(self):
        from datetime import datetime
        self.update_signal.emit(().strftime("%H:%M:%S"))
    def start(self):
        (1000)  # Triggered every second

2. QtWidgets - UI Control Library

The core module for building the user interface, including40+ types of prefabricated controls

Key Components:

  • QApplication: Apply the main loop
  • QMainWindow: Main window frame
  • QPushButton: Button
  • QLabel: Text tags
  • QLineEdit: Single line input box

Example: Create a basic window

 
from  import QApplication, QMainWindow, QPushButton
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        ("PyQt Demo")
        (100, 100, 400, 300)
        btn = QPushButton("Click Me", self)
        (150, 150)
        (self.on_click)
    def on_click(self):
        print("The button is clicked!")
if __name__ == "__main__":
    app = QApplication([])
    window = MainWindow()
    ()
    app.exec_()

3. QtGui - Graphics Processing

deal withDrawingFont managementandImage operationbasic module.

Core functions:

  • QPainter: 2D drawing
  • QFont: Font management
  • QPixmap: Image processing

Example: Custom drawing

from  import QWidget
from  import QPainter, QColor
class Canvas(QWidget):
    def paintEvent(self, event):
        painter = QPainter(self)
        (QColor(255, 0, 0))
        (50, 50, 100, 100)  # Draw a red circle

4. QtNetwork - Network Communication

accomplishHTTP RequestTCP/UDP communicationand other network functions.

Example: HTTP GET Request

from  import QNetworkAccessManager, QNetworkRequest
from  import QUrl
class Downloader:
    def __init__(self):
         = QNetworkAccessManager()
        (self.handle_response)
    def fetch(self, url):
        request = QNetworkRequest(QUrl(url))
        (request)
    def handle_response(self, reply):
        data = ()
        print(f"receive {len(data)} Byte data")

5. QtSql - Database Interaction

Supports multiple databases (SQLite, MySQL, PostgreSQL, etc.)Unified interface

Example: SQLite operation

 
from  import QSqlDatabase, QSqlQuery
# Create a database connectiondb = ("QSQLITE")
("")
if ():
    query = QSqlQuery()
    query.exec_("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)")
    query.exec_("INSERT INTO users (name) VALUES ('Alice')")
    ()

6. QtWebEngine - Web Rendering

Chromium-basedModern web rendering engine

Example: Embed browser

 
from  import QWebEngineView
from  import QMainWindow
class BrowserWindow(QMainWindow):
    def __init__(self):
        super().__init__()
         = QWebEngineView()
        ()
        (QUrl(""))

3. Comprehensive application examples

Combining multiple modules to create a weather query application:

# Complete examples containing network requests, UI controls, and JSON parsingimport sys
import json
from  import (QApplication, QWidget, QVBoxLayout, 
                             QLineEdit, QLabel, QPushButton)
from  import QNetworkAccessManager
class WeatherApp(QWidget):
    def __init__(self):
        super().__init__()
         = QNetworkAccessManager()
        (self.handle_response)
        self.init_ui()
    def init_ui(self):
        layout = QVBoxLayout()
        self.city_input = QLineEdit("Input City")
        self.result_label = QLabel("Waiting for inquiry...")
        btn = QPushButton("Inquiry of the weather")
        (self.query_weather)
        (self.city_input)
        (btn)
        (self.result_label)
        (layout)
    def query_weather(self):
        city = self.city_input.text()
        url = f"/{city}"
        (QNetworkRequest(QUrl(url)))
    def handle_response(self, reply):
        data = (().data())
        temp = data['main']['temp']
        self.result_label.setText(f"Current temperature:{temp}°C")
if __name__ == "__main__":
    app = QApplication()
    window = WeatherApp()
    ()
    (app.exec_())

4. PyQt version selection suggestions

  • PyQt5: Current mainstream stable version (recommended)
  • PyQt6: Latest version, some APIs have been adjusted

Installation command:

pip install pyqt5  # Basic installationpip install pyqt5-tools  # IncludeQt DesignerPlease help with tools

5. Recommended learning resources

Official Documentation:PyQt5 Reference Guide — PyQt Documentation v5.15.7

Qt Designer Tutorial: Visual UI Design Tools

Books "PyQt5 Rapid Development and Practical Practice"

GitHub open source project reference

This is the end of this article about the detailed explanation of PyQt of Python GUI framework. For more related content of Python GUI framework, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!