我的问题是指问题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 :
It is also possible to connect signals by passing a slot as a keyword argument corresponding to the name of the signal when creating an object, or using the pyqtConfigure() method of QObject. For example the following three fragments are equivalent:
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)
关于python - 理解一段python代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21334197/