qtqgraphicssceneqpixmapmousepress

How to get the exact location from a click on the qgraphicsscene in Qt


I am writing codes to load in image from a file and did some edits on this image(change some pixels' value), zoomed in or zoomed out and then save the image. Also, I want to know the location in the original image associated to a click on the qgraphicsscen. Up till now, I can not find any function useful.

My codes for loading image:

qgraphicsscene = myqgraphicsview->getScene();
qgraphicsscene->setSceneRect(image->rect());
myqgraphicsview->setScene(qgraphicsscene);
qgraphicsscene->addPixmap(QPixmap::fromImage(*image)); // this is the original image

My codes for editing:

mousePressEvent(QMouseEvent * e){
QPointF pt = mapToScene(e->pos());
scene->addEllipse(pt.x()-1, pt.y()-1, 2.0, 2.0,
QPen(), QBrush(Qt::SolidPattern));}

I want to know the relationship between e->pos() and the exact location in the original image.


Solution

  • Receiving a mousePressEvent in the GraphicsView means that calling pos() on the MouseEvent will return a point in the view's coordinate space.

    You can, at this point, convert the coordinate to scene space with the view's mapToScene function, then use the scene's itemAt function to find the item that was selected.

    With the returned item, the scene coordinate can then be mapped to the local coordinates of the item that was clicked on with the item's mapFromScene function.

    So, in the GraphicsView: -

    mousePressEvent(QMouseEvent * e)
    {
        // get scene coords from the view coord
        QPointF scenePt = mapToScene(e->pos());
    
        // get the item that was clicked on
        QGraphicsItem item* = qgraphicsscene->itemAt(pt, transform());
    
        // get the scene pos in the item's local coordinate space
        QPointF localPt = item->mapFromScene(scenePt);
    }
    

    With the position local to the item with the image, it's just a matter of mapping its scale to the original image.

    While you can do it this way, another option would be to inherit from the Qt class that stores the image and handle the mousePressEvent in there. This should provide you with the coordinate in the item's local space, without having to go through finding the item in the scene and converting the coordinates yourself.