python - 使用文件监视通过 PyQt4 刷新日志查看器

标签 python pyqt4 qlistview qabstractlistmodel

我使用 PyQt4 在 Python 中实现了一个非常简单的日志查看器。

我有兴趣使用它来跟踪程序的执行,因此当新行附加到日志文件时必须刷新 ListView 。

这是我的实现(没有 watch ):

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它以及如何触发 向数据添加一行并刷新 View 事件。

有什么帮助吗?

谢谢。

最佳答案

我对 python 和 pyqt 很陌生,但这在这里“有效”:

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)
        self.logfile = 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)

        self.watcher = QFileSystemWatcher([logfile], parent=None)
        self.connect(self.watcher, SIGNAL('fileChanged(const QString&)'), self.update_log)

        # build the list widget
        list_label = QLabel(QString("<strong>MoMo</strong> Log Viewer"))
        list_model = LogEntryModel(logfile)
        self.list_model = list_model
        self.list_view = QListView()
        self.list_view.setModel(self.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)

    def update_log(self):
        print 'file changed'
        self.list_model.slurp(self.list_model.logfile)
        self.list_view.updateGeometries()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    form = LogViewerForm(sys.argv[1])
    form.show()
    app.exec_()

但请注意,这可能不是一个好方法。 您可能想要流式传输日志文件... 也许更有经验的人可以帮忙。

关于python - 使用文件监视通过 PyQt4 刷新日志查看器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4785588/

相关文章:

python - python中类内部类的命名空间

python - 在执行任务之前禁用 QPushButton

python - Django - 如何限制哪些用户可以连接到套接字?

python - 为什么比较具有相同值的两个属性类型 `float` 和 `int` 在 Python 中得到 `False`?

python - 不断收到 Kattis 问题的运行时错误

python - 如何为 QDockWidget 的选项卡和窗口标题设置不同的文本?

python - 如何使 QTableWidget 中的单元格只读?

python - 选择 QListView 中的所有项目并在目录更改时取消选择所有项目

c++ - Qt 的 ItemViewsNG 项目的状态如何?

qt - QListView 放置指示器样式