我的问题是指 How to capture output of Python's interpreter and show in a Text widget? 问题的已接受答案,它显示了如何将标准输出重定向到 QTextEdit。

作者 Ferdinand Beyer 定义了一个类 EmittingStream 如下:

from PyQt4 import QtCore

class EmittingStream(QtCore.QObject):

    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

他像这样使用这个类:
# Within your main window class...

def __init__(self, parent=None, **kwargs):
    # ...

    # Install the custom output stream
    sys.stdout = EmittingStream(textWritten=self.normalOutputWritten)

def __del__(self):
    # Restore sys.stdout
    sys.stdout = sys.__stdout__

def normalOutputWritten(self, text):
    """Append text to the QTextEdit."""
    # Maybe QTextEdit.append() works as well, but this is how I do it:
    cursor = self.textEdit.textCursor()
    cursor.movePosition(QtGui.QTextCursor.End)
    cursor.insertText(text)
    self.textEdit.setTextCursor(cursor)
    self.textEdit.ensureCursorVisible()

我不明白实例化 EmittingStream 类的行。看起来好像关键字参数 textWritten=self.normalOutputWritten 将 textWritten-signal 连接到 normalOutputWritten-slot,但我不明白为什么会这样。

最佳答案

此功能是 documented here :


act = QtGui.QAction("Action", self)
act.triggered.connect(self.on_triggered)

act = QtGui.QAction("Action", self, triggered=self.on_triggered)

act = QtGui.QAction("Action", self)
act.pyqtConfigure(triggered=self.on_triggered)

10-07 19:11