在Qt drag和drop基础上,实现QGraphicsItem的鼠标拖动缩放,效果如下:
如图所示,整个item由两个QGraphicsItem组成,item1用来显示主图片,item2用来显示移动光标。
先来看item2的实现,它实现的功能有显示和消失(鼠标移动到item周围显示,其他地方消失)、颜色改变(使用鼠标缩放时改变颜色)。
void CornerGrabber
:
: paint ( QPainter
* painter ,
const QStyleOptionGraphicsItem * ,
QWidget * )
{
// fill the box with solid color, use sharp corners
_outterborderPen . setCapStyle ( Qt : : SquareCap );
_outterborderPen . setStyle ( Qt : : SolidLine );
painter - > setPen ( _outterborderPen );
QPointF topLeft ( 0 , 0 );
QPointF bottomRight ( _width , _height );
QRectF rect ( topLeft , bottomRight );
QBrush brush ( Qt : : SolidPattern );
brush . setColor ( _outterborderColor );
painter - > fillRect ( rect , brush );
}
const QStyleOptionGraphicsItem * ,
QWidget * )
{
// fill the box with solid color, use sharp corners
_outterborderPen . setCapStyle ( Qt : : SquareCap );
_outterborderPen . setStyle ( Qt : : SolidLine );
painter - > setPen ( _outterborderPen );
QPointF topLeft ( 0 , 0 );
QPointF bottomRight ( _width , _height );
QRectF rect ( topLeft , bottomRight );
QBrush brush ( Qt : : SolidPattern );
brush . setColor ( _outterborderColor );
painter - > fillRect ( rect , brush );
}
item2其实是一个巨型,宽和高由_width和_height确定,颜色由_outterborderColor确定,初始时黑色。
void CornerGrabber
:
:hoverLeaveEvent( QGraphicsSceneHoverEvent
* )
{
_outterborderColor = Qt : :black;
this - >update( 0, 0,_width,_height);
}
{
_outterborderColor = Qt : :black;
this - >update( 0, 0,_width,_height);
}