从线程监视CPU活动中更新进度栏

发布于 2025-02-02 02:19:38 字数 1499 浏览 4 评论 0原文

我从我的代码中获取此错误:

RuntimeWarning: MetaObjectBuilder::addMethod: Invalid method signature provided for "CPU_VALUE"
  self.threadclass.CPU_VALUE.connect(SIGNAL('CPU_VALUE'), self.UpdateProgressBar)
from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import SIGNAL, Signal
import main
import sysinfo


class MainUiClass(main.Ui_MainWindow, QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.setupUi(self)
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.threadclass.CPU_VALUE.connect(SIGNAL('CPU_VALUE'), self.UpdateProgressBar)
        # self.UpdateProgressBar()

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


class CpuClass(QtCore.QObject):
    cpu = Signal()


class ThreadClass(QtCore.QThread):
    CPU_VALUE = CpuClass()
    cpu = Signal()

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

    def run(self):
        while 1:
            # val = sysinfo.getCPU()
            self.CPU_VALUE.emit(SIGNAL('CPU_VALUE'), sysinfo.getCPU())
            # print(val)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    a = MainUiClass()
    a.show()
    app.exec_()

sysinfo文件:

import psutil

def getCPU():
    return psutil.cpu_percent(interval=1)

I am getting this error from my code:

RuntimeWarning: MetaObjectBuilder::addMethod: Invalid method signature provided for "CPU_VALUE"
  self.threadclass.CPU_VALUE.connect(SIGNAL('CPU_VALUE'), self.UpdateProgressBar)
from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import SIGNAL, Signal
import main
import sysinfo


class MainUiClass(main.Ui_MainWindow, QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainUiClass, self).__init__(parent)
        self.setupUi(self)
        self.threadclass = ThreadClass()
        self.threadclass.start()
        self.threadclass.CPU_VALUE.connect(SIGNAL('CPU_VALUE'), self.UpdateProgressBar)
        # self.UpdateProgressBar()

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


class CpuClass(QtCore.QObject):
    cpu = Signal()


class ThreadClass(QtCore.QThread):
    CPU_VALUE = CpuClass()
    cpu = Signal()

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

    def run(self):
        while 1:
            # val = sysinfo.getCPU()
            self.CPU_VALUE.emit(SIGNAL('CPU_VALUE'), sysinfo.getCPU())
            # print(val)


if __name__ == '__main__':
    app = QtWidgets.QApplication([])
    a = MainUiClass()
    a.show()
    app.exec_()

sysinfo file:

import psutil

def getCPU():
    return psutil.cpu_percent(interval=1)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

调妓 2025-02-09 02:19:38

您的示例有几个问题。首先,您正在混合旧式和新型信号,这令人困惑且不必要。旧式信号绝不能在新应用中使用。其次,您使用的是信号对象(cpusignal),这是不必要的,因为可以在qthread类上直接定义信号。第三,您不会在信号中散发CPU百分比的值,因此进度条将永远不会更新。最后,您尚未提供清洁线程关闭线程的机制。

在下面的演示脚本中,上述所有问题已经解决,我还添加了一个simulator类来生成用于测试的CPU活动。单击测试按钮将产生大约二十秒的活动,然后将相应地更新进度栏:

“

import psutil
from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import Signal

class MainUiClass(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.progress = QtWidgets.QProgressBar()
        self.button = QtWidgets.QPushButton('Test')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.progress)
        layout.addWidget(self.button)
        self.monitor = CpuMonitor()
        self.monitor.cpuPercent.connect(self.progress.setValue)
        self.monitor.start()
        self.simulator = Simulator()

    def handleButton(self):
        if not self.simulator.isRunning():
            self.simulator.start()

    def closeEvent(self, event):
        for thread in self.simulator, self.monitor:
            thread.stop()
            thread.quit()
            thread.wait()

class CpuMonitor(QtCore.QThread):
    cpuPercent = Signal(int)

    def run(self):
        self._stopped = False
        while not self._stopped:
            value = int(psutil.cpu_percent(interval=1))
            self.cpuPercent.emit(value)

    def stop(self):
        self._stopped = True

class Simulator(QtCore.QThread):
    def run(self):
        self._stopped = False
        random = QtCore.QRandomGenerator.system()
        timer1 = QtCore.QDeadlineTimer(20000)
        while not self._stopped and not timer1.hasExpired():
            duration = random.bounded(400, 800)
            self.msleep(duration)
            timer2 = QtCore.QDeadlineTimer(duration)
            while not self._stopped and not timer2.hasExpired():
                pass

    def stop(self):
        self._stopped = True

if __name__ == '__main__':

    app = QtWidgets.QApplication(['CPU Monitor'])
    a = MainUiClass()
    a.show()
    app.exec_()

Your example has several problems. Firstly, you are mixing old-style and new-style signals, which is confusing and unnecessary. Old-style signals should never be used in new applications. Secondly, you are using a signal object (CpuSignal), which is unnecessary since signals can be directly defined on the QThread class. Thirdly, you aren't emitting the value of the cpu percent in the signal, so the progress bar will never be updated. Finally, you haven't provided a mechanism for shutting down your thread cleanly.

In the demo script below, all the above issues have been fixed and I have also added a Simulator class to generate cpu-activity for testing. Clicking the Test button will produce about twenty seconds of activity and the progress-bar will then be updated accordingly:

screenshot

import psutil
from PySide2 import QtWidgets, QtCore
from PySide2.QtCore import Signal

class MainUiClass(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.progress = QtWidgets.QProgressBar()
        self.button = QtWidgets.QPushButton('Test')
        self.button.clicked.connect(self.handleButton)
        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.progress)
        layout.addWidget(self.button)
        self.monitor = CpuMonitor()
        self.monitor.cpuPercent.connect(self.progress.setValue)
        self.monitor.start()
        self.simulator = Simulator()

    def handleButton(self):
        if not self.simulator.isRunning():
            self.simulator.start()

    def closeEvent(self, event):
        for thread in self.simulator, self.monitor:
            thread.stop()
            thread.quit()
            thread.wait()

class CpuMonitor(QtCore.QThread):
    cpuPercent = Signal(int)

    def run(self):
        self._stopped = False
        while not self._stopped:
            value = int(psutil.cpu_percent(interval=1))
            self.cpuPercent.emit(value)

    def stop(self):
        self._stopped = True

class Simulator(QtCore.QThread):
    def run(self):
        self._stopped = False
        random = QtCore.QRandomGenerator.system()
        timer1 = QtCore.QDeadlineTimer(20000)
        while not self._stopped and not timer1.hasExpired():
            duration = random.bounded(400, 800)
            self.msleep(duration)
            timer2 = QtCore.QDeadlineTimer(duration)
            while not self._stopped and not timer2.hasExpired():
                pass

    def stop(self):
        self._stopped = True

if __name__ == '__main__':

    app = QtWidgets.QApplication(['CPU Monitor'])
    a = MainUiClass()
    a.show()
    app.exec_()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文