我有一个带有QTextEdit
框的PyQt GUI,它在代码执行期间显示print语句。我选择通过重定向sys.stdout
来完成此操作,跟随此类帖子:
Print out python console output to Qtextedit
它非常适合记录打印语句,以便用户可以看到执行过程中发生的事情,但是我希望在代码运行时更新它,而不是写入缓冲区并在最后打印出所有内容。例如,在此代码中,单击“运行”按钮将等待5秒钟以打印“正在运行...”和“完成”。函数运行后,我希望它显示'Running ...',等待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' object has no attribute 'flush'
,因此我继续在我创建的flush
类中定义Stream
,如下所示:
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()
产生了错误RecursionError: maximum recursion depth exceeded
。这是我的理解用完的地方,因为我已经尝试了其他方法来刷新打印缓冲区,但它们似乎都有这个问题。关于我做错了什么建议?