[英]How to rotate a QGraphicsPixmap around a point according to mouseMoveEvent?
I want rotate a QGraphicsPixmapItem around a point according to mouse position.我想根据鼠标 position 围绕一个点旋转 QGraphicsPixmapItem。
So i tried this:所以我尝试了这个:
void Game::mouseMoveEvent(QMouseEvent* e){
setMouseTracking(true);
QPoint midPos((sceneRect().width() / 2), 0), currPos;
currPos = QPoint(mapToScene(e->pos()).x(), mapToScene(e->pos()).y());
QPoint itemPos((midPos.x() - cannon->scenePos().x()), (midPos.y() - cannon->scenePos().y()));
double angle = atan2(currPos.y(), midPos.x()) - atan2(midPos.y(), currPos.x());
cannon->setTransformOriginPoint(itemPos);
cannon->setRotation(angle); }
But the pixmap moves a few of pixels.但是像素图移动了几个像素。
Besides the mixup of degrees and radians that @rafix07 pointed out there is a bug in the angle calculation.除了@rafix07 指出的角度和弧度的混合之外,角度计算中还有一个错误。 You basically need the angle of the line from
midPos
to currPos
which you calculate by你基本上需要从
midPos
到你计算的currPos
的线的角度
double angle = atan2(currPos.y() - midPos.y(), currPos.x() - midPos.x());
Additionally the calculation of the transformation origin assumes the wrong coordinate system.此外,变换原点的计算假定了错误的坐标系。 The origin must be given in the coordinate system of the item in question (see QGraphicsItem::setTransformOriginPoint ), not in scene coordinates.
原点必须在相关项目的坐标系中给出(参见QGraphicsItem::setTransformOriginPoint ),而不是在场景坐标中。 Since you want to rotate around the center of that item it would just be:
由于您想围绕该项目的中心旋转它只是:
QPointF itemPos(cannon->boundingRect().center());
Then there is the question whether midPos
is actually the point highlighted in your image in the middle of the canon.然后还有一个问题,
midPos
是否真的是您图像中在佳能中间突出显示的点。 The y-coordinate is set to 0 which would normally be the edge of the screen, but your coordinate system may be different. y 坐标设置为 0,通常是屏幕的边缘,但您的坐标系可能不同。 I would assume the
itemPos
calculated above is just the right point, you only need to map it to scene coordinates ( cannon->mapToScene(itemPos)
).我会假设上面计算的
itemPos
是正确的点,您只需要将 map 到场景坐标( cannon->mapToScene(itemPos)
)。
Lastly I would strongly advise against rounding scene coordinates (which are double
s) to int
s as it is done in the code by forcing it to QPoint
s instead of QPointF
s.最后,我强烈建议不要将场景坐标(是
double
s)舍入到int
s,因为它是在代码中通过将其强制为QPoint
s 而不是QPointF
s 来完成的。 Just use QPointF
whenever you are dealing with scene coordinates.每当您处理场景坐标时,只需使用
QPointF
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.