Render QTreeView background for selected cells

  • Hello, I am trying to center a checkbox and I have used the solution provided here:

    But is has an unpleasant side effect of not rendering the entire cell background when the row is selected.

    For Example: ! Rendering)!

    Here is my code:
    virtual void paint (QPainter* aPainter,
    const QStyleOptionViewItem& aOption,
    const QModelIndex& aIndex) const
    QStyleOptionViewItem viewItemOption(aOption);
    QRect newRect = QStyle::alignedRect(aOption.direction,
    QSize(aOption.decorationSize.width() + 5,
    viewItemOption.rect = newRect;
    QStyledItemDelegate::paint(aPainter, viewItemOption, aIndex);


    If I can draw the background for selected cells, I can perform a two step rendering to fill the entire cell. The first call would fill the background. Then I would go ahead and call paint to render the checkmark. Or if there is a better way, I'm open to other options.

    Any help or advice would be greatly appreciated. Thanks!

  • Found the solution to my problem. I thought I would share in case anyone else has the same problem.

    Between lines 6 & 7 (basically before you render the checkbox), insert the following two lines which will trigger the entire cell background to be rendered with nothing in it.

    QStyle *style = aOption.widget ? aOption.widget->style() : QApplication::style();
    style->drawControl(QStyle::CE_ItemViewItem, &aOption, aPainter, qobject_cast<QWidget *>(this->parent()));

    Then render the checkbox overtop of that and all should work.

  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Thanks for sharing the solution !

    IIRC you might simplify that and use the option's state to know whether the item is checked or not and paint the background accordingly.

    Something like:

    if (option.state & QStyle::State_Selected) {
    painter->fillRect(option.rect, option.palette.color(QPalette::Highlight));

    Hope it helps

Log in to reply