我使用 PyQt4 在 Python 中实现了一个非常简单的日志查看器。
我有兴趣使用它来跟踪程序的执行,因此当新行附加到日志文件时必须刷新列表视图。
这是我的实现(没有手表):
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class LogEntryModel(QAbstractListModel):
    def __init__(self, logfile, parent=None):
        super(LogEntryModel, self).__init__(parent)
        self.slurp(logfile)
    def rowCount(self, parent=QModelIndex()):
        return len(self.entries)
    def data(self, index, role):
        if index.isValid() and role == Qt.DisplayRole:
            return QVariant(self.entries[index.row()])
        else:
            return QVariant()        
    def slurp(self, logfile):
        self.entries = []        
        with open(logfile, 'rb') as fp:
            for line in fp.readlines():
                tokens = line.strip().split(' : ')
                sender = tokens[2]
                message = tokens[4]
                entry = "%s %s" % (sender, message)
                self.entries.append(entry)
class LogViewerForm(QDialog):
    def __init__(self, logfile, parent=None):
        super(LogViewerForm, self).__init__(parent)
        # build the list widget
        list_label = QLabel(QString("<strong>MoMo</strong> Log Viewer"))
        list_model = LogEntryModel(logfile)        
        self.list_view = QListView()
        self.list_view.setModel(list_model)
        list_label.setBuddy(self.list_view)
        # define the layout
        layout = QVBoxLayout()
        layout.addWidget(list_label)
        layout.addWidget(self.list_view)
        self.setLayout(layout)
if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = LogViewerForm(sys.argv[1])
    form.show()
    app.exec_()
如前所述,应用程序按预期工作:打开文件,解析内容(拆分' : '并创建一个列表),并使用QListView.
有一个QFileSystemWatcher类发出fileChanged信号,但我不知道connect它在哪里以及如何触发向数据添加一行并刷新视图事件。
有什么帮助吗?
谢谢。