From 2b3f060830d8bbd38c64fb6274575b6f6d22b742 Mon Sep 17 00:00:00 2001 From: Real Python Bot <42617967+realpython-bot@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:38:58 +0000 Subject: [PATCH] Add python-pyqt-qthread materials folder Code examples for the PyQt6 update of "Use PyQt's QThread to Prevent Freezing GUIs". --- python-pyqt-qthread/README.md | 28 +++++++ python-pyqt-qthread/account_manager.py | 92 +++++++++++++++++++++++ python-pyqt-qthread/freezing_gui.py | 65 ++++++++++++++++ python-pyqt-qthread/qrunnable_example.py | 69 +++++++++++++++++ python-pyqt-qthread/requirements.txt | 1 + python-pyqt-qthread/responsive_gui.py | 96 ++++++++++++++++++++++++ 6 files changed, 351 insertions(+) create mode 100644 python-pyqt-qthread/README.md create mode 100644 python-pyqt-qthread/account_manager.py create mode 100644 python-pyqt-qthread/freezing_gui.py create mode 100644 python-pyqt-qthread/qrunnable_example.py create mode 100644 python-pyqt-qthread/requirements.txt create mode 100644 python-pyqt-qthread/responsive_gui.py diff --git a/python-pyqt-qthread/README.md b/python-pyqt-qthread/README.md new file mode 100644 index 0000000000..390252e849 --- /dev/null +++ b/python-pyqt-qthread/README.md @@ -0,0 +1,28 @@ +# Use PyQt's QThread to Prevent Freezing GUIs + +This folder provides the code examples for the Real Python tutorial [Use PyQt's QThread to Prevent Freezing GUIs](https://realpython.com/python-pyqt-qthread/). + +## Setup + +You need Python 3.10 or later. Create and activate a virtual environment, then install the pinned dependencies: + +```console +$ python -m venv venv/ +$ source venv/bin/activate +(venv) $ python -m pip install -r requirements.txt +``` + +## Usage + +Each script is a standalone PyQt6 application: + +- `freezing_gui.py`: a GUI that freezes while it runs a long task in the main thread +- `responsive_gui.py`: the same GUI, now responsive because a `QThread` runs the task in a worker +- `qrunnable_example.py`: runs several tasks in the global `QThreadPool` with `QRunnable` +- `account_manager.py`: protects a shared bank account balance with `QMutex` + +Run any of them from your terminal: + +```console +(venv) $ python responsive_gui.py +``` diff --git a/python-pyqt-qthread/account_manager.py b/python-pyqt-qthread/account_manager.py new file mode 100644 index 0000000000..10a819ced2 --- /dev/null +++ b/python-pyqt-qthread/account_manager.py @@ -0,0 +1,92 @@ +import logging +import random +import sys +from time import sleep + +from PyQt6.QtCore import QMutex, QObject, QThread, pyqtSignal +from PyQt6.QtWidgets import ( + QApplication, + QLabel, + QMainWindow, + QPushButton, + QVBoxLayout, + QWidget, +) + +logging.basicConfig(format="%(message)s", level=logging.INFO) + +balance = 100.00 +mutex = QMutex() + + +class AccountManager(QObject): + finished = pyqtSignal() + updatedBalance = pyqtSignal() + + def withdraw(self, person, amount): + logging.info("%s wants to withdraw $%.2f...", person, amount) + global balance + mutex.lock() + if balance - amount >= 0: + sleep(1) + balance -= amount + logging.info("-$%.2f accepted", amount) + else: + logging.info("-$%.2f rejected", amount) + logging.info("===Balance===: $%.2f", balance) + self.updatedBalance.emit() + mutex.unlock() + self.finished.emit() + + +class Window(QMainWindow): + def __init__(self, parent=None): + super().__init__(parent) + self.setupUi() + self.threads = [] + + def setupUi(self): + self.setWindowTitle("Account Manager") + self.resize(200, 150) + self.centralWidget = QWidget() + self.setCentralWidget(self.centralWidget) + button = QPushButton("Withdraw Money!") + button.clicked.connect(self.startThreads) + self.balanceLabel = QLabel(f"Current Balance: ${balance:,.2f}") + layout = QVBoxLayout() + layout.addWidget(self.balanceLabel) + layout.addWidget(button) + self.centralWidget.setLayout(layout) + + def createThread(self, person, amount): + thread = QThread() + worker = AccountManager() + worker.moveToThread(thread) + thread.started.connect(lambda: worker.withdraw(person, amount)) + worker.updatedBalance.connect(self.updateBalance) + worker.finished.connect(thread.quit) + worker.finished.connect(worker.deleteLater) + thread.finished.connect(thread.deleteLater) + return thread + + def updateBalance(self): + self.balanceLabel.setText(f"Current Balance: ${balance:,.2f}") + + def startThreads(self): + self.threads.clear() + people = { + "Alice": random.randint(100, 10000) / 100, + "Bob": random.randint(100, 10000) / 100, + } + self.threads = [ + self.createThread(person, amount) + for person, amount in people.items() + ] + for thread in self.threads: + thread.start() + + +app = QApplication(sys.argv) +window = Window() +window.show() +sys.exit(app.exec()) diff --git a/python-pyqt-qthread/freezing_gui.py b/python-pyqt-qthread/freezing_gui.py new file mode 100644 index 0000000000..f2e4c2b752 --- /dev/null +++ b/python-pyqt-qthread/freezing_gui.py @@ -0,0 +1,65 @@ +import sys +from time import sleep + +from PyQt6.QtCore import Qt +from PyQt6.QtWidgets import ( + QApplication, + QLabel, + QMainWindow, + QPushButton, + QVBoxLayout, + QWidget, +) + + +class Window(QMainWindow): + def __init__(self, parent=None): + super().__init__(parent) + self.clicksCount = 0 + self.setupUi() + + def setupUi(self): + self.setWindowTitle("Freezing GUI") + self.resize(300, 150) + self.centralWidget = QWidget() + self.setCentralWidget(self.centralWidget) + # Create and connect widgets + self.clicksLabel = QLabel("Counting: 0 clicks", self) + self.clicksLabel.setAlignment( + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + ) + self.stepLabel = QLabel("Long-Running Step: 0") + self.stepLabel.setAlignment( + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + ) + self.countBtn = QPushButton("Click me!", self) + self.countBtn.clicked.connect(self.countClicks) + self.longRunningBtn = QPushButton("Long-Running Task!", self) + self.longRunningBtn.clicked.connect(self.runLongTask) + # Set the layout + layout = QVBoxLayout() + layout.addWidget(self.clicksLabel) + layout.addWidget(self.countBtn) + layout.addStretch() + layout.addWidget(self.stepLabel) + layout.addWidget(self.longRunningBtn) + self.centralWidget.setLayout(layout) + + def countClicks(self): + self.clicksCount += 1 + self.clicksLabel.setText(f"Counting: {self.clicksCount} clicks") + + def reportProgress(self, n): + self.stepLabel.setText(f"Long-Running Step: {n}") + + def runLongTask(self): + """Long-running task in 5 steps.""" + for i in range(5): + sleep(1) + self.reportProgress(i + 1) + + +app = QApplication(sys.argv) +win = Window() +win.show() +sys.exit(app.exec()) diff --git a/python-pyqt-qthread/qrunnable_example.py b/python-pyqt-qthread/qrunnable_example.py new file mode 100644 index 0000000000..49f4935ce0 --- /dev/null +++ b/python-pyqt-qthread/qrunnable_example.py @@ -0,0 +1,69 @@ +import logging +import random +import sys +import time + +from PyQt6.QtCore import QRunnable, Qt, QThreadPool +from PyQt6.QtWidgets import ( + QApplication, + QLabel, + QMainWindow, + QPushButton, + QVBoxLayout, + QWidget, +) + +logging.basicConfig(format="%(message)s", level=logging.INFO) + + +# 1. Subclass QRunnable +class Runnable(QRunnable): + def __init__(self, n): + super().__init__() + self.n = n + + def run(self): + # Your long-running task goes here ... + for i in range(5): + logging.info(f"Working in thread {self.n}, step {i + 1}/5") + time.sleep(random.randint(700, 2500) / 1000) + + +class Window(QMainWindow): + def __init__(self, parent=None): + super().__init__(parent) + self.setupUi() + + def setupUi(self): + self.setWindowTitle("QThreadPool + QRunnable") + self.resize(250, 150) + self.centralWidget = QWidget() + self.setCentralWidget(self.centralWidget) + # Create and connect widgets + self.label = QLabel("Hello, World!") + self.label.setAlignment( + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + ) + countBtn = QPushButton("Click me!") + countBtn.clicked.connect(self.runTasks) + # Set the layout + layout = QVBoxLayout() + layout.addWidget(self.label) + layout.addWidget(countBtn) + self.centralWidget.setLayout(layout) + + def runTasks(self): + threadCount = QThreadPool.globalInstance().maxThreadCount() + self.label.setText(f"Running {threadCount} Threads") + pool = QThreadPool.globalInstance() + for i in range(threadCount): + # 2. Instantiate the subclass of QRunnable + runnable = Runnable(i) + # 3. Call start() + pool.start(runnable) + + +app = QApplication(sys.argv) +window = Window() +window.show() +sys.exit(app.exec()) diff --git a/python-pyqt-qthread/requirements.txt b/python-pyqt-qthread/requirements.txt new file mode 100644 index 0000000000..54b5e02f59 --- /dev/null +++ b/python-pyqt-qthread/requirements.txt @@ -0,0 +1 @@ +PyQt6==6.12.1 diff --git a/python-pyqt-qthread/responsive_gui.py b/python-pyqt-qthread/responsive_gui.py new file mode 100644 index 0000000000..2e0e6e0860 --- /dev/null +++ b/python-pyqt-qthread/responsive_gui.py @@ -0,0 +1,96 @@ +import sys +from time import sleep + +from PyQt6.QtCore import QObject, Qt, QThread, pyqtSignal +from PyQt6.QtWidgets import ( + QApplication, + QLabel, + QMainWindow, + QPushButton, + QVBoxLayout, + QWidget, +) + + +class Worker(QObject): + finished = pyqtSignal() + progress = pyqtSignal(int) + + def run(self): + """Long-running task.""" + for i in range(5): + sleep(1) + self.progress.emit(i + 1) + self.finished.emit() + + +class Window(QMainWindow): + def __init__(self, parent=None): + super().__init__(parent) + self.clicksCount = 0 + self.setupUi() + + def setupUi(self): + self.setWindowTitle("Freezing GUI") + self.resize(300, 150) + self.centralWidget = QWidget() + self.setCentralWidget(self.centralWidget) + # Create and connect widgets + self.clicksLabel = QLabel("Counting: 0 clicks", self) + self.clicksLabel.setAlignment( + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + ) + self.stepLabel = QLabel("Long-Running Step: 0") + self.stepLabel.setAlignment( + Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignVCenter + ) + self.countBtn = QPushButton("Click me!", self) + self.countBtn.clicked.connect(self.countClicks) + self.longRunningBtn = QPushButton("Long-Running Task!", self) + self.longRunningBtn.clicked.connect(self.runLongTask) + # Set the layout + layout = QVBoxLayout() + layout.addWidget(self.clicksLabel) + layout.addWidget(self.countBtn) + layout.addStretch() + layout.addWidget(self.stepLabel) + layout.addWidget(self.longRunningBtn) + self.centralWidget.setLayout(layout) + + def countClicks(self): + self.clicksCount += 1 + self.clicksLabel.setText(f"Counting: {self.clicksCount} clicks") + + def reportProgress(self, n): + self.stepLabel.setText(f"Long-Running Step: {n}") + + def runLongTask(self): + # Step 2: Create a QThread object + self.thread = QThread() + # Step 3: Create a worker object + self.worker = Worker() + # Step 4: Move worker to the thread + self.worker.moveToThread(self.thread) + # Step 5: Connect signals and slots + self.thread.started.connect(self.worker.run) + self.worker.finished.connect(self.thread.quit) + self.worker.finished.connect(self.worker.deleteLater) + self.thread.finished.connect(self.thread.deleteLater) + self.worker.progress.connect(self.reportProgress) + # Step 6: Start the thread + self.thread.start() + + # Final resets + self.longRunningBtn.setEnabled(False) + self.thread.finished.connect( + lambda: self.longRunningBtn.setEnabled(True) + ) + self.thread.finished.connect( + lambda: self.stepLabel.setText("Long-Running Step: 0") + ) + + +app = QApplication(sys.argv) +win = Window() +win.show() +sys.exit(app.exec())