Qt 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

 1 ImageScene::ImageScene(QObject* parent): QGraphicsScene(parent)  2 {  3 }  4 
 5 ImageScene::~ImageScene()  6 {  7 }  8 
 9 void ImageScene::mousePressEvent(QGraphicsSceneMouseEvent* event) 10 { 11     QGraphicsScene::mousePressEvent(event); // 將點擊事件向下傳遞到item中
12 }

子類化QGraphicsPixmapItem

 1 ImageItem::ImageItem(QGraphicsItem *parent): ImageItem(parent)  2 {  3 }  4 
 5 ImageItem::ImageItem(const QPixmap& pixmap, QGraphicsItem* parent) : QGraphicsPixmapItem(pixmap, parent)  6 {  7 }  8 
 9 ImageItem::~ImageItem() 10 { 11 } 12 
13 void ImageItem::mousePressEvent(QGraphicsSceneMouseEvent* event) 14 { 15     std::cout << "Item: (" << event->scenePos().x() << ", " << event->scenePos().y() << ')' << std::endl; 16 }

使用方法

1 ImageView* view = new ImageView(); // 子類化的QGraphicsView
2 ImageScene* scene = new ImageScene(); 3 ImageItem* imageItem = new ImageItem(QPixmap::fromImage(image)); 4 scene->addItem(imageItem); 5 view->setScene(scene);

如果在ImageScene的點擊事件中調用scenePos(), 同時點擊周圍白色邊框將會返回坐標結果,此時坐標系原點為顯示圖像的左上角。換而言之,圖像左側空白區域內坐標的x均為負值,上方空白區域內坐標的y均為負值,右側空白區域內坐標的x大於圖像寬度,下方空白區域內坐標的y大於圖像高度。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM