PyQt5 Signals and Threading

11,111

The signal must be created, inside your ThreadClass, or before but as you emit the signal inside the ThreadClass, it is better to create it inside your class.

After creation, you need to connect it to the progress bar function. Here is an example of the signal created and connected inside your class.

class ThreadClass(QtCore.QThread):
    # Create the signal
    sig = QtCore.pyqtSignal(int)

    def __init__(self, parent=None):
        super(ThreadClass, self).__init__(parent)

        # Connect signal to the desired function
        self.sig.connect(updateProgBar)

    def run(self):
        while True:
            val = sysInfo.getCpu()

            # Emit the signal
            self.sig.emit(val)

Keep in mind that signals have changed style since PyQt5 : Description

if you watched a tutorial for PyQt4, it is not be the same.

Share:
11,111
ryn1x
Author by

ryn1x

Updated on June 17, 2022

Comments

  • ryn1x
    ryn1x almost 2 years

    I watched a short tutorial on PyQt4 signals on youtube and am having trouble getting a small sample program running. How do I connect my signal being emitted from a thread to the main window?

    import cpuUsageGui
    import sys
    import sysInfo
    from PyQt5 import QtCore
    
    """Main window setup"""
    app = cpuUsageGui.QtWidgets.QApplication(sys.argv)
    Form = cpuUsageGui.QtWidgets.QWidget()
    ui = cpuUsageGui.Ui_Form()
    ui.setupUi(Form)
    
    def updateProgBar(val):
        ui.progressBar.setValue(val)
    
    class ThreadClass(QtCore.QThread):
        def run(self):
            while True:
                val = sysInfo.getCpu()
                self.emit(QtCore.pyqtSignal('CPUVALUE'), val)
    
    threadclass = ThreadClass()
    
    # This section does not work
    connect(threadclass, QtCore.pyqtSignal('CPUVALUE'), updateProgBar)
    # This section does not work
    
    if __name__ == "__main__":
        threadclass.start()
        Form.show()
        sys.exit(app.exec_())