我自定义了QGraphicsRectItem类,在场景里添加该多个对象,用鼠标选中其中一个后,为什么没有画出周围的虚线框(表示被选中)呢?boundingRect()虚函数被重写了啊?请知道的指点下,谢谢
CCustomRectItem::CCustomRectItem(ItemType Type, QMenu *pMenu,
QGraphicsItem *parent, QGraphicsScene *scene)
:QGraphicsRectItem(parent,scene)
{
itype = Type;
contextMenu = pMenu;
m_cursor = new QCursor;
switch (Type)
{
case Protection:
mRect = QRectF(-50,-70,100,140);
setRect(mRect);
itemColor = QColor(250,204,167);
break;
case SignalDevice:
mRect = QRectF(-40,-40,80,80);
setRect(mRect);
itemColor = QColor(152,208,222);
break;
default:
break;
}
setRect(mRect);
setZValue(0);
setAcceptDrops(true);
setFlag(QGraphicsItem::ItemIsMovable, true);
setFlag(QGraphicsItem::ItemIsSelectable, true);
setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
setFlag(QGraphicsItem::ItemIsFocusable,true);
setAcceptsHoverEvents(true);
cScale = false;
zoomFlag = false;
}
void CCustomRectItem::ResetRect(QRectF rect)
{
mRect = rect;
update(boundingRect());
}
QRectF CCustomRectItem::boundingRect()
{
return QRectF(mRect.x()-2,mRect.y()-2,mRect.width()+4,mRect.height()+4);
// return QRectF(mRect);
}void CCustomRectItem::paint(QPainter *painter, QStyleOptionGraphicsItem *option, QWidget *widget)
{
// Q_UNUSED(option);
// Q_UNUSED(widget);
painter->save();
painter->setBrush(QBrush(itemColor));
painter->drawRect(mRect);
painter->restore();
}
//实现该虚函数,该函数会被基类调用,用于设置Item的形状,以及其他碰撞检测等用途
QPainterPath CCustomRectItem::shape()
{
QPainterPath path;
path.addRect(mRect);
return path;
}
void CCustomRectItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
if(cScale)
{
start = event->scenePos();
zoomFlag = true;
update();
QGraphicsItem::mousePressEvent(event);
}
}
}
void CCustomRectItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(zoomFlag)
{
QPointF dis;
end = event->scenePos();
dis=end-start;
start=end;
QRectF tem;
prepareGeometryChange();
switch (direction)
{
case 1:
tem = QRectF(mRect.x()+dis.x()/2,mRect.y()+dis.y()/2,mRect.width()+dis.x(),mRect.height()+dis.y());
this->ResetRect(tem);
update(boundingRect());
this->moveBy(-dis.x()/2,-dis.y()/2);
break;
case 2:
tem = QRectF(mRect.x(),mRect.y()+dis.y()/2,mRect.width(),mRect.height()+dis.y());
this->ResetRect(tem);
update(boundingRect());
this->moveBy(0,-dis.y()/2);
break;
case 3:
tem = QRectF(mRect.x()+dis.x()/2,mRect.y(),mRect.width()+dis.x(),mRect.height());
this->ResetRect(tem);
update(boundingRect());
this->moveBy(-dis.x()/2,0);
break;
default:
break;
}
update();
}
else
{
QGraphicsItem::mouseMoveEvent(event);
}
}
void CCustomRectItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
cScale = false;
zoomFlag = false;
update();
QGraphicsItem::mouseReleaseEvent(event);
}