How Python QTimer and graphical user interface (GUI) applications with Qt works together?

630 Views Asked by At

I started the timer and connect to function call “read_file” at interval 1sec. However, GUI interface does not come up. I do not understand on how Python QTimer and QT GUI work together? What can I do so my GUI page pop up and display the ping status. Any help I would appreciated.

import sys
from reachable_gui import *
import subprocess
import threading
import time
from PyQt5.QtCore import QTimer
import os

def signal(self):
    
    self.Button_Manual.clicked.connect(Manual)
    self.Button_Pdf.clicked.connect(Pdf)
    read_file(self)
   
def Manual():
    pass

def Pdf():
    pass
      
def read_file(self):
        {
    #read line by line IP and device from a file and pass it to ping()
    }
  timer = QtCore.QTimer()
  timer.timeout.connect(self.read_file)
  timer.setInterval(1000)
  timer.start()
        
def ping(self,IP,name):
    { 
    # ping the device and update GUI status.
    }
    
Ui_MainWindow.ping = ping
Ui_MainWindow.signal = signal
Ui_MainWindow.Manual = Manual
Ui_MainWindow.Pdf = Pdf
Ui_MainWindow.read_file = read_file

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    ui.signal()
    MainWindow.show()
    sys.exit(app.exec_())
1

There are 1 best solutions below

0
furas On BEST ANSWER

I don't know if this helps you resolve your problem but this is example how to use QTimer to run function many times.

But if function runs longer then it may create longer interval.

import sys
from PyQt5.QtCore import QTimer
from PyQt5 import QtWidgets
import datetime
#import time
   
def read_file():
    #time.sleep(2) # simulate long-running function
    
    current_time = datetime.datetime.now().strftime('%Y.%m.%d - %H:%M:%S')
    label.setText(current_time)
    
    print('current_time:', current_time)
    

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    window = QtWidgets.QMainWindow()
    
    # some GUI in window
    label = QtWidgets.QLabel(window, text='???')
    window.setCentralWidget(label)
    window.show()
    
    # timer which repate function `read_file` every 1000ms
    timer = QTimer()
    timer.timeout.connect(read_file)
    timer.setInterval(1000)
    timer.start()
    
    sys.exit(app.exec())