New to pyQT, threading question
-
I am new to Python and pyQT, I am creating a small app that gets the status of various services on a remote server using fabric and ssh. This is causing the pyQT app to freeze. I am told that using a thread is the way to solve this problem but I am having trouble getting it to work.
The service status is shown with a radio button color (red/green) and I use a function for each that runs a service check on the remote server and returns red or green based on the status.
def check_service(service): c = Connection('server.com', user="user", connect_kwargs={"key_filename": "/Users/devuser/.ssh/id_rsa",}) result = c.run('systemctl is-active --quiet service', warn=True) if result.exited == 0: status = 0 # service running elif result.failed: status = 1 # service not running else: status = 2 # status unknown return(status)
The status in QT is shown with a radio button:
self.NF_status = QRadioButton() self.NF_status.setStyleSheet("QRadioButton::indicator {background-color : %s }" % check_service("server-service.service")) self.NF_status.setCheckable(False)
In order to get it to update status, I used Qtimer to get updates. There are 12 services that I need to check
class MainWindow(QMainWindow): def processOneThing(self): self.NF_status.setStyleSheet("QRadioButton::indicator {background-color : %s }" % check_service("server-service.service")) ... timer = QTimer(self) timer.timeout.connect(self.processOneThing) timer.setInterval(5000) # 1000ms = 1s timer.start()
It works but things are just bogged down. From what I have read I can use a Worker(Qthread) class to run the service checks and then pull that data into the MainWindow but so far have been unsuccessful. Looking for some help.
-
@jdev8000 You can move all this long lasting checks including the timer in a worker object which is running in another thread. Everytime there is something new in that thread the worker object emits a signal. This signal is connected to a slot in the UI thread. This slots updates the UI. Never touch UI in other threads, only in main/UI thread!
See https://wiki.qt.io/QThreads_general_usage