Widgets

From CodeAtCode/oss-ai-skills · View interactive version

Widgets is an AI agent skill from the GitHub repository CodeAtCode/oss-ai-skills. Use when building PyQt/PySide6 UIs with QtWidgets - display, input and container widgets, buttons, item views like QListWidget and QTableWidget, layout management, or event handling (mouse/keyboard events, event filters, shortcuts)

How to use this skill

Skill file

Objective: Use this skill to reduce layout-breakage incidents (setGeometry + resize conflicts), event-handler bugs (missed accept()/ignore() calls), model-view sync failures (stale item references), and keyboard-shortcut conflicts (global filter overuse) by enforcing layout discipline, event-filter patterns, and model-view contract rules below.

PyQt Widgets - QtWidgets Module

Widget Selection Guide

Display Widgets

QLabel - Use for showing text or images. Choose when:

Pitfall: Don't use QLabel for editable content - use QLineEdit or QTextEdit instead.

See widgets-api.md for complete QLabel API.

QProgressBar - Use for visual progress indication. Choose when:

Pitfall: Don't forget to update the value asynchronously for long operations.

See widgets-api.md for complete QProgressBar API.

QLCDNumber - Use for numeric display with digital appearance. Choose when:

Pitfall: Limited use cases - most numeric displays are better with QLabel.

See widgets-api.md for complete QLCDNumber API.

Input Widgets

QLineEdit - Use for single-line text input. Choose when:

Pitfall: Don't use for multi-line text - use QTextEdit instead.

See widgets-api.md for complete QLineEdit API.

QTextEdit - Use for multi-line rich text editing. Choose when:

Pitfall: Plain text operations use toPlainText()/setPlainText(), HTML uses toHtml()/setHtml() - don't mix.

See widgets-api.md for complete QTextEdit API.

QSpinBox/QDoubleSpinBox - Use for numeric input with constraints. Choose when:

Pitfall: Don't forget to set reasonable min/max values to prevent overflow.

See widgets-api.md for complete spin box API.

QComboBox - Use for dropdown selection. Choose when:

Pitfall: Use currentIndexChanged for index changes, currentTextChanged for text changes - they fire separately.

See widgets-api.md for complete QComboBox API.

QCheckBox - Use for boolean or tristate options. Choose when:

Pitfall: stateChanged fires for all three states in tristate mode; toggled only for checked/unchecked.

See widgets-api.md for complete QCheckBox API.

QRadioButton - Use for mutually exclusive selection. Choose when:

Pitfall: Group radio buttons with QButtonGroup or same parent for exclusivity.

See widgets-api.md for complete QRadioButton API.

QSlider - Use for continuous or stepped value selection. Choose when:

Pitfall: Don't use for precise input - pair with QSpinBox for exact value display.

See widgets-api.md for complete QSlider API.

Buttons

QPushButton - Use for command execution. Choose when:

Pitfall: Use clicked for action, pressed/released for visual feedback control.

See widgets-api.md for complete QPushButton API.

QToolButton - Use for toolbar or compact icon buttons. Choose when:

Pitfall: Not ideal for main action buttons - use QPushButton for primary actions.

See widgets-api.md for complete QToolButton API.

Container Widgets

QGroupBox - Use for visual grouping of related controls. Choose when:

Pitfall: Remember to add a layout to the group box, not just widgets.

See widgets-api.md for complete QGroupBox API.

QTabWidget - Use for tabbed interfaces. Choose when:

Pitfall: Use currentChanged to react to tab switches; don't store state in tab widgets directly.

See widgets-api.md for complete QTabWidget API.

QScrollArea - Use for scrolling content. Choose when:

Pitfall: Always set setWidgetResizable(True) unless you need precise scroll control.

See widgets-api.md for complete QScrollArea API.

QSplitter - Use for resizable panes. Choose when:

Pitfall: Set setChildrenCollapsible(False) if a pane must have minimum content.

See widgets-api.md for complete QSplitter API.

QStackedWidget - Use for page-based navigation. Choose when:

Pitfall: Use setCurrentIndex() or setCurrentWidget() - don't rely on user navigation.

See widgets-api.md for complete QStackedWidget API.

Layout Discipline

Do use layouts, not setGeometry, because resize events break fixed positions.

# ✅ GOOD: Layouts adapt to resize
layout = QVBoxLayout()
layout.addWidget(button)
layout.setStretchFactor(widget, 1)  # Proportional sizing
# ❌ BAD: Hardcoded positions fail on resize
button.setGeometry(10, 10, 100, 30)

Do set size policies instead of fixed sizes because layouts need growth hints.

from PySide6.QtWidgets import QSizePolicy

widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)

Event Handling

See references/event-handling.md for event handlers, event filters, and shortcuts.

Do call event.accept() in handlers because unaccepted events propagate up the tree.

class MyWidget(QWidget):
    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            print("Left click at", event.pos())
        event.accept()  # Stop propagation

Do call event.ignore() in closeEvent because ignoring keeps the widget open.

def closeEvent(self, event):
    reply = QMessageBox.question(
        self, 'Exit',
        'Are you sure?',
        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
    )
    if reply == QMessageBox.StandardButton.Yes:
        event.accept()
    else:
        event.ignore()  # Widget stays open

Do install event filters on specific targets because global filters intercept every event and kill performance.

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.textEdit.installEventFilter(self)  # Target-specific
    
    def eventFilter(self, obj, event):
        if obj == self.textEdit and event.type() == QEvent.Type.KeyPress:
            if event.key() == Qt.Key.Key_Tab:
                return True  # Consumed
        return super().eventFilter(obj, event)

Model-View Contract

See references/item-views-layouts.md for QListWidget, QTreeWidget, QTableWidget, and layout management.

Do use data() / setData() for custom data because text() only stores display strings.

item.setData(Qt.ItemDataRole.UserRole, {"id": 123})
data = item.data(Qt.ItemDataRole.UserRole)

Do check for None before accessing table items because empty cells return None.

item = table.item(0, 0)
text = item.text() if item else ""  # Avoid crash on empty cell

State Management

Do centralize state in a dedicated class because scattered widget state creates sync bugs.

class AppState:
    def __init__(self):
        self.data_changed = Signal()
        
state = AppState()
# Connect to signal for updates

Deep Dives

See references for detailed content loaded on demand:

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.