Логотип Pyqt Threading

Pyqt Threading

Організація
CodeAtCode
pyqt-threading

Use when handling PyQt/PySide6 threading - QThread patterns, QThreadPool/QRunnable, thread safety rules, moveToThread, Qt Concurrent, QTimer, testing threaded code, lifecycle management

Огляд

ВидавецьCodeAtCode
Репозиторійoss-ai-skills
Назва навичкиpyqt-threading
Зірки
30
Форки
3
Файли в пакеті
5
ЛіцензіяGPL-3.0
Посилання
  • Інструкції у форматі Markdown

    Файл SKILL.md, який модель завантажує за потреби, тож токени витрачаються лише тоді, коли запит справді відповідає навичці.

  • Працює з будь-якою LLM

    Навички ШІ — це звичайний Markdown, а не код для певного постачальника, тому вони працюють із GPT, Claude, Gemini, Grok або локальною моделлю.

  • Файлів у комплекті: 5

    Скрипти, шаблони й довідкові матеріали, які модель може читати під час роботи. Файли доступні лише для читання й ніколи не виконуються.

  • Відкритий вихідний код

    Опубліковано на GitHub користувачем CodeAtCode. Перегляньте вихідний вміст перед установленням.

Встановлення

Установіть навичку ШІ Pyqt Threading у TypingMind, щоб використовувати її з будь-якою LLM, або додайте її до іншого агента, що читає SKILL.md.

1

Встановити в TypingMind

TypingMind встановлює навичку безпосередньо з її папки GitHub — читає SKILL.md, збирає файли ресурсів у пакет і зберігає результат локально.

  1. Відкрийте застосунок і перейдіть до Плагіни → Навички.
  2. Виберіть «Встановити з GitHub».
  3. Вставте наведений нижче URL папки навички та підтвердьте встановлення.
    https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pyqt/threading
  4. Увімкніть навичку в кожному чаті, де хочете її використовувати.
Плагіни → Навички → Нова навичка → За URL GitHub, потім вставте URL папки й натисніть «Продовжити».
2

Встановити в іншому агенті

Будь-який агент, що підтримує формат Agent Skills, може використовувати цю навичку — скопіюйте папку до каталогу навичок цього агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CodeAtCode/oss-ai-skills.git /tmp/oss-ai-skills
mkdir -p .claude/skills
cp -r /tmp/oss-ai-skills/frameworks/pyqt/threading .claude/skills/pyqt-threading
Після копіювання перезапустіть Claude Code, щоб завантажити нову навичку.

Використовуйте навичку в TypingMind

Увімкніть навичку Pyqt Threading в будь-якому чаті TypingMind, і далі модель усе зробить сама. Назва й опис навички містяться в системному промпті, а щойно надходить відповідний запит, модель самостійно завантажує повні інструкції — вам не потрібно викликати навичку вручну, і до фактичного використання вона не витрачає токенів.

Модель самостійно завантажує навичку Pyqt Threading, щойно надходить відповідний запит.

Працює з будь-якою моделлю ШІ

Навички ШІ — це звичайні інструкції Markdown, а не код для певного постачальника, тому навичка Pyqt Threading не прив’язана до моделі, для якої її створено. Установіть її один раз у TypingMind і використовуйте з GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama або локальною моделлю, яку ви запускаєте самостійно, — усе з вашими власними ключами API.

  • Завантажується лише за потреби

    Системний промпт містить лише назву й опис. Інструкції завантажуються за першого відповідного запиту, тож невикористана навичка нічого не коштує.

  • Змінюйте моделі під час чату

    Оскільки навичка — це інструкції, а не код, зміна моделі не порушує її роботу: наступна модель читає той самий файл SKILL.md.

Інструкції навички

Це вміст файлу SKILL.md, який завантажує модель. Прочитайте його перед установленням — навичка містить інструкції, яких дотримуватиметься ваша модель.

Objective: Use this skill to prevent UI freezes, cross-thread crashes, and thread-leak memory bugs by enforcing the worker-object pattern, queued signal connections, and proper thread lifecycle cleanup.

PyQt Threading - Core Patterns

Thread Safety Rules

CRITICAL: Qt/PyQt is NOT thread-safe for UI operations. You MUST follow these rules:

  1. Never access widgets from worker threads - Only the main thread can modify UI
  2. Use signals for cross-thread communication - Emit signals from worker, connect to slots in main thread
  3. Use Qt.QueuedConnection for thread-safe signal delivery - AutoConnection handles this automatically
  4. Never block the main thread - Long operations will freeze the UI
python
# ❌ WRONG: Direct UI access from thread
class BadWorker(QThread):
    def run(self):
        # This will crash or cause undefined behavior!
        self.label.setText("Done")

# ✅ CORRECT: Use signals
class GoodWorker(QThread):
    finished = Signal(str)
    
    def run(self):
        result = self.process_data()
        self.finished.emit(result)  # Signal emitted, UI updated in main thread

QThread with Worker Object (Recommended Pattern)

The most flexible pattern separates the worker logic from thread lifecycle:

python
from PySide6.QtCore import QThread, Signal, QObject, Slot

class Worker(QObject):
    """Worker object that does the actual work."""
    finished = Signal(object)
    progress = Signal(int)
    error = Signal(str)
    
    def __init__(self, data):
        super().__init__()
        self.data = data
        self._is_cancelled = False
    
    @Slot()
    def process(self):
        """Main processing method called from thread."""
        try:
            for i, item in enumerate(self.data):
                if self._is_cancelled:
                    return
                
                # Simulate heavy work
                result = self.process_item(item)
                self.progress.emit(int((i + 1) / len(self.data) * 100))
            
            self.finished.emit({"status": "success", "count": len(self.data)})
        except Exception as e:
            self.error.emit(str(e))
    
    def cancel(self):
        self._is_cancelled = True
    
    def process_item(self, item):
        import time
        time.sleep(0.1)  # Simulate work
        return item * 2

class ThreadController(QObject):
    """Manages worker thread lifecycle."""
    def __init__(self):
        super().__init__()
        self.thread = None
        self.worker = None
    
    def start_work(self, data):
        # Create thread and worker
        self.thread = QThread()
        self.worker = Worker(data)
        
        # Move worker to thread
        self.worker.moveToThread(self.thread)
        
        # Connect signals
        self.worker.finished.connect(self.on_finished)
        self.worker.progress.connect(self.on_progress)
        self.worker.error.connect(self.on_error)
        
        # Thread lifecycle
        self.thread.started.connect(self.worker.process)
        self.thread.finished.connect(self.thread.deleteLater)
        
        # Start thread
        self.thread.start()
    
    def cancel_work(self):
        if self.worker:
            self.worker.cancel()
        if self.thread:
            self.thread.quit()
            self.thread.wait()
    
    @Slot()
    def on_finished(self, result):
        print(f"Work completed: {result}")
        self.cleanup()
    
    @Slot()
    def on_progress(self, percent):
        print(f"Progress: {percent}%")
    
    @Slot()
    def on_error(self, error):
        print(f"Error: {error}")
        self.cleanup()
    
    def cleanup(self):
        self.thread = None
        self.worker = None

moveToThread() Pattern - Worker Object Semantics

Correct Pattern: Worker + Thread Controller

The worker object pattern is the recommended approach for explicit thread control:

python
from PySide6.QtCore import QThread, Signal, QObject, Slot

class Worker(QObject):
    """Worker owns the work, controller owns the thread."""
    progress = Signal(int)
    finished = Signal(object)
    
    def __init__(self, data):
        super().__init__()
        self.data = data
        self._is_running = False
    
    @Slot()
    def process(self):
        """Main work method - called from thread."""
        self._is_running = True
        try:
            # Heavy computation here
            for i in range(100):
                self.progress.emit(i)
            self.finished.emit(None)
        finally:
            self._is_running = False

class ThreadController(QObject):
    """Controller owns thread and manages worker."""
    def __init__(self):
        super().__init__()
        self.thread = None
        self.worker = None
    
    def start_work(self, data):
        # Create NEW thread and worker
        self.thread = QThread()
        self.worker = Worker(data)
        
        # CRITICAL: Move worker TO thread
        self.worker.moveToThread(self.thread)
        
        # Worker lifetime tied to thread lifetime
        self.thread.started.connect(self.worker.process)
        self.thread.finished.connect(self.thread.quit)
        self.thread.finished.connect(self.thread.deleteLater)
        
        self.thread.start()

Ownership Semantics

ObjectOwnerLifetimeDeletion
WorkerThreadControllerUntil thread.quit() + wait()worker.deleteLater()
ThreadThreadControllerUntil deletedthread.deleteLater()
SignalsTheir parentUntil parent deletedAutomatic

Common Mistakes to Avoid

python
# ❌ WRONG: Worker outlives thread
controller = ThreadController()
controller.thread = QThread()
controller.worker = Worker()
controller.thread.moveToThread(controller.worker)  # Wrong direction!
controller.thread.start()
# Problem: Worker destroyed before thread finishes

# ❌ WRONG: Forgetting thread lifecycle
def start_work():
    thread = QThread()
    worker = Worker()
    worker.moveToThread(thread)
    thread.start()  # Never quit() or wait()!
# Problem: Zombie thread keeps running

# ✅ CORRECT: Proper ownership chain
controller = ThreadController()
controller.start_work(data)
# Later when done:
controller.thread.quit()
controller.thread.wait()
# Now delete: controller.worker.deleteLater()

Common Issues

IssueCauseSolution
UI freezesBlocking operation in main threadMove to worker thread
Crashes on widget accessAccessing UI from worker threadUse signals instead
Memory leaksThread not cleaned upUse deleteLater() and proper lifecycle
DeadlocksMultiple mutexes acquired in different orderAlways acquire in same order, use timeout
Race conditionsShared data without locksUse QMutex or atomic operations

Best Practices

  1. Always use signals for cross-thread communication - Direct widget access from threads causes crashes
  2. Keep worker objects thread-affinity aware - Never assume QObject is in main thread
  3. Clean up threads properly - Use deleteLater() and quit() + wait()
  4. Handle cancellation - Check flags periodically in long operations
  5. Use QThreadPool for parallel independent tasks - Default pool manages resource limits
  6. Use moveToThread() for explicit thread control - Worker object pattern is recommended
  7. Never use time.sleep() in main thread - Use QTimer or workers instead
  8. Keep locks short-lived - Only hold mutexes for critical section duration
  9. Use QReadWriteLock for read-heavy data - Multiple readers possible, single writer
  10. Monitor thread pool limits - Set maxThreadCount to prevent resource exhaustion

Common Pitfalls

IssueCauseSolution
UI crashes on widget accessWidget accessed from worker threadAlways use signals to update UI from main thread
DeadlockMultiple mutexes acquired in different orderAlways acquire in consistent order, use timeouts
Race conditionsShared data without locksUse QMutex, QAtomicPointer, or atomic operations
Memory leaksThreads not cleaned upUse deleteLater() on threads and workers
Thread not stoppingNo quit() + wait() sequenceAlways call thread.quit() then thread.wait()
Signals firing from wrong threadAutoConnection uses queued deliveryAutoConnection is correct - don't change
Re-entrancy issuesSignal handler calls slot recursivelyUse flags to track state changes
Resource exhaustionUnlimited thread pool threadsSet maxThreadCount on QThreadPool
Busy-wait loopsThread polling without sleepUse QTimer instead of polling
Lock not releasedException before unlockUse QMutexLocker for RAII-style cleanup

Top 5 Mistakes to Avoid

  1. Never access UI from worker threads - The most common crash cause

    python
    # ❌ CRASH: Direct UI access
    def run(self):
        self.label.setText("Done")  # Crashes!
    
    # ✅ SAFE: Use signals
    def run(self):
        self.finished.emit("Done")  # UI updated in main thread
  2. Forgetting thread lifecycle management - Threads become zombies

    python
    # ❌ BAD: No cleanup
    thread = QThread()
    thread.start()  # Never quit() or wait()
    
    # ✅ GOOD: Proper lifecycle
    thread.start()
    thread.quit()
    thread.wait()  # Wait for thread to finish
  3. Acquiring locks in wrong order - Deadlock

    python
    # ❌ DEADLOCK
    def do_work(self):
        with lock_a:
            with lock_b:
                pass
    
    def do_other_work(self):
        with lock_b:  # Different order!
            with lock_a:
                pass
    
    # ✅ SAFE: Consistent ordering
    # Always acquire locks in same order (e.g., by ID)
  4. Using locks too long - Performance issues

    python
    # ❌ BAD: Lock held for long operation
    with lock:
        result = heavy_computation()
    
    # ✅ GOOD: Hold lock only for data access
    with lock:
        data = self.shared_data
    result = heavy_computation(data)  # Outside lock
  5. Forgetting to check cancellation - Threads don't stop

    python
    # ❌ BAD: Infinite loop
    def run(self):
        while True:
            do_work()
    
    # ✅ GOOD: Check cancellation flag
    def run(self):
        while not self._cancelled:
            if self._work_done():
                break
            do_work()

Deep Dives

For detailed coverage of advanced patterns, load these reference files:

  • Pool Patterns (references/pool-patterns.md) - QThread Subclass, QThreadPool/QRunnable, QTimer, Fire-and-Forget
  • Qt Concurrent (references/qt-concurrent.md) - Map/filter/reduce operations, progress tracking, simple background tasks
  • Lifecycle & Cleanup (references/lifecycle-cleanup.md) - Thread signals, proper cleanup, graceful shutdown
  • Advanced Safety (references/advanced-safety.md) - Thread-safe state, UI state races, resource exhaustion
  • Testing (references/testing.md) - pytest-qt patterns, signal testing, thread lifecycle testing, race condition tests

References

Official Documentation

Qt for Python (PySide6/PyQt6)

Community Resources

Advanced Topics

Testing

Файли в пакеті

Модель читає ці файли за потреби, поки навичку завантажено. Вони доступні для читання й ніколи не виконуються.

Поширені запитання

Що робить навичка ШІ Pyqt Threading?

Use when handling PyQt/PySide6 threading - QThread patterns, QThreadPool/QRunnable, thread safety rules, moveToThread, Qt Concurrent, QTimer, testing threaded code, lifecycle management

Навіщо використовувати Pyqt Threading у TypingMind?

Тому що ви встановлюєте її один раз і використовуєте з будь-якою моделлю. Pyqt Threading — це звичайний Markdown, а не код для конкретного постачальника, тому та сама навичка працює з GPT-5, Claude, Gemini, Grok або локальною моделлю. Ви можете змінити модель навіть посеред чату, і навичка продовжить працювати. TypingMind використовує ваші власні ключі API, тож ви платите безпосередньо постачальникам замість передплати за кожне місце користувача, а ваші навички й чати залишаються у вашому сховищі.

Як встановити Pyqt Threading у TypingMind?

Відкрийте в TypingMind Плагіни → Навички → Встановити з GitHub і вставте https://github.com/CodeAtCode/oss-ai-skills/tree/master/frameworks/pyqt/threading. TypingMind прочитає файл SKILL.md, додасть супровідні файли та встановить навичку, яку можна вмикати окремо для кожного чату.

Які моделі ШІ можуть використовувати Pyqt Threading?

Будь-яка модель, яку ви підключите в TypingMind. Навички ШІ — це звичайні інструкції у форматі Markdown, а не код для конкретного постачальника, тому GPT, Claude, Gemini, Grok і локальні моделі можуть завантажувати цю навичку, коли запит їй відповідає.

Зі скількома моделями ШІ можна використовувати Pyqt Threading?

Зі скількома забажаєте. Якщо модель підтримує навички, ви можете використовувати з нею Pyqt Threading — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama та інші — усе в TypingMind із власними ключами API.

Чи безкоштовна навичка ШІ Pyqt Threading?

Так. Навичку опубліковано на GitHub: CodeAtCode, за ліцензією GPL-3.0. Ви платите лише своєму постачальнику ШІ за використані токени.

Що таке навички ШІ?

Навичка ШІ — це багаторазовий набір інструкцій, який навчає модель ШІ виконувати одне конкретне завдання. Він відповідає відкритому формату Agent Skills: файл SKILL.md із назвою та описом, а також скрипти, шаблони чи довідкові файли, які можуть знадобитися моделі. Модель читає інструкції лише тоді, коли ваш запит відповідає навичці, тому встановлена навичка нічого не коштує, доки її не використано.

Чим навички ШІ відрізняються від плагінів або серверів MCP?

Плагін або сервер MCP надає моделі нові інструменти для виклику — код, який десь виконується й повертає результат. Натомість навичка ШІ надає моделі знання та порядок дій: як підійти до завдання, яких кроків дотримуватися та яким має бути якісний результат. Навички — це звичайний Markdown, тож їм не потрібні ні сервер, ні ключ API, ні середовище виконання, і вони працюють із будь-якою моделлю.

Усі

Створіть власний ШІ-простір уже зараз

Підпишіться на нашу розсилку, щоб дізнаватися про нові функції та майбутні розіграші 👇