我有一个自定义的QStyledItemDelegate,它可以在某一列中绘制一个QPixmap。 当用鼠标悬停在该单元格上时,我想用不同的方式来绘制它。
下面是我的paint事件,当没有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
这可能是因为QTreeView的选择行为是 QAbstractItemView::SelectRows
默认情况下。您可以使用:
m_tree_view.setSelectionBehavior(QAbstractItemView::SelectItems);