PyQt6 UI Development Rules Skill
Overview
This skill enforces rules for building production-quality PyQt6 desktop applications. The core principles are: strict MVC separation via signals/slots, never blocking the UI thread, centralized theming via QSS, and layout-manager-driven responsive design. These rules prevent the most common PyQt6 failures: frozen UIs, untestable coupling, and platform-specific rendering bugs.
When to Use
- When building new PyQt6 desktop applications
- When refactoring existing PyQt/PySide code to PyQt6
- When debugging frozen or unresponsive Qt UIs
- When implementing custom widgets or complex layouts
- When setting up cross-platform desktop application builds
Iron Laws
- ALWAYS use Qt's signal/slot mechanism for UI-to-logic communication -- direct method calls between UI and business logic layers break MVC separation and cause untestable coupling.
- NEVER perform long-running operations on the main UI thread -- blocking the Qt event loop makes the interface unresponsive and triggers OS "not responding" dialogs.
- ALWAYS apply QSS stylesheets at the QApplication level rather than per-widget -- per-widget inline styles create inconsistent themes and unmaintainable styling sprawl.
- NEVER use absolute pixel coordinates for widget layout -- use Qt layout managers (QVBoxLayout, QHBoxLayout, QGridLayout) to ensure DPI-aware and cross-platform rendering.
- ALWAYS test the UI on all target platforms before release -- PyQt6 rendering, font scaling, and widget sizing differ between Windows, macOS, and Linux.
Anti-Patterns
| Anti-Pattern |
Why It Fails |
Correct Approach |
| Calling business logic directly from UI slots |
Couples UI to logic; makes testing impossible and breaks MVC architecture |
Emit signals from UI; connect to controller/service methods via slot |
| Running network or file I/O on the main thread |
Blocks the Qt event loop; UI freezes until operation completes |
Use QThread, QRunnable, or asyncio with qasync for background operations |
| Hardcoding pixel sizes and positions |
Breaks on high-DPI displays and different OS DPI scaling settings |
Use layout managers and size policies; use logicalDpiX() for DPI-aware sizing |
| Setting styles inline on individual widgets |
Creates visual inconsistency; extremely difficult to theme or maintain |
Define a single QSS stylesheet at QApplication level and use object names/classes |
| Ignoring cross-platform rendering differences |
Widget sizes, fonts, and margins differ significantly between Windows/macOS/Linux |
Test on all target platforms; use platform-conditional logic where rendering diverges |
Workflow
Step 1: Application Architecture (MVC)
# model.py -- Business logic, no Qt dependencies
class DataModel:
def __init__(self):
self._items = []
def add_item(self, item: str) -> bool:
if item and item not in self._items:
self._items.append(item)
return True
return False
# controller.py -- Mediates between Model and View
from PyQt6.QtCore import QObject, pyqtSignal
class Controller(QObject):
items_changed = pyqtSignal(list)
error_occurred = pyqtSignal(str)
def __init__(self, model: DataModel):
super().__init__()
self._model = model
def add_item(self, item: str) -> None:
if self._model.add_item(item):
self.items_changed.emit(self._model._items.copy())
else:
self.error_occurred.emit(f"Could not add: {item}")
Step 2: Signal/Slot Wiring
# view.py -- UI only, connects via signals/slots
from PyQt6.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QLineEdit, QPushButton, QListWidget
class MainView(QMainWindow):
def __init__(self, controller: Controller):
super().__init__()
self._controller = controller
# Wire signals to slots
self._controller.items_changed.connect(self._on_items_changed)
self._controller.error_occurred.connect(self._on_error)
# UI emits to controller -- never calls model directly
self._add_btn.clicked.connect(lambda: self._controller.add_item(self._input.text()))
def _on_items_changed(self, items: list) -> None:
self._list.clear()
self._list.addItems(items)
Step 3: Background Operations
from PyQt6.QtCore import QThread, pyqtSignal
class WorkerThread(QThread):
progress = pyqtSignal(int)
finished_with_result = pyqtSignal(object)
error = pyqtSignal(str)
def __init__(self, task_fn, parent=None):
super().__init__(parent)
self._task_fn = task_fn
def run(self):
try:
result = self._task_fn(self.progress.emit)
self.finished_with_result.emit(result)
except Exception as e:
self.error.emit(str(e))
Step 4: QSS Theming
# Apply at QApplication level
app = QApplication(sys.argv)
app.setStyleSheet(Path("styles/dark-theme.qss").read_text())
# QSS file
"""
QMainWindow {
background-color: #2b2b2b;
color: #e0e0e0;
}
QPushButton {
background-color: #3c3f41;
border: 1px solid #555;
border-radius: 4px;
padding: 6px 16px;
color: #e0e0e0;
}
QPushButton:hover {
background-color: #4c5052;
}
"""
Step 5: Layout Management
# Use layout managers -- never setGeometry() or move()
layout = QVBoxLayout()
layout.addWidget(self._toolbar)
layout.addWidget(self._content, stretch=1) # stretch fills available space
layout.addWidget(self._status_bar)
# For responsive grids
grid = QGridLayout()
grid.addWidget(label, 0, 0)
grid.addWidget(input_field, 0, 1)
grid.setColumnStretch(1, 1) # input stretches, label stays fixed
Complementary Skills
| Skill |
Relationship |
modern-python |
Project setup with uv, ruff, ty, pytest |
python-backend-expert |
Backend service patterns for desktop app backends |
tdd |
Test-driven development for Qt widget testing |
accessibility |
Accessibility audit patterns applicable to desktop apps |
Memory Protocol (MANDATORY)
Before starting:
Read .claude/context/memory/learnings.md for prior PyQt6 patterns and platform-specific workarounds.
After completing: Record any platform-specific rendering issues, signal/slot patterns, or QThread gotchas to .claude/context/memory/learnings.md.
ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.
1---2name: pyqt6-ui-development-rules3description: PyQt6 desktop GUI development rules -- signal/slot architecture, QSS theming, QThread concurrency, layout management, and cross-platform rendering. Enforces MVC separation and responsive UI patterns.4version: 2.0.05category: Languages6agents: [python-pro, developer]7tags: [pyqt6, python, gui, desktop, qt, ui, signals-slots, qss, qthread]8model: sonnet9invoked_by: both10user_invocable: true11tools: [Read, Write, Edit, Bash, Glob, Grep]12globs: ['**/gui/**/*.*', '**/*_ui.py', '**/*_dialog.py', '**/*_window.py']13best_practices:14 - Use Qt signal/slot mechanism for all UI-to-logic communication15 - Never block the main thread with long-running operations16 - Apply QSS stylesheets at the QApplication level for consistent theming17 - Use layout managers instead of absolute pixel coordinates18 - Test on all target platforms before release19error_handling: graceful20streaming: supported21verified: true22lastVerifiedAt: '2026-03-01'23source: builtin24trust_score: 10025provenance_sha: aab9454f75a6421926metadata:27 source: https://skillmd.com/skills/oimiragieo/pyqt6-ui-development-rules28---2930# PyQt6 UI Development Rules Skill3132<identity>33PyQt6 desktop GUI development specialist enforcing MVC separation, signal/slot architecture, QSS theming, threaded concurrency, and cross-platform rendering best practices. Ensures responsive, accessible, and visually consistent desktop applications.34</identity>3536<capabilities>37- Design MVC-separated PyQt6 application architecture38- Implement signal/slot communication patterns between UI and business logic39- Configure QSS application-level theming with dark/light mode support40- Manage background operations with QThread, QRunnable, and QThreadPool41- Build responsive layouts using QVBoxLayout, QHBoxLayout, QGridLayout, and QFormLayout42- Implement custom QWidget subclasses with proper paintEvent handling43- Set up cross-platform DPI-aware rendering44- Configure accessibility features (screen reader support, keyboard navigation)45</capabilities>4647## Overview4849This skill enforces rules for building production-quality PyQt6 desktop applications. The core principles are: strict MVC separation via signals/slots, never blocking the UI thread, centralized theming via QSS, and layout-manager-driven responsive design. These rules prevent the most common PyQt6 failures: frozen UIs, untestable coupling, and platform-specific rendering bugs.5051## When to Use5253- When building new PyQt6 desktop applications54- When refactoring existing PyQt/PySide code to PyQt655- When debugging frozen or unresponsive Qt UIs56- When implementing custom widgets or complex layouts57- When setting up cross-platform desktop application builds5859## Iron Laws60611. **ALWAYS** use Qt's signal/slot mechanism for UI-to-logic communication -- direct method calls between UI and business logic layers break MVC separation and cause untestable coupling.622. **NEVER** perform long-running operations on the main UI thread -- blocking the Qt event loop makes the interface unresponsive and triggers OS "not responding" dialogs.633. **ALWAYS** apply QSS stylesheets at the QApplication level rather than per-widget -- per-widget inline styles create inconsistent themes and unmaintainable styling sprawl.644. **NEVER** use absolute pixel coordinates for widget layout -- use Qt layout managers (QVBoxLayout, QHBoxLayout, QGridLayout) to ensure DPI-aware and cross-platform rendering.655. **ALWAYS** test the UI on all target platforms before release -- PyQt6 rendering, font scaling, and widget sizing differ between Windows, macOS, and Linux.6667## Anti-Patterns6869| Anti-Pattern | Why It Fails | Correct Approach |70| ---------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |71| Calling business logic directly from UI slots | Couples UI to logic; makes testing impossible and breaks MVC architecture | Emit signals from UI; connect to controller/service methods via slot |72| Running network or file I/O on the main thread | Blocks the Qt event loop; UI freezes until operation completes | Use QThread, QRunnable, or asyncio with qasync for background operations |73| Hardcoding pixel sizes and positions | Breaks on high-DPI displays and different OS DPI scaling settings | Use layout managers and size policies; use `logicalDpiX()` for DPI-aware sizing |74| Setting styles inline on individual widgets | Creates visual inconsistency; extremely difficult to theme or maintain | Define a single QSS stylesheet at QApplication level and use object names/classes |75| Ignoring cross-platform rendering differences | Widget sizes, fonts, and margins differ significantly between Windows/macOS/Linux | Test on all target platforms; use platform-conditional logic where rendering diverges |7677## Workflow7879### Step 1: Application Architecture (MVC)8081```python82# model.py -- Business logic, no Qt dependencies83class DataModel:84 def __init__(self):85 self._items = []8687 def add_item(self, item: str) -> bool:88 if item and item not in self._items:89 self._items.append(item)90 return True91 return False9293# controller.py -- Mediates between Model and View94from PyQt6.QtCore import QObject, pyqtSignal9596class Controller(QObject):97 items_changed = pyqtSignal(list)98 error_occurred = pyqtSignal(str)99100 def __init__(self, model: DataModel):101 super().__init__()102 self._model = model103104 def add_item(self, item: str) -> None:105 if self._model.add_item(item):106 self.items_changed.emit(self._model._items.copy())107 else:108 self.error_occurred.emit(f"Could not add: {item}")109```110111### Step 2: Signal/Slot Wiring112113```python114# view.py -- UI only, connects via signals/slots115from PyQt6.QtWidgets import QMainWindow, QVBoxLayout, QWidget, QLineEdit, QPushButton, QListWidget116117class MainView(QMainWindow):118 def __init__(self, controller: Controller):119 super().__init__()120 self._controller = controller121122 # Wire signals to slots123 self._controller.items_changed.connect(self._on_items_changed)124 self._controller.error_occurred.connect(self._on_error)125126 # UI emits to controller -- never calls model directly127 self._add_btn.clicked.connect(lambda: self._controller.add_item(self._input.text()))128129 def _on_items_changed(self, items: list) -> None:130 self._list.clear()131 self._list.addItems(items)132```133134### Step 3: Background Operations135136```python137from PyQt6.QtCore import QThread, pyqtSignal138139class WorkerThread(QThread):140 progress = pyqtSignal(int)141 finished_with_result = pyqtSignal(object)142 error = pyqtSignal(str)143144 def __init__(self, task_fn, parent=None):145 super().__init__(parent)146 self._task_fn = task_fn147148 def run(self):149 try:150 result = self._task_fn(self.progress.emit)151 self.finished_with_result.emit(result)152 except Exception as e:153 self.error.emit(str(e))154```155156### Step 4: QSS Theming157158```python159# Apply at QApplication level160app = QApplication(sys.argv)161app.setStyleSheet(Path("styles/dark-theme.qss").read_text())162163# QSS file164"""165QMainWindow {166 background-color: #2b2b2b;167 color: #e0e0e0;168}169QPushButton {170 background-color: #3c3f41;171 border: 1px solid #555;172 border-radius: 4px;173 padding: 6px 16px;174 color: #e0e0e0;175}176QPushButton:hover {177 background-color: #4c5052;178}179"""180```181182### Step 5: Layout Management183184```python185# Use layout managers -- never setGeometry() or move()186layout = QVBoxLayout()187layout.addWidget(self._toolbar)188layout.addWidget(self._content, stretch=1) # stretch fills available space189layout.addWidget(self._status_bar)190191# For responsive grids192grid = QGridLayout()193grid.addWidget(label, 0, 0)194grid.addWidget(input_field, 0, 1)195grid.setColumnStretch(1, 1) # input stretches, label stays fixed196```197198## Complementary Skills199200| Skill | Relationship |201| ----------------------- | ------------------------------------------------------- |202| `modern-python` | Project setup with uv, ruff, ty, pytest |203| `python-backend-expert` | Backend service patterns for desktop app backends |204| `tdd` | Test-driven development for Qt widget testing |205| `accessibility` | Accessibility audit patterns applicable to desktop apps |206207## Memory Protocol (MANDATORY)208209**Before starting:**210211Read `.claude/context/memory/learnings.md` for prior PyQt6 patterns and platform-specific workarounds.212213**After completing:** Record any platform-specific rendering issues, signal/slot patterns, or QThread gotchas to `.claude/context/memory/learnings.md`.214215> ASSUME INTERRUPTION: Your context may reset. If it's not in memory, it didn't happen.