python - PyQt4:使用 QTimer 不断更新进度条

标签 python pyqt4 signals-slots qtimer qprogressbar

我有一个带有三个进度条的简单对话框,我想不断更新它(显示系统资源使用情况)。通过阅读文档,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()

最佳答案

您必须保留对计时器对象的引用,否则当 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 - PyQt4:使用 QTimer 不断更新进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46940232/

相关文章:

python - 如何使用 QFileDialog 选项并检索 saveFileName?

python - 为什么不能使用 std::ref 将对象传递到 Boost.Python 模块中?

python - 如何在我的 Pig Latin Translator (Python) 上添加退出选项

python imaplib 获取结果与来自 gmail 的简单电子邮件无关

c++ - Qt 线程对象只发送信号作为 Qt :DirectConnection - why?

c++ - 如何在 QML 中创建 Q_GADGET 结构的新实例?

c++ - 如何在信号槽中放置等待条件?

python - 遍历 globals() 字典

python - 在已编译的 PyQt4 Qt Designer 上显示来自操作工具栏的弹出窗口

python - 使用 PyQt 资源系统的问题