PyQt5信号和线程

时间:2016-11-10 21:08:11

标签: python qt python-3.x pyqt pyqt5

我在youtube上观看了一个关于PyQt4信号的简短教程,但是在运行一个小样本程序时遇到了麻烦。如何将从线程发出的信号连接到主窗口?

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_())

1 个答案:

答案 0 :(得分:8)

必须在ThreadClass内部或之前创建信号,但是当您在ThreadClass中发出信号时,最好在类中创建它。

创建后,您需要将其连接到进度条功能。以下是在班级内创建并连接的信号示例。

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)

请记住,自PyQt5以来,信号已经改变了样式:Description

如果您看过PyQt4的教程,那就不一样了。