QGraphicsItem 鼠标点击事件编程方法

功能需求,在QGraphicsView中显示一张图像,如下图,鼠标点击图片时返回图片坐标系内的像素坐标,但是点击边上空白部分时不返回坐标。
这里写图片描述
实现思路是子类化QGraphicsView,QGraphicsScene, QGraphicsPixmapItem,并重写鼠标点击事件函数mousePressEvent(QGraphicsSceneMouseEvent* event)。光标默认的样式是手型样式以便拖拽图片。这里我更改了鼠标的样式,变为十字型,并且关闭了拖拽图片的功能。具体的实现方式见博文: QGraphicsView改变光标的样式

但是在重写鼠标点击事件函数时发现鼠标点击事件在子类化后的QGraphicsScene中被响应,但是子类化后的QGraphicsPixmapItem无法响应。QGraphicsView的事件传递机制的顺序是View->Scene->Item,也就是说事件被子类化的QGraphicsScene吞没了,没有传递到下一级的Item。
解决方案,在子类化的QGraphicsScene中重写mousePressEvent()方法内部一定要要记得调用:

QGraphicsScene::mousePressEvent(event);

注意,要想返回图像坐标系的位置,就需要在子类化的QGraphicsPixmapItem中调用scenePos()函数。即使放大图像,点击图像中相同位置也会返回相同坐标结果。

关键代码如下:
子类化QGraphicsScene

ImageScene::ImageScene(QObject* parent): QGraphicsScene(parent)
{
}

ImageScene::~ImageScene()
{
}

void ImageScene::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
    QGraphicsScene::mousePressEvent(event); // 将点击事件向下传递到item中
}

子类化QGraphicsPixmapItem

ImageItem::ImageItem(QGraphicsItem *parent): ImageItem(parent)
{
}

ImageItem::ImageItem(const QPixmap& pixmap, QGraphicsItem* parent) : QGraphicsPixmapItem(pixmap, parent)
{
}

ImageItem::~ImageItem()
{
}

void ImageItem::mousePressEvent(QGraphicsSceneMouseEvent* event)
{
    std::cout << "Item: (" << event->scenePos().x() << ", " << event->scenePos().y() << ')' << std::endl; 
}

使用方法

ImageView* view = new ImageView(); // 子类化的QGraphicsView
ImageScene* scene = new ImageScene();
ImageItem* imageItem = new ImageItem(QPixmap::fromImage(image));
scene->addItem(imageItem);
view->setScene(scene);

如果在ImageScene的点击事件中调用scenePos(), 同时点击周围白色边框将会返回坐标结果,此时坐标系原点为显示图像的左上角。换而言之,图像左侧空白区域内坐标的x均为负值,上方空白区域内坐标的y均为负值,右侧空白区域内坐标的x大于图像宽度,下方空白区域内坐标的y大于图像高度。

  • 8
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值