Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt5 - How to emit signal from worker tread to call event by GUI thread

Tags:

python

pyqt5

As I Mentioned in Title. How can i do something like this?

class Main(QWidget):

        def __init__(self):

                super().__init__()

        def StartButtonEvent(self):

                self.test = ExecuteThread()
                self.test.start()

        def MyEvent(self):

                #MainThreadGUI

class ExecuteThread(QThread):

        def run(self):

                # A lot of work

                # Signal to main thread about finishing of job = mainthread will perform MyEvent

I found some tutorials here pyqt4 emiting signals in threads to slots in main thread

and here Emit signal from pyQt Qthread

But it seems it does not working in PyQt5 :/

like image 249
Erik Šťastný Avatar asked Mar 10 '23 09:03

Erik Šťastný


1 Answers

Just use the QThread.finished signal here. It will be executed automatically if you finish your thread. Of course you can also define your own custom signal if you want.

from PyQt5.QtCore import pyqtSignal

class Main(QWidget):

    def __init__(self):
        super().__init__()

    def StartButtonEvent(self):
        self.test = ExecuteThread()
        self.test.start()
        self.test.finished.connect(thread_finished)
        self.test.my_signal.connect(my_event)

    def thread_finished(self):
        # gets executed if thread finished
        pass

    def my_event(self):
        # gets executed on my_signal 
        pass


class ExecuteThread(QThread):
    my_signal = pyqtSignal()

    def run(self):
        # do something here
        self.my_signal.emit()
        pass
like image 124
MrLeeh Avatar answered Apr 29 '23 20:04

MrLeeh