I have a QListView containing QStandardItems . How to set stylesheet for a single item in the Qlistview based on the QModelIndex acquired?
-
You can only set stylesheet to a widget. Item is not a widget. Nevertheless, you can set a background color, for example. Or set a delegate. Or use `void QAbstractItemView::setIndexWidget ( const QModelIndex & index, QWidget * widget )` – Amartel Jun 07 '13 at 10:24
-
Is there a way of doing this in Qt 5.6 onwards? I was setting background color for individual QTreeView cells using Qt::BackgroundColorRole in the data() function of my subclassed QAbstractItemModel, however, I have had a datasheet enforced on my program, and now this does nothing. I have tried to find a way around for a while, and found lots of info about appending the stylesheet with specific widget objects, but as far as I can tell the cells of a View aren't a widget in their own right until they're an editor... so I don't think I can use my custom subclassed delegate either... thoughts? – Iron Attorney Aug 24 '17 at 09:11
2 Answers
If you use QListWidget instead of QListView, you can call QListWidget::setItemWidget() and you can customize how individual items look by applying a stylesheet to the items that you add. You need to make sure that your item widget class inherits from QWidget and you can apply styles to the widget using QSS like so in your constructor:
setStyleSheet("WidgetItem:pressed { background-color: #444444; }");
Here's a reference to QSS: http://qt-project.org/doc/qt-4.8/stylesheet-examples.html

- 9,634
- 10
- 46
- 85
-
-
Check the date before downvoting.... It's been 3 years since I made this answer. I can look at updating the answer, but I had honestly forgotten I answered this. The reference to Qt 4.8 should be a hint that this answer is old... – Cameron Tinker Jul 17 '16 at 07:52
-
The Widget-classes have been depricated since 4.0. They were kept from Qt3 in Qt4 only for old-style developers, who couldn't understand Model-Views. – Valentin H Jul 17 '16 at 09:51
There seems to be no way to set a stylesheet in the Model-View conecpt. But what exist is the FontRole. If you want to make an entry bold or italic or change the size then the FontRole can do that. If you want to change the color then you have to find some other solution.
Here is an example to make certain entries bold in python:
def data(self, index, role=QtCore.Qt.DisplayRole):
# use parent class to get unaltered result
res = super().data(index, role=role)
if role == QtCore.Qt.FontRole:
# modify FontRole
if index.row() = 3:
# row number 3 should be bold
if res is None:
# parent class didn't return a QFont so make one
res = QtGui.QFont()
# set bold attribute in font
res.setBold(True)
return res
The above data()
method sets the 4th row bold (rows are counted from 0). I leave translating to C++ to the reader.

- 11,875
- 2
- 24
- 42