Pythonguis iconPythonguisSep 9, 2026 ~1 min source read

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

When I click the X button to close the window, the threads keep running in the background. This is a very common situation when working with multithreaded PyQt6 applications.

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

Share this story

Send the public story page.

Useful takeaways from this story.

When I click the X button to close the window, the threads keep running in the background.

This is a very common situation when working with multithreaded PyQt6 applications.

This means your Python process can hang, or you might see tracebacks as threads try to interact with widgets that no longer exist.

Building the complete brief

The page is ready to read now. The fuller skim-friendly version will appear here automatically.

The useful part

When I click the X button to close the window, the threads keep running in the background. This is a very common situation when working with multithreaded PyQt6 applications. You've set up background workers using QThreadPool or QThread, everything runs great — but when you close the window, the application doesn't fully exit.

How it works

  • The solution is to hook into your window's close event and explicitly stop your background work before the window finishes closing.
  • When you close a PyQt6 window by clicking the X button (or calling close()), Qt destroys the window and its widgets.
  • I'm using QThreadPool and worker threads in my PyQt application.
  • Any threads you've started — whether via QThreadPool, QThread, or QRunnable — are managed separately.
  • This means your Python process can hang, or you might see tracebacks as threads try to interact with widgets that no longer exist.

What to take from it

They don't automatically stop just because the window is gone. Overriding closeEvent Every QWidget (including QMainWindow) has a method called closeEvent that Qt calls whenever the widget is about to close. By overriding this method, you can run your own cleanup code at exactly the right moment.

Details worth keeping

What's the best way to clean everything up on application exit? The threads keep going, and you might even see errors in your console.

Keep reading in the app

Open the app view to save this story, compare related coverage, and continue from the same source.

Open in app