场景图元缩放,鼠标点击图元边框进行拉伸操作:
(1)判断鼠标在图元位置并设置鼠标样式
8个方向【上,下,左,右,左上,左下,右上,右下】
void CustomGraphicsW::setFrameSectionCursor(const QPointF& currentPoint)
{
m_dir = windowFrameSectionAt(currentPoint);
switch (m_dir)
{
case Qt::NoSection:
setCursor(QCursor(Qt::ArrowCursor));
break;
case Qt::LeftSection:
setCursor(QCursor(Qt::SizeHorCursor));
break;
case Qt::TopLeftSection:
setCursor(QCursor(Qt::SizeFDiagCursor));
break;
case Qt::TopSection:
setCursor(QCursor(Qt::SizeVerCursor));
break;
case Qt::TopRightSection:
setCursor(QCursor(Qt::SizeBDiagCursor));
break;
case Qt::RightSection:
setCursor(QCursor(Qt::SizeHorCursor));
break;
case Qt::BottomRightSection:
setCursor(QCursor(Qt::SizeFDiagCursor));
break;
case Qt::BottomSection:
setCursor(QCursor(Qt::SizeVerCursor));
break;
case Qt::BottomLeftSection:
setCursor(QCursor(Qt::SizeBDiagCursor));
break;
case Qt::TitleBarArea:
break;
default:
break;
}
}
(2)鼠标移动事件 【主要进行缩放拉伸计算并重置图元大小】
void CustomGraphicsW::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
QPointF globalPoint = mapFromScene(event->scenePos());
QPointF offset = globalPoint - m_mousePressPos;
QRectF r = this->geometry();
if (m_isLeftBtnPressed && m_isResize)
{
if (m_dir != Qt::NoSection)
{
switch (m_dir)
{
case Qt::LeftSection:
r.setLeft(r.left() + offset.x());
break;
case Qt::RightSection:
r.setRight(r.right() + offset.x());
break;
case Qt::TopSection:
r.setTop(r.top() + offset.y());
break;
case Qt::BottomSection:
r.setBottom(r.bottom() + offset.y());
break;
case Qt::TopLeftSection:
r.setLeft(r.left() + offset.x());
r.setTop(r.top() + offset.y());
break;
case Qt::TopRightSection:
r.setRight(r.right() + offset.x());
r.setTop(r.top() + offset.y());
break;
case Qt::BottomLeftSection:
r.setLeft(r.left() + offset.x());
r.setBottom(r.bottom() + offset.y());
break;
case Qt::BottomRightSection:
r.setRight(r.right() + offset.x());
r.setBottom(r.bottom() + offset.y());
break;
default:
break;
}
this->setGeometry(r);
m_mousePressPos = mapFromScene(event->scenePos());
}
else
{
event->accept();
}
}
QGraphicsWidget::mouseMoveEvent(event);
}
(3)鼠标样式改变时机
void CustomGraphicsW::hoverMoveEvent(QGraphicsSceneHoverEvent *event)
{
setFrameSectionCursor(mapFromScene(event->scenePos()));
QGraphicsWidget::hoverMoveEvent(event);
}
以上 即缩放主要操作代码实现,这里给出场景中的图元缩放例子,其他无边框窗口缩放同理。