Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a PyQT program keep refreshing one widget, always providing an up-to-date value?

Tags:

python

pyqt

I'm learning to program with PyQT4 and Python. I'm trying to code a simple app that will display the current CPU usage in a QLCD widget. For CPU usage I'm using psutils module.

The problem is that the CPU usage is not updated all the time - it only records the CPU usage at the moment the app has been launched (I'm guessing), and then it just stops. So, I'm looking for some sort of a loop equivalent that will hopefully not take too much of CPU power to process.

This is what I have so far:

self.wpCpuUsage.display(cpu_percent(interval=1))

and this is within __init__ of the QMainWindow class.

I've tried putting it in a for loop, but then it iterates over it, and basically waits for it to iterate and then executes the program.

Help?

like image 944
Bo Milanovich Avatar asked Dec 31 '25 00:12

Bo Milanovich


1 Answers

You can use a QTimer[reference] object with a callback.

Something like that should work:

def call_this():
    self.wpCpuUsage.display(cpu_percent(interval=1))

self.my_timer = QtCore.QTimer()
self.my_timer.timeout.connect(call_this)
self.my_timer.start(1000) #1 second interval
like image 103
JBernardo Avatar answered Jan 02 '26 14:01

JBernardo