【问题标题】:QFileSystemModel QTableView Date Modified highlightingQFileSystemModel QTableView 日期修改高亮
【发布时间】:2020-10-04 05:20:57
【问题描述】:

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

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

【问题讨论】:

    标签: python pyqt qtableview qfilesystemmodel


    【解决方案1】:

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

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

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

    • 使用QStyledItemDelegate 修改QStyleOptionViewItembackgroundBrush 属性。

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

    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()
    

    【讨论】:

      猜你喜欢
      • 2020-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 2016-11-10
      • 1970-01-01
      相关资源
      最近更新 更多