I'm trying to make the background worker start with the start button and stop with the stop button. When I push start the program starts but I can't stop it and it also exits the gui when completed. Sorry, I am a novice just trying to learn. I found this example here and I am just trying to expand on it. Background thread with QThread in PyQt
# main.py
from PyQt5.QtCore import QThread
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QGridLayout, QPushButton
import sys
import worker
class Form(QWidget):
def __init__(self):
super().__init__()
self.label = QLabel("0") # start out at 0.
##### I added the stuff below 6/8/2020 ####################################
k = 2
self.button1 = QPushButton("Push to start") # create start button
self.button2 = QPushButton("Push to Stop") # create a stop button.
self.button1.clicked.connect(self.start) # connect button to function
self.button2.clicked.connect(self.stop) # connect button to function
########################################################################
# 1 - create Worker and Thread inside the Form
self.obj = worker.Worker() # no parent! #### Calls to worker.py
self.thread = QThread() # no parent! #### Creates an empty thread
# 2 - Connect Worker`s Signals to Form method slots to post data.
self.obj.intReady.connect(self.onIntReady) # connects the definition below
# 3 - Move the Worker object to the Thread object
self.obj.moveToThread(self.thread)
# 4 - Connect Worker Signals to the Thread slots
self.obj.finished.connect(self.thread.quit)
# 5 - Connect Thread started signal to Worker operational slot method
#self.thread.started.connect(self.obj.procCounter(k)) #### starts the counter in worker.py
# 6 - Start the thread
self.thread.start()
# 7 - Start the form
self.initUI()
def start(self):
k=2
self.obj.procCounter(k)
def stop(self):
self.thread.quit()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(self.label,0,1)
grid.addWidget(self.button1, 0, 0)
grid.addWidget(self.button2, 0, 2)
self.move(300, 150)
self.setWindowTitle('thread test')
self.show()
def onIntReady(self, i):
self.label.setText("{}".format(i))
print(i)
app = QApplication(sys.argv)
form = Form()
sys.exit(app.exec_())
# worker.py
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
import time
class Worker(QObject): # this is called by Worker.worker() in main.py
finished = pyqtSignal() # sets up to emit a signal back to main.py
intReady = pyqtSignal(int) # emits an integer to main.py def onIntReady
@pyqtSlot()
def procCounter(self,k): # A slot takes no params
for i in range(1, 10):
time.sleep(1)
self.intReady.emit(i*k) # emits the signal to onIntReady
#def procCounter(self): # A slot takes no params
# for i in range(1, 100):
# time.sleep(1)
# self.intReady.emit(i)
self.finished.emit()