python GUI庫(kù)圖形界面開(kāi)發(fā)之PyQt5多線程中信號(hào)與槽的詳細(xì)使用方法與實(shí)例
最簡(jiǎn)單的多線程使用方法是利用QThread函數(shù),展示QThread函數(shù)和信號(hào)簡(jiǎn)單結(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)建一個(gè)線程實(shí)例并設(shè)置名稱 變量 信號(hào)與槽 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): #自定義信號(hào)參數(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ù),運(yùn)行多線程 self.times = int(val) self.run() def run( self ): #當(dāng)次數(shù)大于0以及名稱不為空時(shí)執(zhí)行代碼 while self.times>0 and self.identity: #發(fā)射信號(hào),觸發(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_())
運(yùn)行如下
有時(shí)候在開(kāi)發(fā)程序時(shí)會(huì)經(jīng)常執(zhí)行一些耗時(shí)的操作,這樣就會(huì)導(dǎo)致界面卡頓,這也是多線程的應(yīng)用范圍之一,這樣我們就可以創(chuàng)建多線程,使用主線程更新界面,使用子線程后臺(tái)處理數(shù)據(jù),最后將結(jié)果顯示在界面上
import sys,timefrom PyQt5.QtCore import *from PyQt5.QtWidgets import *class BackQthread(QThread): #自定義信號(hào)為str參數(shù)類型 update_date=pyqtSignal(str) def run( self ): while True: #獲得當(dāng)前系統(tǒng)時(shí)間 data=QDateTime.currentDateTime() #設(shè)置時(shí)間顯示格式 curTime=data.toString(’yyyy-MM-dd hh:mm:ss dddd’) #發(fā)射信號(hào) 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界面實(shí)時(shí)更新的例子’) self.resize(400,100) #實(shí)例化文本輸入框及其初始大小 self.input=QLineEdit(self) self.input.resize(400,100) self.initUI() def initUI( self ): #實(shí)例化對(duì)象 self.backend=BackQthread() #信號(hào)連接到界面顯示槽函數(shù) self.backend.update_date.connect(self.handleDisplay) #多線程開(kāi)始 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_())
運(yùn)行程序,效果如下
本文主要講解了PyQt5多線程中信號(hào)與槽的詳細(xì)使用方法與實(shí)例,更多關(guān)于PyQt5信號(hào)與槽的知識(shí)請(qǐng)查看下面的相關(guān)鏈接
相關(guān)文章:
1. WML語(yǔ)法大全與相關(guān)介紹第1/3頁(yè)2. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)3. 匹配模式 - XSL教程 - 44. 詳解JS前端使用迭代器和生成器原理及示例5. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)6. 詳解CSS偽元素的妙用單標(biāo)簽之美7. 使用css實(shí)現(xiàn)全兼容tooltip提示框8. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法9. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向10. ASP編碼必備的8條原則
