PyQt5 信号和线程 [英] PyQt5 Signals and Threading

查看:90
本文介绍了PyQt5 信号和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 youtube 上观看了有关 PyQt4 信号的简短教程,但在运行小示例程序时遇到了问题.如何将从线程发出的信号连接到主窗口?

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

推荐答案

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

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)

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

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

如果你看过 PyQt4 的教程,就不一样了.

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

这篇关于PyQt5 信号和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆