Best way to display logs in pyqt?

前端 未结 6 954
迷失自我
迷失自我 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:19

    Here's a complete working example based on mfitzp's answer:

    import sys
    from PyQt4 import QtCore, QtGui
    import logging
    
    # Uncomment below for terminal log messages
    # logging.basicConfig(level=logging.DEBUG, format=' %(asctime)s - %(name)s - %(levelname)s - %(message)s')    
    
    class QPlainTextEditLogger(logging.Handler):
        def __init__(self, parent):
            super().__init__()
            self.widget = QtGui.QPlainTextEdit(parent)
            self.widget.setReadOnly(True)    
    
        def emit(self, record):
            msg = self.format(record)
            self.widget.appendPlainText(msg)    
    
    
    class MyDialog(QtGui.QDialog, QPlainTextEditLogger):
        def __init__(self, parent=None):
            super().__init__(parent)    
    
            logTextBox = QPlainTextEditLogger(self)
            # You can format what is printed to text box
            logTextBox.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
            logging.getLogger().addHandler(logTextBox)
            # You can control the logging level
            logging.getLogger().setLevel(logging.DEBUG)
    
            self._button = QtGui.QPushButton(self)
            self._button.setText('Test Me')    
    
            layout = QtGui.QVBoxLayout()
            # Add the new logging box widget to the layout
            layout.addWidget(logTextBox.widget)
            layout.addWidget(self._button)
            self.setLayout(layout)    
    
            # Connect signal to slot
            self._button.clicked.connect(self.test)    
    
        def test(self):
            logging.debug('damn, a bug')
            logging.info('something to remember')
            logging.warning('that\'s not right')
            logging.error('foobar')
    
    if (__name__ == '__main__'):
        app = None
        if (not QtGui.QApplication.instance()):
            app = QtGui.QApplication([])
        dlg = MyDialog()
        dlg.show()
        dlg.raise_()
        if (app):
            app.exec_()
    

提交回复
热议问题