qt hoverMoveEvent鼠标响应事件

场景: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;
}

相关推荐

  1. qt hoverMoveEvent鼠标响应事件

    2024-01-13 06:36:02       61 阅读
  2. 十个鼠标事件

    2024-01-13 06:36:02       63 阅读
  3. python --监听鼠标事件

    2024-01-13 06:36:02       29 阅读
  4. 【React】React响应事件

    2024-01-13 06:36:02       43 阅读
  5. react之响应事件

    2024-01-13 06:36:02       28 阅读
  6. Qt 鼠标进入离开事件

    2024-01-13 06:36:02       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-13 06:36:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-13 06:36:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-13 06:36:02       82 阅读
  4. Python语言-面向对象

    2024-01-13 06:36:02       91 阅读

热门阅读

  1. IDC服务器算力如何计算?

    2024-01-13 06:36:02       55 阅读
  2. Android所有版本的存储权限适配

    2024-01-13 06:36:02       37 阅读
  3. Ubuntu上使用Snap安装Docker

    2024-01-13 06:36:02       65 阅读
  4. 系统语言德语时浮点数转化问题

    2024-01-13 06:36:02       57 阅读