Explanation of timers, threads, signals and slots in python

(1) The operation of the
timer The role of the timer: Timing, performing a certain operation regularly
The use of the timer:
(1) Import the timer module
(2) Set the timer: create a timer object
(3) Timer binding event , This event is executed according to the time set by the timer,-Timer setting 1s When the timer is turned on, this event will be executed once every 1s (slot function)
(4) Start the timer, from the moment it starts Start working
(5) Turn off the timer, the timer will stop working from the moment it is turned off
. Pseudo code for timer operation:

#coding=utf8
"""
动态显示时间
"""
import Qtimer

class ShowTimeDemo(QWidget):
    def __init__(self,parent=None):
	#这里省略其他控件定义代码......
	
        # 设置定时器
        self.timer = QTimer()
        # 定时器绑定的事件,一旦开启定时器(这里会设置定时器的时间),就会定时执行链接的槽函数(比如说定时从视频中取出图片,以及图片帧的入队列操作)
        self.timer.timeout.connect(self.showtime		
        # 按下按键就会开启定时器,定时器中设置了定时时间
        self.btn1.clicked.connect(self.start)
        self.btn2.clicked.connect(self.end)

        self.setLayout(layout)
    # 定时器绑定的事件(需要定时执行的)    
    def showtime(self):
        time = QDateTime.currentDateTime()
        timeDisplay = time.toString("yyyy-MM-dd hh:mm:ss dddd")
        self.label.setText(timeDisplay)
    # 开启定时器的操作,定时的时间是1s执行一次
    def start(self):
        self.timer.start(1000)
        self.btn1.setEnabled(False)
        self.btn2.setEnabled(True)
        
     # 关闭定时器的操作
     def end(self):
        self.timer.stop()
        self.btn1.setEnabled(True)
        self.btn2.setEnabled(False)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ShowTimeDemo()
    window.show()
    sys.exit(app.exec_())

It can be summarized as follows: set the timer, perform timer binding to execute a timed event, turn on the timer, and turn off the
timer. Once the timer is turned on, the timer starts to work (the timer bound event is executed according to the timing time) --- --Timer finished

(2) Thread operation
thread: a functional part in the execution of a program (process), which can also refer to an operation process-the operation in the thread is not the same as the operation of the timer, but the basic operations are: creation , Open, operate, close these four steps

Thread operation: It is more like an independent function code.
Here is an example: Multithreading in pyqt5 updates UI data.
Two threads: interface thread—> that is, main thread
background thread—> thread that processes data The
pseudo code is as follows:

#coding=utf8
from PyQt5.QtCore import QThread,pyqtSignal,QDateTime
from PyQt5.QtWidgets import QApplication,QDialog,QLineEdit
import time
import sys
"""
多线程更新UI数据
在这里做一个2线程更新UI数据
后台线程:得到并记录数据
主线程:窗口线程
在主线程中开启后台线程,并接收后台传输过来的数据(这里使用信号来输出数据,信号在下面会介绍)
"""
# 后台线程继承自线程类
class BackendThread(QThread):
    # 定义一个信号,用于将数据传输到界面(主线程)中
    updata_date = pyqtSignal(str)
    def run(self):
        while True:
            data = QDateTime.currentDateTime()
            currentTime = data.toString("yyyy-MM-dd hh:mm:ss")
            self.updata_date.emit(str(currentTime))
            # 设置频率,python中设置while()循环的频率---while循环中设置		                    
            time.sleep(1) 1s执行一次while循环
            time.sleep(1)

class ThreadUpdataUI(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.setWindowTitle("多线程更新UI数据")
        self.resize(400,400)
        self.input = QLineEdit(self)
        self.input.resize(200,200)

        self.initUI()
    def initUI(self):
    	# 创建线程类---继承了线程类所有的操作
        self.backend = BackendThread()
        """
        后台中的信号传输数据到主界面中的控件中,使用信号传输数据
        """
        self.backend.updata_date.connect(self.handleDisplay)

        # 开启后台线程
        self.backend.start()
    # 主界面中控件接收后台线程传输过来的数据
    def handleDisplay(self,data):
        self.input.setText(data)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ThreadUpdataUI()
    window.show()
    app.exec_()
    

The role of threads is very powerful, multi-threaded, if necessary, will improve the efficiency of the code, the code execution to avoid conflict
Summary: create a thread (and instantiate) - (thread what you need to do) ---- open Thread-you can close the thread without performing related operations [create, open, close]

(3) The operation of signals and slots ----- mainly introduce the operation of
signals Signal: Signal is a data transmission mechanism in pyqt, used to efficiently transmit data ----> widely used in data interaction

The creation of the signal is to create for the data.
Create-with data, create at any location, create any type of signal (depending on the data you want to transmit)
Trigger-with data (custom trigger, other commonly used controls Triggered in the trigger)
Binding-with data (binding slot function-in the main interface, the control receives the data sent by the signal)

How to design: decide according to what type of data is transmitted
(1) what kind of signal is created
(2) trigger signal to send the corresponding data
(3) signal binding slot function-the corresponding control performs data update operation

Pseudo-code for signal operations:
signal creation,
signal trigger,
signal-bound slot function (once a signal is triggered, the signal-bound slot function is automatically executed)

Operation code:

class DateDialog(QWidget):
    # 信号的定义 信号的定义也是多种多样的,主要就是你想传输什么样的数据,在不同的窗口之间传输
    # Signal_parp = pyqtSignal(str)
    # 信号的定义
    Signal1 = pyqtSignal(str,int)
    def __init__(self,parent=None):
        super(DateDialog,self).__init__(parent)
        self.setWindowTitle("Signal")
        layout = QVBoxLayout(self)
        self.datetime = QDateTimeEdit(self)
        self.datetime.setCalendarPopup(True)
        self.datetime.setDateTime(QDateTime.currentDateTime())

        self.Label = QLineEdit()

        self.button = QPushButton("发送")
        layout.addWidget(self.datetime)
        layout.addWidget(self.button)
        layout.addWidget(self.Label)
        self.setLayout(layout)

        self.button.clicked.connect(self.onClickButton)
        # 信号绑定的槽函数--在信号触发的时候执行
        self.Signal1.connect(self.onSignal)
    # 信号的触发可以通过其他控件来触发----控件本身就有触发机制
    def onClickButton(self):
        data_str = self.datetime.dateTime().toString()
        print("触发了")
        print(data_str)
        # 信号的触发,在这里信号是通过按键来进行触发的
        self.Signal1.emit(data_str,12)
   # 信号绑定的槽函数  
   def onSignal(self,data_str,data_int):
        self.Label.setText(data_str + str(data_int))
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = DateDialog()
    window.show()
    app.exec_()
                          

The general idea of ​​signal operation:
(1) signal creation-created according to the type of data to be transmitted
(2) signal trigger-when to trigger (trigger is required to transfer data)
(3) signal The bound slot function-the block of code that is executed after the signal is triggered.
Remember-using the signal to transfer data is very convenient and fast

                                           今日分享完毕----欢迎留言交流
Published 129 original articles · Like 43 · Visits 100,000+

Guess you like

Origin blog.csdn.net/nbxuwentao/article/details/103881084