PyQt5 - 如何避免在多线程设置(Qthread)中更新progresssbar时崩溃gui?

时间:2017-12-10 03:44:59

标签: python pyqt pyqt5 qthread

我是多线程新手。我使用的视频文件工作正常,开头的进度条显示进度条中的百分比。当我想连续更改进度条值时,例如当前的cpu使用值,以下代码在运行代码时不断崩溃。为什么代码不起作用?

我认为问题是发射和连接。如果是这样我该怎么办?我该如何纠正这个?在此先感谢您的帮助。

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QObject, pyqtSignal
import sysinfo
from multi import Ui_Form


class main(QtWidgets.QWidget ,Ui_Form):
    cpu_value = pyqtSignal()
    def __init__(self, parent = None):
        super(main,self).__init__(parent)
        self.setupUi(self)
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.cpu_value.connect(self.updateProgressBar)



    def updateProgressBar(self):
        val = sysinfo.getCPU()
        self.progressBar.setValue(val)

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

    def run(self):
        while 1:
            val = sysinfo.getCPU()
            self.cpu_value.emit(val)

if __name__ == '__main__':
    a = QtWidgets.QApplication(sys.argv)
    app = main()
    app.show()
    a.exec_()

1 个答案:

答案 0 :(得分:0)

env:python3.5 + pyqt5.9

我使用计时器来更新CPU信息:

enter image description here

#!/usr/bin/python3
# 2017.12.10 13:20:11 CST
# 显示 CPU

import sys
from PyQt5 import QtCore, QtWidgets
import psutil

class CPU(QtWidgets.QProgressBar):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("CPU Info")
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(lambda : self.setValue(psutil.cpu_percent()))
        self.timer.start(1000)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    win = CPU()
    win.show()
    app.exec_()