场景:QWidget里面套了QGraphicsView,QGraphicsView当中设置了QGraphicsScene场景以及自定义的QGraphicsItem像元重绘图像。
本想要在QWidget当中,让鼠标移动到图像上时,得到指定坐标。而QMouseEvent事件需要点击了鼠标后才会响应。于是想着设置 SetMouseTracking(true); 但是没有效果。然后据说是需要在其继承的父窗口中都进行设置。不知道是因为嵌套太多层了,没设置对还是什么原因,依旧没有效果。
于是改变对策,选择到自定义的QGraphicsItem当中重写hoverMoveEvent事件,最终实现所需效果。 记得需要在构造函数当中设置 setAcceptHoverEvents(true);
class ImgShow : public QObject, public QGraphicsItem
{
Q_OBJECT
public:
ImgShow(QRectF rect);
~ImgShow() override;
protected:
virtual QRectF boundingRect() const override;
virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override;
void hoverMoveEvent(QGraphicsSceneHoverEvent* event);
private:
QRectF curRect;
QPixmap curPix;
QMutex mtx;
};
cpp
ImgShow::ImgShow(QRectF rect)
{
curRect = rect;
//使其在鼠标未点击也能响应悬停事件
setAcceptHoverEvents(true);
}
ImgShow::~ImgShow()
{
}
QRectF ImgShow::boundingRect() const
{
return curRect;
}
void ImgShow::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
mtx.lock();
// painter->drawPixmap(-static_cast<int>(curRect.width() / 2), -static_cast<int>(curRect.height() / 2), curPix);
//上面的drawPixmap起始位置不太一样
painter->drawPixmap(curRect.toRect(), curPix);
qDebug()<< curRect.width() << curRect.height();
mtx.unlock();
}
void ImgShow::hoverMoveEvent(QGraphicsSceneHoverEvent* event)
{
QPointF localPos = event->pos(); // 当前鼠标位置相对于图元坐标系的坐标
QRectF imageRect = mapRectToScene(boundingRect()); // 图像有效区域在场景中的位置
QPointF globalPos = scenePos() + localPos - imageRect.topLeft(); // 转换为图像有效区域的全局坐标
qDebug()<< globalPos;
}