'''
多线程更新UI数据
原理:
1.子线程:完成某项指定的任务,比如更新系统时间并完成时间格式化
2.定义Run方法:获取当前系统时间,并且将值给到信号
3.槽函数为主线程中的函数
4.子线程完成工作后,触发信号,调用主线程中的槽函数,实现UI数据更新
'''
from PyQt5.QtCore import QThread, pyqtSignal, QDateTime
from PyQt5.QtWidgets import QApplication, QDialog, QLineEdit
import time
import sys
class BackendThread(QThread): # 子线程类:完成后台任务,更新当前时间
update_date=pyqtSignal(str) # 初始化自定义信号
def run(self): # run方法:获取当前系统时间,并且将值给到信号
while True:
data =QDateTime.currentDateTime()
currentTime=data.toString('yyyy-MM-dd hh:mm:ss')
self.update_date.emit(str(currentTime)) #自定义信号触发机制:传参
time.sleep(1)
class ThreadUpdateUI(QDialog): # 主线程:继承QDialog
def __init__(self):
QDialog.__init__(self)
self.setWindowTitle('多线程更新UI数据')
self.resize(400,100)
self.le_input=QLineEdit(self)
self.le_input.resize(400,100)
self.initUI()
def initUI(self):
self.backend=BackendThread() # 实例化子线程类
self.backend.update_date.connect(self.handleDisplay_cb) # 绑定自定义信号与槽函数(主线程中的方法:即显示在le_input文本框中)
self.backend.start() # 启动子线程
def handleDisplay_cb(self,data):
self.le_input.setText(data)
if __name__=='__main__':
app =QApplication(sys.argv)
example = ThreadUpdateUI()
example.show()
sys.exit(app.exec_())
输出结果: