加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

理解一段python代码

发布时间:2020-12-20 13:39:56 所属栏目:Python 来源:网络整理
导读:我的问题涉及问题 How to capture output of Python’s interpreter and show in a Text widget?的接受答案,该问题显示了如何将标准输出重定向到QTextEdit. 作者Ferdinand Beyer定义了一个类EmittingStream: from PyQt4 import QtCoreclass EmittingStream(
我的问题涉及问题 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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读