IgorZ
IgorZ

Reputation: 1164

PyQt5 terminate application from worker

This is an example of the application that starts the QApp -> Worker -> Something that causes sys.exit() inside the worker

import sys
from PyQt5.QtCore import QRunnable, pyqtSlot, QThreadPool
from PyQt5.QtWidgets import QWidget, QApplication


class App(QWidget):

    def __init__(self):
        super().__init__()
        self.init_ui()
        self.threadpool = QThreadPool()
        worker = Worker()
        self.threadpool.start(worker)

    def init_ui(self):
        self.setFixedSize(600, 300)
        self.show()


class Worker(QRunnable):
    def __init__(self):
        super(Worker, self).__init__()

    @pyqtSlot()
    def run(self):
        print("Running worker...")
        run_application()


def run_window():
    app = QApplication([])
    ex = App()
    sys.exit(app.exec_())


def run_application():
    print('Running application...')
    sys.exit(10)

if __name__ == '__main__':
    run_window()

There are several cases when I run it:
exits with code 0
exits with code 10
window keeps hanging

It feels like a racing.
So what is the correct way to terminate the window in case of the sys.exit() or the exception inside the worker?

Edit: forgot to mention that I need to return the exit code and track it since I run the window through the subprocess/Popen.

Upvotes: 1

Views: 106

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

If you want to close the windows then a possible solution is to terminate the eventloop using QCoreApplication::quit():

def run_application():
    print("Running application...")
    QCoreApplication.quit()

Or QCoreApplication::exit():

def run_application():
    print("Running application...")
    QCoreApplication.exit(10)

Upvotes: 2

Related Questions