python - 理解一段python代码

标签 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.normalOutputWrittentextWritten-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/

相关文章:

python - 内存未释放 - PyQt4

excel - PyQt : How to sort QTableView columns(strings and numericals)

python - PySide(或 PyQt)信号和槽基础知识

python - 如何修复我的 'Jump' ?

python - matplotlib:隐藏子图并用其他子图填充空间

python - pyside-uic/pyuic4 : command not found

python - 如何选择包含按钮的 QTableWidget 单元格

qt - 有没有办法从Qt中的另一个信号触发信号?

python - 如何从一个列表中减去另一个列表中的数字,只要它们具有相同的索引? (Python)

python - 在线求职很乏味。帮我自动化