Python GUIs: Clean up on exit ... Note

Python GUIs: Clean up on exit — Stopping threads when closing a PyQt6 application — How to properly shut down background threads and workers when your application window is closed

Background threads in PyQt applications, managed by QThreadPool or QThread, continue running even after the main window is closed. This can cause the application to hang or generate errors. To address this, override the closeEvent method in your main window class. This method is automatically called when the window begins to close, providing an opportunity to execute cleanup code. Inside closeEvent, you should signal all your background workers to stop their execution. For workers implemented as QRunnable, this typically involves setting an internal flag that the worker's run method periodically checks. After signaling the workers to stop, use QThreadPool.waitForDone() to pause execution until all threads in the pool have completed their tasks. This ensures that no threads are abruptly terminated, preventing potential issues. Finally, call event.accept() to allow the window to close normally. It is also crucial to wrap your application's event loop execution with sys.exit() to guarantee a clean process termination. This pattern ensures that all background operations are gracefully halted before the application fully exits.