python GUI庫圖形界面開發(fā)之PyQt5多線程中信號與槽的詳細使用方法與實例
PyQt5簡單多線程信號與槽的使用
最簡單的多線程使用方法是利用QThread函數(shù),展示QThread函數(shù)和信號簡單結(jié)合的方法
import sys
from 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-=1
if __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,time
from 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多線程中信號與槽的詳細使用方法與實例,更多關(guān)于PyQt5信號與槽的知識請查看下面的相關(guān)鏈接
相關(guān)文章
Python selenium模擬網(wǎng)頁點擊爬蟲交管12123違章數(shù)據(jù)
本次介紹怎么以模擬點擊方式進入交管12123爬取車輛違章數(shù)據(jù),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
Python import與from import使用及區(qū)別介紹
Python程序可以調(diào)用一組基本的函數(shù)(即內(nèi)建函數(shù)),比如print()、input()和len()等函數(shù)。接下來通過本文給大家介紹Python import與from import使用及區(qū)別介紹,感興趣的朋友一起看看吧2018-09-09
python皮爾遜相關(guān)性數(shù)據(jù)分析分析及實例代碼
這篇文章主要為大家介紹了python皮爾遜相關(guān)性分析及實例代碼,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02

