理解一段python代码

时间:2014-01-24 13:39:23

标签: python pyqt4 signals-slots

我的问题是指问题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,但我不明白为什么这很有效。

1 个答案:

答案 0 :(得分:1)

此功能为documented here

  

也可以通过将插槽作为关键字来连接信号   创建时对应于信号名称的参数   对象,或使用QObject的pyqtConfigure()方法。例如   以下三个片段是等效的:

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)