代码之家  ›  专栏  ›  技术社区  ›  Spencer

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

  •  2
  • Spencer  · 技术社区  · 7 年前

    我有一个简单的对话框,其中有三个进度条,我想不断更新(显示系统资源使用情况)。通过阅读文档, 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()
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   ekhumoro    7 年前

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

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