新西兰注册公司做网站,做课件的软件下载带有蓝色的网站,工程建设交易信息网,宁波高端网站建设公司场景#xff1a;QWidget里面套了QGraphicsView#xff0c;QGraphicsView当中设置了QGraphicsScene场景以及自定义的QGraphicsItem像元重绘图像。 本想要在QWidget当中#xff0c;让鼠标移动到图像上时#xff0c;得到指定坐标。而QMouseEvent事件需要点击了鼠标后才会响应。…场景QWidget里面套了QGraphicsViewQGraphicsView当中设置了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_castint(curRect.width() / 2), -static_castint(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;
}