I have a QListView
with a QFileSystemModel
. Based on the selection in QTreeView
, QListView
shows the contents of the folder.
Now I need to change the color of the file names depending on some conditions.
The initial idea would be to iterate over the elements in a QListView and set the color for each element depending on whether the condition is met. However, this seems impossible, since the setData()
QFileSystemModel
only accepts changes to EditRole
, ignoring something like [see this ]
self.FileModel.setData(index, QtGui.QBrush(QtCore.Qt.red), role=QtCore.Qt.ForegroundRole)
It is also indicated here and the sentence in the latter was a subclass of QItemDelegate
for the purpose of coloring elements in a QListView.
Therefore, I subclassed QStyledItemDelegate
and redefined its paint()
method to show the file name in green, if the condition is met, this works fine. However, now it looks pretty ugly: file icons are lost and the mouse_over effect no longer works.
Although this subclassing works randomly anyway, my top level question will be
- Is there a way to colorize elements in a
QListView
related to a condition-based QFileSystemModel
?
Now provided that this may not be the case, and stick with the QItemDelegate subclass,
- Is there a way to bring back the original behavior with good choices and icons?
- Does anyone know which ItemDelegate is initially used for QFileSystemModel in a QListView and how to use it?
- Is it possible to get the source code and copy the drawing method from there?
Below is the minimal code that uses subclassification and shows user behavior. It uses QLineEdit
, where you can enter a line, so that all files containing this line are highlighted in green.
import sys from PyQt4 import QtGui, QtCore class MyFileViewDelegate(QtGui.QStyledItemDelegate ): def __init__(self, parent=None, *args, **kwargs): QtGui.QItemDelegate.__init__(self, parent, *args) self.condition = None self.isMatch = False self.brush_active = QtGui.QBrush(QtGui.QColor("#79b9ed")) self.brush_active_matched = QtGui.QBrush(QtGui.QColor("#58cd1c")) self.pen = QtGui.QPen(QtGui.QColor("#414141") ) self.pen_matched = QtGui.QPen(QtGui.QColor("#39c819") ) self.pen_active = QtGui.QPen(QtGui.QColor("#eef2fd") ) self.pen_active_matched = QtGui.QPen(QtGui.QColor("#e7fade") ) def paint(self, painter, option, index): text = index.data(QtCore.Qt.DisplayRole) self.matchText(text) painter.save()
This is a comparison of how it looks with and without a subclass of QItemDelegate:
just to mention, another problem with this code is that after changing the condition, you need to move the mouse in QFileView to start the redraw. I wonder which slot I can use to connect to the LineEdit.textChange
signal to do this directly.