view python/ide/logview.py @ 297:a6f61e9a9d5c

Added docs requirements
author Windel Bouwman
date Sun, 01 Dec 2013 17:35:54 +0100
parents 7b38782ed496
children dcae6574c974
line wrap: on
line source

#!/usr/bin/python

import sys
import os
import logging
import datetime

from PyQt4.QtGui import QApplication, QWidget, QTableView, QVBoxLayout
from PyQt4.QtGui import QHeaderView
from PyQt4.QtCore import Qt
from PyQt4.QtCore import QAbstractTableModel

def formatTime(t):
    t2 = datetime.datetime.fromtimestamp(t)
    return t2.strftime('%H:%M:%S')

class LogModel(QAbstractTableModel):
    def __init__(self):
        super().__init__()
        self.entries = []
        self.headers = ['Time', 'Level', 'Logger', 'Message']
        self.txts = []
        self.txts.append(lambda e: str(formatTime(e.created)))
        self.txts.append(lambda e: str(e.levelname))
        self.txts.append(lambda e: str(e.name))
        self.txts.append(lambda e: str(e.msg))

    def rowCount(self, parent):
        return len(self.entries)
        
    def columnCount(self, parent):
        return len(self.headers)

    def data(self, index, role):
        if not index.isValid():
            return
        row, col = index.row(), index.column()
        if role == Qt.DisplayRole:
            le = self.entries[row]
            return self.txts[col](le)

    def headerData(self, section, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.headers[section]
            
    def newLog(self, x):
        self.entries.append(x)
        self.modelReset.emit()


class LogView(QWidget):
    """ Log view component """
    def __init__(self, parent=None):
        super().__init__(parent)
        l = QVBoxLayout(self)
        self.tv = QTableView(self)
        self.tv.horizontalHeader().setStretchLastSection(True)
        l.addWidget(self.tv)
        self.lm = LogModel()
        self.tv.setModel(self.lm)
    
        class MyHandler(logging.Handler):
            def emit(self2, x):
                self.lm.newLog(x)
                self.tv.scrollToBottom()
                for i in range(3):
                    self.tv.resizeColumnToContents(i)

        logging.getLogger().addHandler(MyHandler())


if __name__ == '__main__':
    app = QApplication(sys.argv)
    lv = LogView()
    lv.show()
    lv.resize(600, 200)
    logging.error('Error!!!')
    logging.warn('Warn here!')
    app.exec_()