Forked from metalman/qapplication_about_to_quit_signal.py
Created
May 23, 2021 14:11
-
-
Save afreerunner/5813d6e4410b140c7968168a92b6f145 to your computer and use it in GitHub Desktop.
QThread graceful exit before QApplication quit.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| see: http://pyqt.sourceforge.net/Docs/PyQt4/qcoreapplication.html#aboutToQuit | |
| ''' | |
| import threading | |
| from PyQt4 import QtCore, QtGui | |
| class Thread(QtCore.QThread): | |
| def __init__(self, parent): | |
| QtCore.QThread.__init__(self, parent) | |
| self.window = parent | |
| self._lock = threading.Lock() | |
| self.running = False | |
| def stop(self): | |
| self.running = False | |
| print('received stop signal from window.') | |
| with self._lock: | |
| self._do_before_done() | |
| def _do_work(self): | |
| print('thread is running...') | |
| self.sleep(1) | |
| def _do_before_done(self): | |
| print('waiting 3 seconds before thread done..') | |
| for i in range(3, 0, -1): | |
| print('{0} seconds left...'.format(i)) | |
| self.sleep(1) | |
| print('ok, thread done.') | |
| def run(self): | |
| self.running = True | |
| while self.running: | |
| with self._lock: | |
| self._do_work() | |
| class Window(QtGui.QMainWindow): | |
| def __init__(self, app): | |
| # remember: | |
| # do not bind QApplication instance `app` to attribute of any object, | |
| # e.g self.app = app, | |
| # that will cause segmentation fault due to gc when closing. | |
| QtGui.QMainWindow.__init__(self) | |
| thread = Thread(self) | |
| app.aboutToQuit.connect(thread.stop) | |
| thread.start() | |
| if __name__ == '__main__': | |
| import sys | |
| app = QtGui.QApplication(sys.argv) | |
| window = Window(app) | |
| window.show() | |
| sys.exit(app.exec_()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment