1

I tried this example from StackOverflow:

How to get a child thread to close when main GUI window is closed in pyqt5 / python 3?

I would like this child thread to terminate when I close the main application. In this example, the child thread is a simple counter. When I close the main GUI, the counter still keeps going. How can I get the thread to end when the GUI window is closed?

My code is here:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 11 12:41:26 2020

@author: Pietro
"""

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QWidget, QApplication,QPushButton, 
                             QVBoxLayout)
from PyQt5.QtCore import QThread
import time, threading, sys





class testScriptApp(QtWidgets.QWidget):

    def __init__(self, parent=None):
        # initialize the widget
        QtWidgets.QWidget.__init__(self, parent)
        # set the window title
        self.setWindowTitle("Scripting")
        # manage the layout
        self.center()
        self.resize(400,400)
        self.mainGrid = QVBoxLayout()
        self.button = QPushButton('Start')
        self.button.clicked.connect(self.on_click)
        self.mainGrid.addWidget(self.button)
        self.setLayout(self.mainGrid)



    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def on_click(self):
        global running
        print('global running : ' , running)
        self.worker = Worker()
        self.worker.run()

    def closeEvent(self, event):
        global running
        running = False
        print('Closing')
#       self.worker.terminate()
        event.accept()

class Worker(QThread):

    def __init__(self):
        QThread.__init__(self)

    def run(self):
        count=1
        global running
        while count>0 and not running:
#        while count>0:
            print('counter on: ',count, running)
            time.sleep(2)
            count+=1
        else:
            print('out of loop')
            return

if __name__ == "__main__":
    running = False
    app = QtWidgets.QApplication(sys.argv)
    myapp = testScriptApp()
    myapp.show()
    app.exec_()

I started trying to learn Python3 weeks ago so please be gentle. What did I do wrong here?

Captain Jack Sparrow
  • 971
  • 1
  • 11
  • 28
pippo1980
  • 2,181
  • 3
  • 14
  • 30
  • Try reading this: https://stackoverflow.com/questions/16246796/how-to-stop-a-qthread-from-the-gui – Captain Jack Sparrow Apr 11 '20 at 13:49
  • 1
    You should call `self.worker.start()` instead of `run()`. If you set `self.worker.setTerminationEnabled(True)` then in the closeEvent `self.worker.terminate()` will terminate the thread. – alec Apr 12 '20 at 03:05
  • Yes Noah, that is working. Thank You a lot. Why do you think I cannot get the else statment of the conter to print 'out of loop' (line 71) ? – pippo1980 Apr 12 '20 at 14:46

0 Answers0