首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

PyQt Qthread 输出到textBrowser,该如何处理

2013-06-25 
PyQt Qthread 输出到textBrowser我的main()程序已经写好,输出大部分是print 输出. 我现在想使用PyQt 的Qth

PyQt Qthread 输出到textBrowser
我的main()程序已经写好,输出大部分是print 输出. 
我现在想使用PyQt 的Qthread, 当点击开始按钮时,main()执行过程中的信息实时输出到textBrowser ,

请问如何connect? 

在网上找到一个例子,但我还是转不过弯来实现我想要的功能. 麻烦使用过的指点下?谢谢.

import sys
from PyQt4 import QtGui, QtCore
import time
import random
 
 
class MyThread(QtCore.QThread):
    trigger = QtCore.pyqtSignal(int)
 
    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)
 
    def setup(self, thread_no):
        self.thread_no = thread_no
 
    def run(self):
        time.sleep(random.random()*5)  # random sleep to imitate working
        self.trigger.emit(self.thread_no)
 
 
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)
 
    def start_threads(self):
        self.threads = []              # this will keep a reference to threads
        for i in range(10):
            thread = MyThread(self)    # create a thread
            thread.trigger.connect(self.update_text)  # connect to it's signal
            thread.setup(i)            # just setting up a parameter
            thread.start()             # start the thread
            self.threads.append(thread) # keep a reference
 
    def update_text(self, thread_no):
        self.text_area.append('thread # %d finished' % thread_no)
 
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
 
    mainwindow = Main()


    mainwindow.show()
 
    sys.exit(app.exec_())




[解决办法]
引用:
比如说,我有个ping IP 的函数, 如何输出该函数的执行过程?


把ping函数放到你的pyqt代码中。

import sys
from PyQt4 import QtGui, QtCore
import time
import random
import subprocess
  
class MyThread(QtCore.QThread):
    trigger = QtCore.pyqtSignal(str) # trigger传输的内容是字符串
  
    def __init__(self, parent=None):
        super(MyThread, self).__init__(parent)
  
    def run(self):
        time.sleep(random.random()*5)  # random sleep to imitate working
        self.ping_host("http://www.yahoo.com")
    
    # 把下面代码中的print改为trigger.emit
    def ping_host(self, host):
        subprocess.call(['arp', '-d'], shell=True, stdout=open('NUL', 'w'), stderr=subprocess.STDOUT)
        # print('Pinging  ' + host + u', Please waiting...')
        self.trigger.emit('Pinging  ' + host + u', Please waiting...\n')
        for i in range(70):
            returncode = subprocess.call('ping -n 1 -w 1 %s' % host, shell = True, stdout = open('NUL', 'w'), \
                                         stderr = subprocess.STDOUT)
            if returncode != 0 :
                self.trigger.emit('.')
                # sys.stdout.write('.')
                # sys.stdout.flush()
                time.sleep(1)
                continue
            else:
                # print('OK')
                self.trigger.emit('OK\n')
                return


        # print(u'\t\n\nCannot connect ' + host +  '!')
        self.trigger.emit(u'\t\n\nCannot connect ' + host +  '!\n')

  
  
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)
  
    def start_threads(self):
        self.threads = []              # this will keep a reference to threads
        thread = MyThread(self)    # create a thread
        thread.trigger.connect(self.update_text)  # connect to it's signal
        thread.start()             # start the thread
        self.threads.append(thread) # keep a reference
  
    def update_text(self, message):
        self.text_area.insertPlainText(message) # use insertPlainText to prevent the extra newline character
  
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
  
    mainwindow = Main()
    mainwindow.show()
  
    sys.exit(app.exec_())


[解决办法]

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore
import sys, subprocess, time

class myThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)

def run(self):
self.pipe = subprocess.Popen('ping 127.0.0.1', stdout=subprocess.PIPE)

while self.pipe.poll() == None:
self.emit(QtCore.SIGNAL("getLog(QString)"), QtCore.QString.fromUtf8((self.pipe.stdout.readline().rstrip())))
time.sleep(0.2)

restInfo = self.pipe.stdout.readlines()
if len(restInfo):
for line in restInfo:
self.emit(QtCore.SIGNAL("writeLog(QString)"), QtCore.QString.fromUtf8((line.rstrip())))

class MainWindow(object):


def __init__(self, Dialog):
self.bt = QtGui.QWidget(Dialog)
Dialog.setMinimumWidth(400)
Dialog.setMinimumHeight(300)
self.button = QtGui.QPushButton(self.bt)
self.button.setText('Start')
self.button_2 = QtGui.QPushButton(self.bt)
self.button_2.setText('Stop')
self.text = QtGui.QPlainTextEdit(self.bt)
self.text.setFont(QtGui.QFont('Courier New', 10))
self.verticalLayout = QtGui.QVBoxLayout(Dialog)
self.verticalLayout.addWidget(self.button)
self.verticalLayout.addWidget(self.button_2)
self.verticalLayout.addWidget(self.text)

self.th1 = myThread()

QtCore.QObject.connect(self.th1, QtCore.SIGNAL("getLog(QString)"), self.writeLog)
QtCore.QObject.connect(self.button, QtCore.SIGNAL('clicked()'), self.run)
QtCore.QObject.connect(self.button_2, QtCore.SIGNAL('clicked()'), self.stop)


def run(self):
self.th1.start()

def stop(self):
self.th1.pipe.terminate()

def writeLog(self, str):
self.text.appendPlainText(str)

app = QtGui.QApplication(sys.argv)
dlg = QtGui.QDialog()
main = MainWindow(dlg)
dlg.show()
sys.exit(app.exec_())

热点排行