How to check from worker thread if a check box in main thread is checked?

Question:

I have designed a GUI program using pyqt5. I have a main thread and a worker thread. When the GUI starts, i get some inputs from user such as age, name,checkboxs … and i want to process the inputs in worker. In question How to assign variables to worker Thread in Python PyQt5? i learned how to pass GUI input variables to worker thread. But now i dont know how to check a checkbox if it is checked or not? I want to access the checkbox in GUI main thread from the worker thread but i dont know how can i do this. I really appreciate answers that help me to solve this problem.

class Worker(QObject):
    finished = pyqtSignal()
    
    def run(self):
        if self.ui.myCheckbox.ischecked(): #checkbox is defined in main thread
           do something

        self.finished.emit()

class MyAPP(QDialog):
    def __init__(self,parent=None):
        super().__init__(parent)

        self.setFixedSize(1180, 850)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.runWorkerBtn.clicked.connect(self.runLongTask)

   def runLongTask(self):
       
        self.thread = QThread()
     
        self.worker = Worker()
  
        self.worker.moveToThread(self.thread)
       
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()


Asked By: Orca

||

Answers:

since python doesn’t have pointer, you can pointing some variables from Worker class to point the MyAPP

class Worker(QObject):
    finished = pyqtSignal()

    def __init__(*args, **kwargs):
        self._main_thread = kwargs.pop("_main_thread")
        super().__init__(*args, **kwargs)
    
    def run(self):
        if self._main_thread.ui.myCheckbox.ischecked(): #checkbox is defined in main thread
           do something

        self.finished.emit()

class MyAPP(QDialog):
    def __init__(self,parent=None):
        super().__init__(parent)

        self.setFixedSize(1180, 850)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.runWorkerBtn.clicked.connect(self.runLongTask)

   def runLongTask(self):
       
        self.thread = QThread()
     
        self.worker = Worker(_main_thread=self.thread)
  
        self.worker.moveToThread(self.thread)
       
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()
Answered By: danangjoyoo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.