python GUI庫圖形界面開發(fā)之PyQt5多線程中信號與槽的詳細(xì)使用方法與實例
最簡單的多線程使用方法是利用QThread函數(shù),展示QThread函數(shù)和信號簡單結(jié)合的方法
import sysfrom PyQt5.QtCore import *from PyQt5.QtWidgets import *class Main(QWidget): def __init__( self, parent=None ): super(Main, self).__init__(parent) #創(chuàng)建一個線程實例并設(shè)置名稱 變量 信號與槽 self.thread = MyThread() self.thread.setIdentity(’thread1’) self.thread.sinOut.connect(self.outText) self.thread.setVal(6) #打印輸出文本 def outText( self, text ): print(text)class MyThread(QThread): #自定義信號參數(shù)為str類型 sinOut = pyqtSignal(str) def __init__( self, parent=None ): super(MyThread, self).__init__(parent) #初始化名稱為空 self.identity = None def setIdentity( self, text ): #設(shè)置多線程名稱 self.identity=text def setVal( self, val ): #接受數(shù)據(jù),運行多線程 self.times = int(val) self.run() def run( self ): #當(dāng)次數(shù)大于0以及名稱不為空時執(zhí)行代碼 while self.times>0 and self.identity: #發(fā)射信號,觸發(fā)打印函數(shù),次數(shù)-1 self.sinOut.emit(self.identity+’==>’+str(self.times)) self.times-=1if __name__ == ’__main__’: app=QApplication(sys.argv) main=Main() main.show() sys.exit(app.exec_())
運行如下
有時候在開發(fā)程序時會經(jīng)常執(zhí)行一些耗時的操作,這樣就會導(dǎo)致界面卡頓,這也是多線程的應(yīng)用范圍之一,這樣我們就可以創(chuàng)建多線程,使用主線程更新界面,使用子線程后臺處理數(shù)據(jù),最后將結(jié)果顯示在界面上
import sys,timefrom PyQt5.QtCore import *from PyQt5.QtWidgets import *class BackQthread(QThread): #自定義信號為str參數(shù)類型 update_date=pyqtSignal(str) def run( self ): while True: #獲得當(dāng)前系統(tǒng)時間 data=QDateTime.currentDateTime() #設(shè)置時間顯示格式 curTime=data.toString(’yyyy-MM-dd hh:mm:ss dddd’) #發(fā)射信號 self.update_date.emit(str(curTime)) #睡眠一秒 time.sleep(1)class window(QDialog): def __init__(self): super(window, self).__init__() #設(shè)置標(biāo)題與初始大小 self.setWindowTitle(’PyQt5界面實時更新的例子’) self.resize(400,100) #實例化文本輸入框及其初始大小 self.input=QLineEdit(self) self.input.resize(400,100) self.initUI() def initUI( self ): #實例化對象 self.backend=BackQthread() #信號連接到界面顯示槽函數(shù) self.backend.update_date.connect(self.handleDisplay) #多線程開始 self.backend.start() def handleDisplay( self,data ): #設(shè)置單行文本框的文本 self.input.setText(data)if __name__ == ’__main__’: app=QApplication(sys.argv) win=window() win.show() sys.exit(app.exec_())
運行程序,效果如下
本文主要講解了PyQt5多線程中信號與槽的詳細(xì)使用方法與實例,更多關(guān)于PyQt5信號與槽的知識請查看下面的相關(guān)鏈接
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗分享3. ASP常用日期格式化函數(shù) FormatDate()4. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效5. asp.net core項目授權(quán)流程詳解6. XMLHTTP資料7. vue使用moment如何將時間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時間格式8. CSS3中Transition屬性詳解以及示例分享9. jsp文件下載功能實現(xiàn)代碼10. 開發(fā)效率翻倍的Web API使用技巧
