pyqt 多線程通訊

在下面例子中,定義了一個信號sigSetText, 定義了一個子線程tpython

信號sigSetText與槽函數self.setText綁定。app

子線程綁定函數self.getTimeAndSetTime, 傳入定義的信號,並修改信號。函數

 

運行原理:在子線程中修改定義的信號的值, 信號的值改變時,槽函數執行,修改界面。字體

 

(槽函數的參數就是信號的參數, 因此信號的參數個數>=槽函數的參數個多, 多出來的直接忽略)ui

#-*- coding:utf-8 -*-
#######
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
import time
import threading

class MyWindow(QDialog,QWidget):
    sigSetText = pyqtSignal(str)  ####信號定義

    def __init__(self,parent = None):
        super(MyWindow,self).__init__(parent)
        self.setFont(QFont("Roman times",14))#####設置字體
        self.resize(200,50)
        self.mainlayout = QGridLayout(self)
        self.timeLabel = QLabel()
        self.timeLabel.setText(u"時間:")
        self.mainlayout.addWidget(self.timeLabel,0,0,1,1)
        self.timeLineEdit = QLineEdit()
        self.mainlayout.addWidget(self.timeLineEdit,0,1,1,1)
        
        #信號self.sigSetText 鏈接槽函數 self.setText
        #當信號self.sigSetText發生變化時,執行槽函數self.setText
        self.sigSetText.connect(self.setText)

        #建立線程,目標函數爲self.getTimeAndSetTime
        #
        t = threading.Thread(target = self.getTimeAndSetTime,args=(self.sigSetTime,))
        t.setDaemon(True)
        t.start()

    #槽函數,參數是前面定義的信號
    def setText(self,str_time):
        self.timeLineEdit.setText(str_time)

    #目標函數,修改信號的值
    def getTimeAndSetTime(self,setTimeSignal):
        while True:
            setTimeSignal.emit(str(time.localtime().tm_hour)+":"+ str(time.localtime().tm_min) + ":" + str(time.localtime().tm_sec))######信號換髮
            time.sleep(1)



app=QApplication(sys.argv)
window=MyWindow()
window.show()
app.exec_()   
相關文章
相關標籤/搜索