Please nominate your Qt Champions for 2021!

Change QAbstractItemView cell's decoration upon hover

  • Hello, all.

    Currently, it is possible to change any visual aspects of a QAbstractItemView's cell using QSS, that is, modify the style of the QAbstractItemView::item subcontrol. I've found no way to customize the decoration of the latter, but only its text color, background, border, etc. The requirement is to change the icon / decoration upon hover. Tried using QIcon's QIcon::Normal and QIcon::Active modes but it didn't work. The brute force approach to hook to the view's notifications where the user is hovering and to provide this information to the model is known but not preferred. If you know about any integrated or better approach, please share it.

  • Moderators

    the cleanest solution IMO is (subclassing QStyledItemDelegate and reimplement the paint method):

    void MyStyledItemDelegate::paint(QPainter *painter,  const QStyleOptionViewItem &option, const QModelIndex &index) const
        QStyleOptionViewItem opt = option;
        initStyleOption(&opt, index);
        if( opt.state & QStyle::State_MouseOver ) // additional checks here?
             opt.icon = QIcon(...);
        const QWidget* widget = opt.widget;
        QStyle *style = widget ? widget->style() : QApplication::style();
        style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);

    alternatively (if you dont want to change the paint() method) only override initStyleOption():

    void MyStyledItemDelegate::initStyleOption(QStyleOptionViewItem* option, const QModelIndex & index) const
         QStyledItemDelegate::initStyleOption(option, index);
         if( option->state & QStyle::State_MouseOver ) // additional checks here?
             option->icon = QIcon(...); //e.g.<QIcon>();

  • Jus a small note, option->icon might not be enough if the icons are of different sizes or you have no icon at all when not hovering. You probably also need decorationPosition

  • @raven-worx, @VRonin , thank you. Now, I have an issue drawing the icon for the focused state. Now, the latter is the one being stylized instead of the mouse hover one. The problem is that the icon/decoration of the focused item is drawn using some color overlay. In my case it is a dark cyan color overlay:
    See the icon displayed on the left of the "High" list item which is the actual decoration that is affected by some mysterious color overlay and compare it to what it should actually look like on the right side of "High". This problem is reproducible only for the item is focused. Could any QSS affect the icon as well e.g. interpret another style preferences of the focused state of the cell as a tint for its decoration?

Log in to reply