QFileSystemModel QTableView日期修改突出显示

问题描述 投票:0回答:1

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

[我想知道是否可以在“修改日期”列中突出显示具有相同值的行,例如,如果今天有两个或多个文件被修改,则该行以绿色突出显示,昨天修改的内容以绿色突出显示,但阴影较浅,等等。

python pyqt qtableview qfilesystemmodel
1个回答
0
投票

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

  • 重写模型的data()方法,以使返回值与角色Qt.BackgroundRole相关联。

  • 使用QIdentityProxyModel来修改与Qt.BackgroundRole关联的值,类似于先前的选项

  • 使用QStyledItemDelegate修改backgroundBrushQStyleOptionViewItem属性。

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

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()
© www.soinside.com 2019 - 2024. All rights reserved.