4

I want to use PySide to create a simple application just to output from python logging.

def mpm_print():
    print 'OK'

def mpm_log():
   log.info('OK')

class LabWindow(QtGui.QMainWindow):
    def __init__(self):
        super(LabWindow, self).__init__()

        self.initUI()
        mpm_print()
        mpm_log()

    def initUI(self):

        font = QtGui.QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.qtxt = QtGui.QTextEdit(self)
        self.qtxt.resize(self.size())
        self.qtxt.setReadOnly(True)
        self.qtxt.setFont(font)

        self.resize(640, 512)
        self.setWindowTitle('Efficient Algorithms Lab')

        self.show()

I would like to know:

  • How can I redirect stdout to write to the QTextEdit ?
  • How can I write a logging.Handler to log to QTextEdit ?

Thanks

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
gosom
  • 1,299
  • 3
  • 16
  • 35

1 Answers1

5

This is copy-pasted from PyQt mailing-list, but should be applicable to PySide

This should do what you want.

class OutLog:
    def __init__(self, edit, out=None, color=None):
        """(edit, out=None, color=None) -> can write stdout, stderr to a
        QTextEdit.
        edit = QTextEdit
        out = alternate stream ( can be the original sys.stdout )
        color = alternate color (i.e. color stderr a different color)
        """
        self.edit = edit
        self.out = None
        self.color = color

    def write(self, m):
        if self.color:
            tc = self.edit.textColor()
            self.edit.setTextColor(self.color)

        self.edit.moveCursor(QtGui.QTextCursor.End)
        self.edit.insertPlainText( m )

        if self.color:
            self.edit.setTextColor(tc)

        if self.out:
            self.out.write(m)

Example usage:

import sys
sys.stdout = OutLog( edit, sys.stdout)
sys.stderr = OutLog( edit, sys.stderr, QtGui.QColor(255,0,0) )
rlacko
  • 571
  • 3
  • 11
  • Cool hack! Since the attributes `sys.stdout` and `sys.stderr` expect [file objects](https://docs.python.org/3/glossary.html#term-file-object) to be linked to them, you just created a new class which has the same class function names as a `file` object (`write` in this case). I'm guessing with something a bit more elaborate you could also use this approach to read `stdin` from a `qlineedit`? – RTbecard May 17 '20 at 13:29