Best way to display logs in pyqt?

前端 未结 6 988
迷失自我
迷失自我 2020-12-01 01:42

I am currently working on a GUI using qt designer. I am wondering how I should go about printing strings on the GUI that acts like a logger window. I am using pyqt5.

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 02:32

    If you are using the Python logging module to can easily create a custom logging handler that passes the log messages through to a QPlainTextEdit instance (as described by Christopher).

    To do this you first subclass logging.Handler. In this __init__ we create the QPlainTextEdit that will contain the logs. The key bit here is that the handle will be receiving messages via the emit() function. So we overload this function and pass the message text into the QPlainTextEdit.

    import logging
    
    class QPlainTextEditLogger(logging.Handler):
        def __init__(self, parent):
            super(Logger, self).__init__()
    
            self.widget = QPlainTextEdit(parent)
            self.widget.setReadOnly(True)
    
        def emit(self, record):
            msg = self.format(record)
            self.widget.textCursor().appendPlainText(msg)
    
        def write(self, m):
            pass
    

    Create an object from this class, passing it the parent for the QPlainTextEdit (e.g. the main window, or a layout). You can then add this handler for the current logger.

    # Set up logging to use your widget as a handler
    log_handler = QPlainTextEditLogger()
    logging.getLogger().addHandler(log_handler)
    

提交回复
热议问题