PYQT中QThread输出到textBrowser
問(wèn)題概述
在PYQT中,有時(shí)我們會(huì)需要將log信息等實(shí)時(shí)打印到ui控件上,但是由于PYQT的進(jìn)程保護(hù)機(jī)制,我們無(wú)法像使用print函數(shù)中那樣,直接使用就能打印出來(lái)信息。所以通常都會(huì)發(fā)現(xiàn),PYQT中的UI控件,比如QTextBrowser,使用它的append()函數(shù)和print函數(shù)同時(shí)來(lái)打印信息,往往print會(huì)將信息實(shí)時(shí)一點(diǎn)點(diǎn)打印出來(lái),而QTextBrowser則不會(huì),反而會(huì)等到這一段程序運(yùn)行結(jié)束后,一次性把所有信息打印出來(lái)。
前面的描述有點(diǎn)繞,再簡(jiǎn)述一下:PYQT中在控件(比如QTextBrowser)上無(wú)法像print函數(shù)那樣實(shí)時(shí)打印信息,而是會(huì)在程序段結(jié)束后,一次性全部打印上去。
在網(wǎng)上查找資料后,看到了解決方案:http://bbs.csdn.net/topics/390478497
注:那個(gè)帖子有點(diǎn)老了,有些程序也許運(yùn)行不通,我只是根據(jù)里面給的自己修改的。
解決思路
完整程序
import sys from PyQt4 import QtGui,QtCore import time import randomclass MyThread(QtCore.QThread):trigger = QtCore.pyqtSignal(str)def __init__(self, parent=None):super(MyThread, self).__init__(parent)def run_(self, message):#time.sleep(random.random() * 5)self.trigger.emit(message)class Main(QtGui.QMainWindow):def __init__(self, parent=None):super(Main, self).__init__(parent)self.text_area = QtGui.QTextBrowser()self.thread_button = QtGui.QPushButton('Start threads')self.thread_button.clicked.connect(self.start_threads)central_widget = QtGui.QWidget()central_layout = QtGui.QHBoxLayout()central_layout.addWidget(self.text_area)central_layout.addWidget(self.thread_button)central_widget.setLayout(central_layout)self.setCentralWidget(central_widget)self.threads = MyThread(self)self.threads.trigger.connect(self.update_text)self.thread_no = 0def start_threads(self):self.thread_no += 1message = "cnt:{0}".format(self.thread_no)self.threads.run_(message) # start the threadprint(message)def update_text(self, message):# self.text_area.append('thread # %d finished'%thread_no)# print('thread # %d finished'%thread_no)self.text_area.append(message)if __name__ == '__main__':app = QtGui.QApplication(sys.argv)mainWindow = Main()mainWindow.show()sys.exit(app.exec_())簡(jiǎn)要說(shuō)明
前面給出了完整程序,這里撿幾個(gè)要點(diǎn)說(shuō)明一下:
trigger = QtCore.pyqtSignal(str)
創(chuàng)建一個(gè)信號(hào)trigger,傳輸字符串類型的數(shù)據(jù)。
def run_(self, message):self.trigger.emit(message)
在線程類中另外定義的一個(gè)函數(shù),主要就是調(diào)用trigger的emit函數(shù)(向trigger這個(gè)通道的入口灌水)。
self.threads = MyThread(self) self.threads.trigger.connect(self.update_text)
創(chuàng)建線程類的實(shí)例,并將信號(hào)trigger連接到槽函數(shù)update_text。
def update_text(self, message):# self.text_area.append('thread # %d finished'%thread_no)# print('thread # %d finished'%thread_no)self.text_area.append(message)
定義槽函數(shù)update_text,在控件上打印信息(前面定義了信號(hào)傳輸?shù)氖莝tr,所以這里直接打印)。
運(yùn)行結(jié)果
后記
自己正好碰到了這個(gè)問(wèn)題,所以就記錄一下,以便以后查閱。
吐槽:最近總碰到人在博客上問(wèn)我為什么程序跑不通之類的問(wèn)題,我也不知道你的環(huán)境是什么樣的,少了什么依賴項(xiàng),請(qǐng)自行解決,我只能盡力保證在自己的電腦上運(yùn)行通過(guò),能力有限請(qǐng)見(jiàn)諒。
總結(jié)
以上是生活随笔為你收集整理的PYQT中QThread输出到textBrowser的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python dlib学习(十一):眨眼
- 下一篇: 基于PYQT编写一个人脸识别软件(2)