Signal
The signal is a tool used to automatically change the interface, the principle is that the signal is bound to a function, when the signal is triggered when the function is called
As an example,
fromPyQt5ImportQtwidgets,qtcore fromUntitledImportUi_formImport TimeclassMywindow (qtwidgets.qwidget,ui_form): _signal=qtcore.pyqtsignal (str)#define the signal, define the parameter as str type def __init__(self): Super (mywindow,self).__init__() self.setupui (self) self.myButton.clicked.connect (self.myprint)#Press the button to execute the MyprintSelf._signal.connect (self.mysignal)#connect the signal to the function mysignal defMyprint (self): Self.tb.setText ("") Self.tb.append ("printing, please wait") Self._signal.emit ("is the print over?")#The signal is triggered . defmysignal (self,string):Print(String) self.tb.append ("Print End") if __name__=="__main__": #The following code acts as an expression of the UI interface Importsys app=qtwidgets.qapplication (SYS.ARGV) myshow=Mywindow () myshow.show () Sys.exit (App.exec_ ())
Timer
The function of a timer is to start a function at timed time by creating a Qtimer object, connecting its timeout signal to the corresponding slot (the binding function name), and calling Start (), and the timer emits a timeout signal at a constant interval until the stop () is called.
For example: Stopwatch function (Refresh the interface every second, until the stop button is pressed)
fromPyqt5.qtwidgetsImport* fromPyqt5.qtcoreImport*ImportSYS fromDatetimeImportdatetimeclassWintimer (qwidget):def __init__(self,parent=None): Super (wintimer,self).__init__(parent)## #界面显示Self.label_start=qlabel ("Start time:") Self.label_curr=qlabel ("Current Time:") Self.label_total=qlabel ("Total time:") self.startbtn=qpushbutton ("Start") self.endbtn=qpushbutton ("Stop") self.endBtn.setEnabled (False)##时间变量Self.start_time=qdatetime.currentdatetime () self.stop_time=qdatetime.currentdatetime ()## #定时器Self.timer=Qtimer () self.timer.timeout.connect (self.currtime) Layout=qgridlayout () layout.addwidget (self.label_start,0,0,The) Layout.addwidget (Self.label_curr,1,0,1,2) Layout.addwidget (Self.label_total,2,0,1,2) Layout.addwidget (SELF.STARTBTN,3, 0) layout.addwidget (self.endbtn,3, 1) self.setlayout (layout) self.startBtn.clicked.connect (Self.starttimer) self.endBtn.clicked.conn ECT (Self.endtimer) Self.setwindowtitle ("Qtimer") Self.resize (250,100) defCurrtime (self): Self.stop_time=qdatetime.currentdatetime () str_time= Self.stop_time.toString ("yyyy-mm-dd hh:mm:ss dddd") Self.label_curr.setText ("Current Time:"+str_time) Str_start= Self.start_time.toString ("YYYY-MM-DD Hh:mm:ss") Str_curr= Self.stop_time.toString ("YYYY-MM-DD Hh:mm:ss") StartTime= Datetime.strptime (Str_start,"%y-%m-%d%h:%m:%s") EndTime= Datetime.strptime (Str_curr,"%y-%m-%d%h:%m:%s") Seconds= (EndTime-startTime). Seconds Self.label_total.setText ("Total time:"+ str (seconds) +"s") defStarttimer (self): Self.start_time=qdatetime.currentdatetime () str_time= Self.start_time.toString ("yyyy-mm-dd hh:mm:ss dddd") Self.label_start.setText ("Start time:"+str_time) Self.timer.start (1000) self.startBtn.setEnabled (False) self.endBtn.setEnabled (True)defEndTimer (self): Self.timer.stop () self.startBtn.setEnabled (True) self.endBtn.setEnabled (False) /c2>if __name__=="__main__": App=qapplication (sys.argv) Form=Wintimer () form.show ( )View Code
Multithreading
Suppose our main interface has an LCD digital panel for displaying time and a button to start the task. The purpose of the program is for the user to click on the button to start a very time-consuming operation (in the program we replace this very time-consuming work with a 2 billion-time cycle, in the real program, this may be a network access, may need to copy a large file or other tasks), while the LCD Start showing the number of milliseconds elapsed. The number of milliseconds is updated with a timer qtimer. When the calculation is complete, the timer stops. This is a very simple application and does not see any problems. But when we start to run the program, the problem is: after clicking the button, the program interface stops responding directly until the end of the loop, and the timer uses display 0.
This is because all of the interfaces in Qt are in the UI line approached (also known as the main thread, that is, executing the qapplication::exec () threads), and executing time-consuming operations (such as that loop) in this thread, blocking the UI thread, thus causing the interface to stop responding. The interface stops responding, the user experience is not natural, but more serious, some window management programs will detect that your program has been unresponsive, may recommend that users force stop the program, so that the program may be terminated, the task can no longer be completed. So, to avoid this problem, we're going to use Qthread to open a new thread:
#Coding=utf-8__author__='a359680405' fromPyqt5.qtcoreImport* fromPyqt5.qtguiImport* fromPyqt5.qtwidgetsImport*Globalsec sec=0classWorkthread (qthread): Trigger=pyqtsignal ()def __int__(self): Super (workthread,self).__init__() defRun (self): forIinchRange (203300030): PassSelf.trigger.emit ()#send a signal after the loop is complete defcounttime ():Globalsec sec+=1Lcdnumber.display (sec)#LED Display number +1 defWork (): Timer.start (1000)#Timer count per secondWorkthread.start ()#Timing StartsWorkThread.trigger.connect (Timestop)#stop counting when you get the loop complete signal deftimestop (): Timer.stop ()Print("When run ends", Lcdnumber.value ())Globalsec sec=0 Apps=qapplication ([]) Top=qwidget () layout=qvboxlayout (top)#vertical Layout class qvboxlayout;Lcdnumber=qlcdnumber ()#Add a displaylayout.addwidget (lcdnumber) button=qpushbutton ("Test") Layout.addwidget (button) Timer=Qtimer () workthread=Workthread () button.clicked.connect (work) Timer.timeout.connect (Counttime)#each time the timer ends, the trigger settimeTop.show () app.exec()View Code
The above code adds a Workerthread class. Workerthread inherits from the Qthread class and overrides its run () function. You can assume that the run () function is the code that the new thread needs to execute. This is where the loop is executed, and then the signal to complete the calculation is issued. In the slot function of the button click, use the Workthread.start () function in work () to start a thread (note that this is not the run () function). Run the program again and you will see that the interface is no longer blocked.
PYQT5 signals, timers and multithreading