【问题标题】:Understanding a piece of python code理解一段python代码
【发布时间】:2014-01-24 13:39:23
【问题描述】:

我的问题是指问题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 信号连接到 normalOutputWritten 插槽,但我不明白为什么这行得通。

【问题讨论】:

  • 这到底是怎么回事你不明白吗?这很简单,你传递一个函数的引用,然后 EmittingStream 构造函数(继承自 QtCore.QObject)将它连接到信号。
  • @l4mpi:这正是我需要知道的,我没有想到这种行为仅仅是由于 QObject 的构造函数。

标签: python pyqt4 signals-slots


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多