4

My question refers to the accepted answer of the question How to capture output of Python's interpreter and show in a Text widget? which shows how to redirect standard output to a QTextEdit.

The author, Ferdinand Beyer, defines a class EmittingStream as such:

from PyQt4 import QtCore

class EmittingStream(QtCore.QObject):

    textWritten = QtCore.pyqtSignal(str)

    def write(self, text):
        self.textWritten.emit(str(text))

He uses the class like this:

# 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()

I don't understand the line that instantiates the EmittingStream class. It looks as if the keyword argument textWritten=self.normalOutputWritten connects the textWritten-signal to the normalOutputWritten-slot, but I do not understand why this works.

Community
  • 1
  • 1
jan
  • 1,408
  • 13
  • 19
  • What exactly about this don't you understand? It's dead simple, you pass a reference to a function and the `EmittingStream` constructor (which is inherited from `QtCore.QObject`) connects it to the signal. – l4mpi Jan 24 '14 at 13:58
  • @l4mpi: That was exactly what I needed to know, it didn't occur to me that this behaviour is simply due to QObject's constructor. – jan Jan 24 '14 at 22:31

1 Answers1

1

This feature is 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)
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677