QFileSystemModel QTableView 修改日期高亮 [英] QFileSystemModel QTableView Date Modified highlighting

查看:74
本文介绍了QFileSystemModel QTableView 修改日期高亮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 QFileSystemModel 和 QTableView 制作一个小文件浏览器.

I am trying to make a little file browser using QFileSystemModel and QTableView.

我想知道是否可以在修改日期"列中突出显示具有相同值的行,例如,如果我有两个或多个今天修改的文件,行以绿色突出显示,昨天修改的那些以绿色但较浅的阴影等突出显示.

I was wondering if it is possible to highlight rows with same value in "Date Modified" column, for instance if I have two or more files which been modified today row gets highlighted in green, those modified yesterday highlighted in green but lighter shade, etc.

推荐答案

要更改背景颜色,有几个选项,例如:

To change the background color there are several options such as:

  • 覆盖模型的data()方法,使得返回值与角色Qt.BackgroundRole相关联.

  • override the data() method of the model so that the return value associated with the role Qt.BackgroundRole.

使用 QIdentityProxyModel 修改与 Qt.BackgroundRole 关联的值,类似于上一个选项

Use a QIdentityProxyModel that modifies the value associated with Qt.BackgroundRole similar to the previous option

使用QStyledItemDelegate来修改QStyleOptionViewItembackgroundBrush属性.

最简单的选项是最后一个选项,所以我将展示您的实现:

The simplest option is the last option so I will show your implementation:

from PyQt5 import QtCore, QtGui, QtWidgets


class DateDelegate(QtWidgets.QStyledItemDelegate):
    def initStyleOption(self, option, index):
        super().initStyleOption(option, index)
        model = index.model()
        if isinstance(model, QtWidgets.QFileSystemModel):
            dt = model.lastModified(index)

            today = QtCore.QDateTime.currentDateTime()
            yesterday = today.addDays(-1)
            if dt < yesterday:
                option.backgroundBrush = QtGui.QColor(0, 255, 0)
            else:
                option.backgroundBrush = QtGui.QColor(0, 155, 0)


def main():
    import sys

    app = QtWidgets.QApplication(sys.argv)

    path_dir = QtCore.QDir.currentPath()

    view = QtWidgets.QTableView()
    model = QtWidgets.QFileSystemModel()
    view.setModel(model)
    model.setRootPath(path_dir)

    view.setRootIndex(model.index(path_dir))

    view.show()

    delegate = DateDelegate(view)
    view.setItemDelegate(delegate)

    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

这篇关于QFileSystemModel QTableView 修改日期高亮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆