Search code examples
qtqtstylesheetsqtguiqlistviewqicon

QListView highlight color not applied to item icon


I'm trying to get the hover highlight color I set on a QListView applied to the items' icons. Right now it only applies to the surroundings (the image has an alpha channel which is 0 where there is white background):

enter image description here

You can see clearly that the 3D model itself is not affected by the highlight color. When I select the item it the image gets the selection color:

enter image description here

And after being selected it is also affected by the highlight color (i.e. that's the result I want to produce by only hovering over the item):

enter image description here

The stylesheet I use is the following:

QListView::item {
    color: #000000;
    background-color:transparent;
}

QListView::item:hover:!pressed {
    padding: -1px;
    border: 1px solid #75c1ff;
    border-radius: 2px;
    background-color: #c6e5ff;
}

QListView::item:selected {
    padding: -1px;
    border: 1px solid #5eb6ff;
    border-radius: 2px;
    background-color: #9ed2ff;
}

This is how I'm returning the image in the data method of the item model of the list view:

return QIcon(QPixmap::fromImage(m_renderedObjectsModels.value(objectModel.path())));

I tried to add multiple QPixmaps there for the different states (like suggested here) but none are applied to only hovering (at least I didn't find a state that I could add a pixmap for that would make it work).


Solution

  • I'm not sure which Qt version you use so let's consider some of Qt5.15. As you use style sheets probably real drawing is happen in QCommonStyle::drawControl() with CE_ItemViewItem type. If it's the case then the thing is in drawing oreder:

    • background
    • check mark
    • icon
    • text
    • focus rect

    So I think that #2 and #3 images are drawn like that because of "focus rect" drawn after the icon. And that doesn't happen in #1 case when just background is drawn with icon over it but without "focus rect".

    To solve that you can try to reimplement style and drawing of items. Or more dirty way could be to set QStyle::State_HasFocus flag of opt parameter. Maybe you can do that somewhere in item's delegate.