I know how to send signals from worker threads back to the main GUI thread, but how can I send signals from the main thread to the worker thread?
Here's some sample code which includes a signal and slot. Here I'm sending signals back to the main thread, but how can I go in the opposite direction?
The goal here being to send a signal to change the value of self.do to 0 when I want the thread to stop.
Here's the main file and I'll put the UI file below
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import QThread, QObject, pyqtSignal, pyqtSlot
from progressUI import Ui_Form
import sys
import time
class ProgressBar(QObject):
progress = pyqtSignal(int)
kill = pyqtSignal()
def __init__(self, timer, parent=None):
super(ProgressBar, self).__init__(parent)
self.time = timer
self.do = 1
def work(self):
while self.do == 1:
y = 0
for _ in range(100):
time.sleep(.1)
y += 1
self.progress.emit(y)
break
self.kill.emit()
@pyqtSlot(str)
def worker_slot(self, sentence):
print(sentence)
class Go(QMainWindow, Ui_Form, QObject):
custom_signal = pyqtSignal(str)
def __init__(self, parent=None):
QMainWindow.__init__(self, parent)
self.setupUi(self)
self.progressBar.setValue(0)
self.startThread()
@pyqtSlot(int)
def updateProgress(self, val):
self.progressBar.setValue(val)
self.custom_signal.emit('hi from main thread')
def startThread(self):
self.progressThread = ProgressBar(60)
self.thread = QThread()
self.progressThread.moveToThread(self.thread)
self.progressThread.progress.connect(self.updateProgress)
self.progressThread.kill.connect(self.thread.quit)
self.custom_signal.connect(self.progressThread.worker_slot)
self.thread.started.connect(self.progressThread.work)
self.thread.start()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
MainApp = Go()
MainApp.show()
sys.exit(app.exec_())
Here's the UI file.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(658, 118)
self.progressBar = QtWidgets.QProgressBar(Form)
self.progressBar.setGeometry(QtCore.QRect(30, 40, 601, 23))
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.label = QtWidgets.QLabel(Form)
self.label.setGeometry(QtCore.QRect(45, 75, 581, 26))
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName("label")
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
_translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Form"))
self.label.setText(_translate("Form", "TextLabel"))