通过重载两个鼠标消息,判断坐标,然后处理。看起来可以。不知道这是不是实现的原理。代码如下:
#ifndef BMYGRAPHICSITEM_H
#define BMYGRAPHICSITEM_H
#include <QGraphicsItem>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
template <typename BaseItem>
class BMyGraphicsItem : public BaseItem
{
public:
BMyGraphicsItem(QGraphicsItem* p=0)
:BaseItem(p)
{
setAcceptHoverEvents(true); //必须有,否则无法接受mouseMove
setAcceptedMouseButtons(Qt::LeftButton);
setFlags( QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable );
}
void hoverMoveEvent ( QGraphicsSceneHoverEvent * event )
{
QPointF pos1 = event->pos();
QPointF pos = pos1;//this->mapFromScene(pos1);
QRectF rect = this->rect();
QRectF top=rect;
top.setTop( rect.top() - 2);
top.setBottom( rect.top() + 2);
QRectF bottom = rect;
bottom.setTop( rect.bottom() -2 );
bottom.setBottom(rect.bottom() +2 );
qDebug() << "\npos1" << pos1 << "\tpos after mapped"<< pos << "\trect"<<rect << "\ttop" << top << "\tbottom" << bottom;
QRectF left=rect;
left.setRight( rect.left() + 2);
QRectF right = rect;
right.setLeft( rect.right() - 2);
if( top.contains(pos) )
{
edge = 0;
cs = Qt::SizeVerCursor;
}
else if ( bottom.contains(pos) )
{
edge = 1;
cs = Qt::SizeVerCursor;
}
else if( left.contains( pos ) )
{
cs = Qt::SizeHorCursor;
edge = 2;
}
else if( right.contains( pos))
{
cs = Qt::SizeHorCursor;
edge = 3;
}
else
{
cs = Qt::ArrowCursor;
}
QCursor cur( cs );
this->setCursor(cur);
return BaseItem::hoverMoveEvent(event);
}
void mouseMoveEvent ( QGraphicsSceneMouseEvent * event )
{
if( this->cursor().shape() == Qt::SizeVerCursor )
{
QPointF pos2 = event->pos();
qDebug() << "\npos2=" << pos2;
QPointF pos1 = event->lastPos();
qDebug() << "\npos1=" << pos1;
float delta_y = pos2.y()-pos1.y();
qDebug() << "\ndelta_y" << delta_y;
QRectF rect = this->rect();
qDebug() << "\nrect=" << rect;
if( edge == 0 )
rect.setTop( rect.top() + delta_y );
else if( edge == 1)
rect.setBottom( rect.bottom() + delta_y );
qDebug() << "\nchanged rect=" << rect;
this->setRect(rect);
this->update();
}
else if(this->cursor().shape() == Qt::SizeHorCursor )
{
QPointF pos2 = event->pos();
qDebug() << "\npos2=" << pos2;
QPointF pos1 = event->lastPos();
qDebug() << "\npos1=" << pos1;
float delta_x = pos2.x()-pos1.x();
qDebug() << "\ndelta_x" << delta_x;
QRectF rect = this->rect();
qDebug() << "\nrect=" << rect;
if( edge == 2 )
rect.setLeft( rect.left() + delta_x );
else if( edge == 3)
rect.setRight(rect.right() + delta_x );
qDebug() << "\nchanged rect=" << rect;
this->setRect(rect);
this->update();
}
else
BaseItem::mouseMoveEvent(event);
}
private:
Qt::CursorShape cs;
int edge; //0 top,1 bottom,2,left,3,right
};
BMyGraphicsItem<QGraphicsRectItem> i;
#endif // BMYGRAPHICSITEM_H