-1

I am new in multi threading. The video file I use work fine and the progress-bar at the start shows a percent in progress-bar. When I want to change the progress-bar value continuously for example the current cpu usage value the below code keeps crashing when i run the code. Why is the code not working??

I think the problem is emit and connect. If so what can i do? And how do I correct this? Thanks in advance for the help.

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_()
ZF007
  • 3,708
  • 8
  • 29
  • 48
  • Try with my answer, and if this helps you do not forget to mark it as correct, if you do not know how to do it check the following link: [tour] – eyllanesc Dec 10 '17 at 04:03
  • `I suppose your code is right`. Then you do `while 1: getcpu_and_emit` in the `run()` method, this is not a good idea. Because is `while-True-op is cpu-costing` even you do it in another thread. `I think use a timer to update some info is a better idea`. See my answer. – Kinght 金 Dec 10 '17 at 05:28
  • it looks like both answers are half of the solution here and should be merged, right? Or eyllanesc.. are you suggesting `self.setupUi(self)` has the appropriate progressbar in question inside it? – ZF007 Dec 11 '17 at 12:04

1 Answers1

0

env: python3.5 + pyqt5.9

I use a timer to update the CPU info like that:

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_()
Kinght 金
  • 17,681
  • 4
  • 60
  • 74