通过自定义delegate,实现根据鼠标状态对添加的自定义控件显示不同图标
先上效果图
首先需要重写 editorEvent 在其中判断鼠标状态 并将状态值存入 QModelIndex
bool editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index)
{
//button的rect
QRect rect = calculate_btn_rect(option.rect);
//按钮点击事件
QMouseEvent *mevent = static_cast<QMouseEvent*>(event);
if(rect.contains(mevent->pos())){
if(event->type() == QEvent::MouseButtonPress)
{
model->setData(index, event->type(), Qt::UserRole + 1);//将鼠标事件类型存入index
model->dataChanged(index, index);
}else if (event->type() == QEvent::MouseButtonRelease)
{
model->setData(index, event->type(), Qt::UserRole + 1);
model->dataChanged(index, index);
emit signal_delete_item_clicked(index);
}else
{
model->setData(index, event->type(), Qt::UserRole + 1);
model->dataChanged(index, index);
}
}
return QStyledItemDelegate::editorEvent(event, model, option, index);
}
再重写绘图事件 paint 根据 QModelIndex 中存放的鼠标状态来绘制图标
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
if (index.isValid()) {
//将事件传回父类以便其他内容继续绘制
QStyledItemDelegate::paint(painter, option, index);
painter->save();
//设置抗锯齿绘图
painter->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
QRectF rect = option.rect;
//计算按钮的区域
QRectF rf = QRectF(rect.left() + margin, rect.bottom() - focus_height - margin, rect.width() - margin*2, focus_height);
if (option.state.testFlag(QStyle::State_MouseOver)) {
QColor c = QColor(Qt::black);
c.setAlpha(50);
painter->setPen(c);
painter->setBrush(c);
//计算绘制区域
QRect btnRect = calculate_btn_rect(option.rect);
//取出鼠标状态
int mouseType = index.data(Qt::UserRole + 1).toInt();
//根据鼠标事件绘制不同图标
if(mouseType == QEvent::MouseButtonPress)
{
//pix_btn_press为按钮图标
QPixmap map = pix_btn_press.scaledToWidth(btnRect .width(), Qt::SmoothTransformation);
painter->drawPixmap(btnRect , map);
}else if (mouseType == QEvent::MouseButtonRelease)
{
QPixmap map = pix_btn.scaledToWidth(btnRect .width(), Qt::SmoothTransformation);
painter->drawPixmap(btnRect , map);
}else{
QPixmap map = pix_btn.scaledToWidth(btnRect .width(), Qt::SmoothTransformation);//, Qt::SmoothTransformation
painter->drawPixmap(btnRect , map);
}
}
painter->restore();
}
}