简体   繁体   中英

PyQt4 slot system transition to PyQt5

I followed some tutorial online to learn about threading with PyQt but the example uses PyQt4 and I'm using PyQt5. I read this link to get some information: http://pyqt.sourceforge.net/Docs/PyQt5/signals_slots.html .

But I still don't understand how I should change my example below for it to work with PyQt5.

What this example is supposed to do is show the cpu percentage on a progress bar, and the reason why I'm using a thread is so the progress bar value will change when the cpu load changes.

So FYI the code below is code that works with PyQt4 but not with version 5, it would be helpful if somebody could show me the right way to do it with PyQt5.

My example code:

import sys
import os
import sysInfo
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QWidget, QApplication

from test import Ui_Form

class MainUiClass(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.setupUi(self)
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.connect(self.threadclass, SIGNAL('CPU_VALUE'), self.updateProgressBar)

    def updateProgressBar(self, val):
        self.progressBar.setValue(val)

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

    def run(self):
        while 1:
            val = sysInfo.getCPU()  # get cpu load
            self.emit(SIGNAL('CPU_VALUE'), val)

if __name__ == '__main__':
    app = QApplication([])
    window = MainUiClass()
    window.show()
    sys.exit(app.exec_())

The way to declare a signal is changed from pyqt4 to pyqt5:

class MainUiClass(QWidget, Ui_Form):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.setupUi(self)
        self.threadclass = ThreadClass()
        self.threadclass.cpuValueChanged.connect(self.updateProgressBar)
        self.threadclass.start()


    def updateProgressBar(self, val):
        self.progressBar.setValue(val)

class ThreadClass(QThread):
    cpuValueChanged = pyqtSignal(int)
    def __init__(self, parent=None):
        super(ThreadClass, self).__init__(parent)

    def run(self):
        while 1:
            val = sysInfo.getCPU()  # get cpu load
            self.cpuValueChanged.emit(val)

if __name__ == '__main__':
    app = QApplication([])
    window = MainUiClass()
    window.show()
    sys.exit(app.exec_())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM