QStyledItemDelegate 绘制事件在单元格(非行)上悬停



我有一个自定义的QStyledItemDelegate,它在特定列中绘制QPixmap。 当鼠标悬停在该单元格上时,我想以不同的方式绘制它。

下面是我的绘制事件,它在未State_MouseOver时会正确绘制单元格。 但是,当我将鼠标悬停在该行的任意位置时,它会更改颜色。 如何仅在鼠标悬停在包含像素图的单元格上时才更改它?

void myDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
Q_ASSERT(index.isValid());
switch(index.column()) {
case DAY_COLUMN:
{
QSize btnSize = QSize(option.rect.height() * .9, option.rect.height() * .9);
QRect r = option.rect;
int x = r.right() - btnSize.width() - 10;
int y = r.top();
QRect btnRect = QRect(x, y, btnSize.width(), btnSize.height());
QPixmap pixmap(":/icons/edit.png");
// If hovered over, change color.
if(option.state & QStyle::State_MouseOver) {
auto mask = pixmap.createMaskFromColor(QColor("Black"), Qt::MaskOutColor);
pixmap.fill(QColor("Red"));
pixmap.setMask(mask);
}
painter->drawPixmap(btnRect, pixmap, pixmap.rect());
return;
}
/*.... draw other column(s) as appropriate ...*/
}
}

我在 QTreeView 中的所有行上使用此委托。
Qt 5.12

可能是因为默认情况下QAbstractItemView::SelectRowsQTreeView 的选择行为。
您可以使用以下方法进行更改:

m_tree_view.setSelectionBehavior(QAbstractItemView::SelectItems);

查看更多:
QAbstractItemView::SelectionBehavior
QTreeView 源代码

最新更新