首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >刷新输出定向到PyQt中的QTextEdit

刷新输出定向到PyQt中的QTextEdit
EN

Stack Overflow用户
提问于 2018-12-13 04:54:40
回答 2查看 0关注 0票数 0

我有一个PyQt GUI,其中包含一个QTextEdit在代码执行期间显示print语句的框。我选择通过重定向来执行此操作sys.stdout,按照以下这样的帖子:

将python控制台输出打印到Qtextedit

它非常适合记录打印语句,以便用户可以看到执行过程中发生的事情,但是我希望在代码运行时更新它,而不是写入缓冲区并在最后打印出所有内容。例如,在此代码中,单击“运行”按钮将等待5秒钟以打印“正在运行...”和“完成”。函数运行后,我希望它显示'Running ...',等待5秒,然后显示'Done'。

以下是我编写的代码的基础知识:

代码语言:javascript
复制
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_())

我首先尝试flush=True在print语句中进行设置。但是,我遇到了错误'Stream' object has no attribute 'flush',所以我继续在我创建flushStream类中定义,如下所示:

代码语言:javascript
复制
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:超出了最大递归深度。 这是我的理解用完的地方,因为我已经尝试了其他方法来刷新打印缓冲区,但它们似乎都有这个问题。 关于我做错的任何建议?

EN

Stack Overflow用户

发布于 2018-12-13 14:20:49

这种情况下的问题与flush相关,但是使用了time.sleep()。 time.sleep()是一个阻塞任务,不允许Qt事件循环运行,从而阻止信号正常工作和GUI更新,解决方案是使用QTimer和QEventLoop替换该GUI睡眠。

代码语言:javascript
复制
def genMastClicked(self):
    """Runs the main function."""
    print('Running...')
    loop = QEventLoop()
    QTimer.singleShot(5000, loop.quit)
    loop.exec_()
    print('Done.')

完整代码:

代码语言:javascript
复制
import sys
import time
from PyQt5.QtCore import QObject, pyqtSignal, QEventLoop, QTimer
from PyQt5.QtWidgets import QMainWindow, QPushButton, QApplication, QTextEdit
from PyQt5.QtGui import QTextCursor


class Stream(QObject):
    """Redirects console output to text widget."""
    newText = 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(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...')
        loop = QEventLoop()
        QTimer.singleShot(5000, loop.quit)
        loop.exec_()
        print('Done.')


if __name__ == '__main__':
    # Run the application.
    app = QApplication(sys.argv)
    app.aboutToQuit.connect(app.deleteLater)
    gui = GenMast()
    sys.exit(app.exec_())
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档