Render QTreeView background for selected cells
-
Hello, I am trying to center a checkbox and I have used the solution provided here:
http://qt-project.org/faq/answer/how_can_i_align_the_checkboxes_in_a_view
But is has an unpleasant side effect of not rendering the entire cell background when the row is selected.
For Example: !https://imagizer.imageshack.us/v2/536x269q90/833/mvr2.png(Problem 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,
Qt::AlignCenter,
QSize(aOption.decorationSize.width() + 5,
aOption.decorationSize.height()),
QRect(aOption.rect.x(),
aOption.rect.y(),
aOption.rect.width(),
aOption.rect.height()));
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!
Joel -
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.
-
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