Reputation: 39
I am using a QTableView and QSqlTableModel to show data from a sqlite DB. In the DB (and model) there is a column with fields that contain either paths ie: '/home/foo/bar.txt' or nothing. For this column in the view I would like to render one icon for items with a path, and a different icon for items with nothing (and not render the actual data/path in the view at all).
I think I need to set up a QStyledItemDelegate to render icons in place of the data, but the staritemdelelgate from the included examples highlights the editor function of the delegate (which I do not want) without shedding any light on how to render QIcons (or maybe I am just missing it). I have looked through the API, but I am unclear as to how to subclass a QStyledItemDelegate, or even if I need to for this use case.
Some guidance on whether this is a viable method, or an example of how to use a QStyledItemDelegate to render icons for a column (preferably in python) would be appreciated.
EDIT: Petr's post solved the issue. A full implementation of the situation I described, based on Petr's solution is:
def data(self, index, role=QtCore.Qt.DisplayRole):
if index.column() == 2:
if role == QtCore.Qt.DecorationRole:
filename = super(MovieModel, self).data(index, QtCore.Qt.DisplayRole)
if not filename == '':
return self.yes_icon
else:
return self.no_icon
elif role == QtCore.Qt.DisplayRole:
return ''
#Other columns/roles:
return super(MovieModel, self).data(index, role)
Hope it helps.
Upvotes: 1
Views: 937
Reputation: 66930
Instead of subclassing the delegate, you can subclass the model, and return the icon in the item's DecorationRole
.
Untested sketch of solution:
class IconModel(QSqlTableModel):
def data(self, index, role=Qt.DisplayRole):
if index.column() == FILENAME_COLUMN_INDEX:
if role == Qt.DecorationRole:
filename = super(IconModel, self).data(index, Qt.DisplayRole)
return icon_for_filename(filename)
elif role == Qt.DisplayRole:
return ''
# Other columns/roles:
return super(IconModel, self).data(index, role)
Subclassing delegates is much more of a pain.
Upvotes: 1