PyQt5 how to notify a (running in a loop) threadpool created using QThreadPool() that a checkbox has change state

19 Views Asked by At

This is working for me with the checkbox example but in the future I'd like to use other user inputs as well. And searching the topic did not show any solution but one thing is that GUI operations should be performed in the main thread for safety reasons.

import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import time
import traceback

class WorkerSignals(QObject):
    mySignal = pyqtSignal(int)

class Worker(QRunnable):
    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()
        self.kwargs['mySignal_feed'] = self.signals.mySignal

    @pyqtSlot()
    def run(self):
        sigslot = self.fn(*self.args, **self.kwargs)

class Ui_MainWindow(object):
    #checkbox and all the other GUI here

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.show()
        self.threadpool = QThreadPool()
        self.runThread()

    def runThread(self):
        worker = Worker(self.thread_fnc)
        worker.signals.mySignal.connect(self.data_process)
        self.threadpool.start(worker)

    def thread_fnc(self, mySignal_feed):
        while True:
            try:
                if self.checkBox_1.isChecked():
                    newNum = 1
                else:
                    newNum = 0
                mySignal_feed.emit(newNum)
                time.sleep(1)
            except: print(traceback.format_exc())

    def data_process(self, newNum):
        print(newNum)

if __name__ == '__main__':
    app = QApplication([])
    form = MainWindow()
    app.exec_()

I have this if self.checkBox_1.isChecked(): that working in this case but would like to replace it with other safe way. That is whenever user changes GUI (checkbox, text, button), the second thread can catch it safely and do works accordingly. So is there a way that changes in GUI are update to second thread without checking GUI from second thread.

0

There are 0 best solutions below