Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt5 Signals and Threading

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_())
like image 646
ryn1x Avatar asked Nov 10 '16 21:11

ryn1x


1 Answers

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.

like image 197
syedelec Avatar answered Nov 04 '22 09:11

syedelec