不能在pyqt插槽中实时输出日志

不能在pyqt插槽中实时输出日志

问题描述:

我创建了一个QPushButton控件和一个QTextEdit控件,我想要的是一旦我点击按钮,系统就会执行一个外部程序,并将日志输出到QTextEdit小部件。不能在pyqt插槽中实时输出日志

问题是日志不能连续发送到QTextEdit小部件。它在完成外部程序后立即发送。为什么?

这是我的代码:

class Window(Qwidget): 
    def __init__(self, parent=None): 
     ... 
     self.button.clicked.connect(self.onStart) 
     ... 
    def onStart(self): 
     # keep sending log in this solt, similar to my external program 
     for i in range(10000): 
      self.logger.debug(str(i)) 

,我已经重定向self.logger.debug() sys.stdout来,并输出日志在一个线程中的QTextEdit控件。

class myThread(QThread): 
    printText = pyqtSignal(str) 

    def __init__(self, parent=None): 
     super(myThread,self).__init__(parent) 

    def write(self, output): 
     self.printText.emit(output) 

    def flush(self): 
     pass 

    def run(self): 
     while True: 
      time.sleep(.1) 

当我点击按钮时,pyqt卡在循环for i in range(10000)并没有显示任何内容。几秒钟后,所有输出日志都会一次显示,而不是实时显示。

+0

代码示例中没有任何内容在单独的线程中运行 - 它全部在主线程中运行,因此将阻止主事件循环。 – ekhumoro

由于ekhumoro的建议,我把循环中的一个线索:

def onStart(self): 
    _thread.start_new_thread(self.myLoop,()) 
def myLoop(self): 
    for i in range(10000): 
     self.logger.debug(i) 

_thread模块符合我的功能需求和良好的工作在这里。如果您需要与myLoop(),threadingqueue中的其他线程通信更强大。