【问题标题】:PyQt4: use a QTimer to continually update progress barsPyQt4:使用 QTimer 不断更新进度条
【发布时间】:2017-10-25 19:04:58
【问题描述】:

我有一个简单的对话框,其中包含三个我想要不断更新的进度条(显示系统资源使用情况)。通过阅读文档,QTimer 是每x 毫秒触发一个函数的正确方法(这将更新进度条)。但是,我无法让它工作,我也不知道为什么。将定时器超时信号连接到更新函数似乎相对简单,但它似乎永远不会触发。

这是我的代码:

import sys
from PyQt4 import QtGui, QtCore
import psutil

class Tiny_System_Monitor(QtGui.QWidget):
    def __init__(self):
        super(Tiny_System_Monitor, self).__init__()
        self.initUI()

    def initUI(self):
        mainLayout = QtGui.QHBoxLayout()

        self.cpu_progressBar = QtGui.QProgressBar()
        self.cpu_progressBar.setTextVisible(False)
        self.cpu_progressBar.setOrientation(QtCore.Qt.Vertical)
        mainLayout.addWidget(self.cpu_progressBar)

        self.vm_progressBar = QtGui.QProgressBar()
        self.vm_progressBar.setOrientation(QtCore.Qt.Vertical)
        mainLayout.addWidget(self.vm_progressBar)

        self.swap_progressBar = QtGui.QProgressBar()
        self.swap_progressBar.setOrientation(QtCore.Qt.Vertical)
        mainLayout.addWidget(self.swap_progressBar)

        self.setLayout(mainLayout)

        timer = QtCore.QTimer()
        timer.timeout.connect(self.updateMeters)
        timer.start(1000)

    def updateMeters(self):
        cpuPercent = psutil.cpu_percent()
        vmPercent = getattr(psutil.virtual_memory(), "percent")
        swapPercent = getattr(psutil.swap_memory(), "percent")

        self.cpu_progressBar.setValue(cpuPercent)
        self.vm_progressBar.setValue(vmPercent)
        self.swap_progressBar.setValue(swapPercent)
        print "updated meters"

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Tiny_System_Monitor()

    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python pyqt4 signals-slots qtimer qprogressbar


    【解决方案1】:

    你必须保留对计时器对象的引用,否则当initUI返回时它会立即被垃圾回收:

    class Tiny_System_Monitor(QtGui.QWidget):
        ...
        def initUI(self):
            ...    
            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.updateMeters)
            self.timer.start(1000)
    

    【讨论】:

    • 谢谢,正是我需要的!它几乎总是很简单。现在请原谅我去学习垃圾收集......(我需要读一本关于基本 python 的书)
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多