Implementation code of PyQt5 QThread countdown function

  • 2021-10-16 02:10:49
  • OfStack

1. Create a multithreaded class
Global variable sec


class work_thread(QThread):
 timer = pyqtSignal() #  Every interval 1 Send signal in seconds 
 end = pyqtSignal() #  Counting completes sending signal 

 def run(self) -> None:
  while True:
   self.sleep(1)
   if sec == 0:
    self.end.emit() #  Send end Signal 
    break
   self.timer.emit()

2. Instantiate thread class, binding count, technology end event


self.label.setText("20")
global sec
sec = 20
self.work_thread = work_thread()
self.work_thread.timer.connect(self.count_time)
self.work_thread.end.connect(self.end)

3. Bind Start Button Events


self.pushButton.clicked.connect(self.start)

4. Event approach


def count_time(self):
 global sec
 sec = int(self.label.text())
 sec -= 1
 self.label.setText(str(sec))

def end(self):
 self.statusbar.showMessage(" Counting stops ")

def start(self):
 self.work_thread.start() #  Startup thread 

PS: Knowledge Point Extension

Realization of PyQt5 Countdown Button Function


"""
 In this example, we implemented two functions: menu button and button with countdown (which is often encountered when registering an account). 
"""
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QMenu
from PyQt5.QtCore import QTimer
import sys

class Example(QWidget):

  def __init__(self):
    super().__init__()
    self.initUI()

  def initUI(self):

    self.resize(400,300)
    self.setWindowTitle(' Graduate early -- Button ( QPushButton ) ')

    bt1 = QPushButton(" What is this ",self)
    bt1.move(50,50)

    self.bt2 = QPushButton(' Send verification code ',self)
    self.bt2.move(200,50)
    """
 Setting menu buttons is actually very simple. First, we create a new one 1 A QMenu Object. Here's addSeparator() In fact, it is to add to the menu 1 Delimiter character. 
    """
    menu = QMenu(self)
    menu.addAction(' I am ')
    menu.addSeparator()
    menu.addAction(' The world ')
    menu.addSeparator()
    menu.addAction(' The most handsome ')

    bt1.setMenu(menu)# Then add this menu to the QPushButton Object 
    """
 No. 1 2 For example, we use the QTimer This class, we have used this time-related class many times before. It will be explained specifically later. 
QTimer Class provides repeatability and a single timer. QTimer Class provides a high-level programming interface for timers. To use it, create 1 A QTimer , put it timeout() Signal to the corresponding slot, and then call the start() . From then on, it will be sent at fixed intervals timeout() Signal. 
setInterval() This property has a timeout interval in milliseconds. The default value for this property is 0 .  
    """

    self.count = 10
    self.bt2.clicked.connect(self.Action)
    self.time = QTimer(self)
    self.time.setInterval(1000)
    self.time.timeout.connect(self.Refresh)

    self.show()
    """
 After we click the button, we judge that if the button is not disabled, we activate the timer and disable the button at the same time, that is, click is prohibited. 
    """
  def Action(self):
    if self.bt2.isEnabled():
      self.time.start()
      self.bt2.setEnabled(False)
    """
 After entering the timeout state, we start the countdown. At the same time, let the text on the button constantly change. 
 When the countdown is complete, we stop the timer. Restore the button to its normal state. At the same time, reset the countdown value to prepare for the next use.  
    """
  def Refresh(self):
    if self.count > 0:
      self.bt2.setText(str(self.count)+' Retransmitted in seconds ')
      self.count -= 1
    else:
      self.time.stop()
      self.bt2.setEnabled(True)
      self.bt2.setText(' Send verification code ')
      self.count = 10

if __name__ == '__main__':
  app = QApplication(sys.argv)
  ex = Example()
  sys.exit(app.exec_())

Related articles: