最近接了个活儿,使用了QGraphicView、QGraphicScene、QGraphicItem实现图层显示图元操作。故做此记录,希望对有需要的朋友能提供一点微薄帮助。
提供有以下三种方实现式,给各位参考。
方法一
通过确定中心点坐标(centerPos)、鼠标按下时的坐标(pressPos)、鼠标移动后当前坐标(movePos),计算旋转后的角度,以实现中心旋转。
- 获取3个点
- 旋转中心坐标:
QPointF centerPos=item->boundingRect().center() - 鼠标按下时坐标:
重写鼠标按下事件函数,在mousePressEvent(QMouseEvent *event)中 event->pos() 获得按下时的坐标
QPointF pressPos = event->pos() - 鼠标移动后当前坐标:
重写鼠标按下事件函数,在mouseMoveEvent(QMouseEvent *event)中 event->pos() 获得移动后的坐标
QPointF movePos = event->pos()
- 旋转中心坐标:
- 3点计算角度
采用余弦定理进行角度计算
cosA = ( b^2 + c^2 - a^2 ) / 2bc
代码实例:
void CGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
if(m_eMouseHandle != Mouse_None) {
m_pressMouse = event->pos();
return;
}
}
return QGraphicsItem::mousePressEvent(event);
}
void CGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (event->buttons() == Qt::LeftButton) {
if (m_eMouseHandle == Mouse_LeftBottom) {
//鼠标在左下,处理鼠标旋转图元绘制
RotateRect(event->pos());
return;
}
}
return QGraphicsItem