Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions python-pyqt-qthread/README.md
Original file line number Diff line number Diff line change
@@ -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
```
92 changes: 92 additions & 0 deletions python-pyqt-qthread/account_manager.py
Original file line number Diff line number Diff line change
@@ -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())
65 changes: 65 additions & 0 deletions python-pyqt-qthread/freezing_gui.py
Original file line number Diff line number Diff line change
@@ -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())
69 changes: 69 additions & 0 deletions python-pyqt-qthread/qrunnable_example.py
Original file line number Diff line number Diff line change
@@ -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())
1 change: 1 addition & 0 deletions python-pyqt-qthread/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
PyQt6==6.12.1
96 changes: 96 additions & 0 deletions python-pyqt-qthread/responsive_gui.py
Original file line number Diff line number Diff line change
@@ -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())
Loading