Python Forum
How to emit a signal from another Class Method? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to emit a signal from another Class Method? (/thread-27987.html)



How to emit a signal from another Class Method? - SKDN - Jun-30-2020

Hi,

I got the emit signal working when it is in the Worker class - def run(self) method. Everything runs fine, the while loop is able to cycle and emit a signal every 1 second. Then the label will be updated after receiving the signal.

I decided to try out by placing the while loop in another class named loop, methodA. This is to try see if the emitted signal will be picked up by the MainWindow. Unfortunately, the signal is not picked up and the program hung up thereafter.

Did I miss any step that prevented the while loop's emitting signals from being picked up? Kindly point me in the right direction by making changes to my script.

Thanks.
import sys
import time
from PyQt5 import QtWidgets
from PyQt5.QtCore import QThread, pyqtSignal
from mydialog import Ui_mydialog


class Mainwindow(QtWidgets.QMainWindow, Ui_mydialog):

    def __init__(self, *args, obj=None, **kwargs):
        super(Mainwindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        self.thread = Worker()
        self.loop = loop()
        self.thread.sig.connect(self.updatelabel)

        self.mypushbutton.clicked.connect(self.mypushbuttonclicked)


    def mypushbuttonclicked(self):
        self.thread.start()

    def updatelabel(self, text):
        self.mylabel.setText(text)

class Worker(QThread):

    sig = pyqtSignal(str)

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        # self.count = 0
        self.loop = loop()

    def run(self):

        self.loop.methodA()

        ## Original code without being in class loop and method loopA
        # while True:
        #     time.sleep(1)
        #     self.count += 1
        #     if (self.count % 1 == 0):
        #         self.sig.emit(f"Timer: {self.count} s")

# Newly added class with method "methodA"
class loop(object):

    sig = pyqtSignal(str)

    def __init__(self):
        self.count = 0

    def methodA(self):

        while True:
            time.sleep(1)
            self.count += 1
            if (self.count % 1 == 0):
                self.sig.emit(f"Timer: {self.count} s")



app = QtWidgets.QApplication(sys.argv)
window = Mainwindow()
app.setStyle("Fusion")
window.show()
app.exec()



RE: How to emit a signal from another Class Method? - Yoriz - Jun-30-2020

Code shown is not able to be run, from mydialog import Ui_mydialog is missing.