Python 刷新PyQt中定向到QTextEdit的输出
我有一个PyQt图形用户界面,带有一个Python 刷新PyQt中定向到QTextEdit的输出,python,pyqt,Python,Pyqt,我有一个PyQt图形用户界面,带有一个QTextEdit框,在代码执行期间显示打印语句。我选择通过重定向sys.stdout来实现这一点,如下所示: 它非常适合记录print语句,这样用户就可以看到执行过程中发生了什么,但是我希望在代码运行时更新它,而不是写入缓冲区并在最后打印出所有内容。例如,在这段代码中,单击“运行”按钮将等待5秒钟打印“运行…”和“完成”。在函数运行后,我希望它显示“运行…”,等待5秒钟,然后显示“完成” 以下是我编写的代码的基本内容: import sys import
QTextEdit
框,在代码执行期间显示打印语句。我选择通过重定向sys.stdout
来实现这一点,如下所示:
它非常适合记录print语句,这样用户就可以看到执行过程中发生了什么,但是我希望在代码运行时更新它,而不是写入缓冲区并在最后打印出所有内容。例如,在这段代码中,单击“运行”按钮将等待5秒钟打印“运行…”和“完成”。在函数运行后,我希望它显示“运行…”,等待5秒钟,然后显示“完成”
以下是我编写的代码的基本内容:
import sys
import time
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QTextEdit
from PyQt5 import QtCore, QtGui
class Stream(QtCore.QObject):
"""Redirects console output to text widget."""
newText = QtCore.pyqtSignal(str)
def write(self, text):
self.newText.emit(str(text))
class GenMast(QMainWindow):
"""Main application window."""
def __init__(self):
super().__init__()
self.initUI()
# Custom output stream.
sys.stdout = Stream(newText=self.onUpdateText)
def onUpdateText(self, text):
"""Write console output to text widget."""
cursor = self.process.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
cursor.insertText(text)
self.process.setTextCursor(cursor)
self.process.ensureCursorVisible()
def closeEvent(self, event):
"""Shuts down application on close."""
# Return stdout to defaults.
sys.stdout = sys.__stdout__
super().closeEvent(event)
def initUI(self):
"""Creates UI window on launch."""
# Button for generating the master list.
btnGenMast = QPushButton('Run', self)
btnGenMast.move(450, 100)
btnGenMast.resize(100, 100)
btnGenMast.clicked.connect(self.genMastClicked)
# Create the text output widget.
self.process = QTextEdit(self, readOnly=True)
self.process.ensureCursorVisible()
self.process.setLineWrapColumnOrWidth(500)
self.process.setLineWrapMode(QTextEdit.FixedPixelWidth)
self.process.setFixedWidth(400)
self.process.setFixedHeight(150)
self.process.move(30, 100)
# Set window size and title, then show the window.
self.setGeometry(300, 300, 600, 300)
self.setWindowTitle('Generate Master')
self.show()
def genMastClicked(self):
"""Runs the main function."""
print('Running...')
time.sleep(5)
print('Done.')
if __name__ == '__main__':
# Run the application.
app = QApplication(sys.argv)
app.aboutToQuit.connect(app.deleteLater)
gui = GenMast()
sys.exit(app.exec_())
我首先尝试在print语句中设置flush=True
。但是,我遇到了错误“Stream”对象没有属性“flush”
,因此我继续在我创建的流
类中定义flush
,如下所示:
class Stream(QtCore.QObject):
"""Redirects console output to text widget."""
newText = QtCore.pyqtSignal(str)
def write(self, text):
self.newText.emit(str(text))
def flush(self):
sys.stdout.flush()
这产生了错误
递归错误:超过了最大递归深度。这就是我的理解力耗尽的地方,因为我尝试了其他方法来刷新打印缓冲区,但它们似乎都有这个问题。关于我做错了什么有什么建议吗?我不知道Qt,所以我没有资格写一个答案,但你需要在一个单独的线程中运行打印功能。明白了,我想知道这是否会是线程问题。冲洗打印缓冲区似乎可行,但我得到的印象是,这不是解决方案。@AlexanderTrevelyan执行线程操作了吗?我现在也遇到了同样的问题是的!线程是解决方案。我学习了一些线程教程,并在模块中添加了一个工人类。我的工人阶级与这里的工人阶级一模一样: