3
votes

I have a QGraphicsView contains a QGraphicsScene which loaded an image. What my app does is let user annotate this image so that I can get the coordinate information of the user's annotation area of this image. To be more comprehensible, I make this picture:

enter image description here

What I want is the exact coordinate information based on the image coordinate, because I add pixmap to the scene, I think the image and the scene have the same coordinate system. But, the QGraphicsView and the scene has the different coordinate, just like the picture shows, and they differ 5pix in width and 1pix in height in my computer(is it always this?).

I use mapToScene function, but I don not get the correct coordinate information.

I post some code here.

scene = new QGraphicsScene();
scene->addPixmap (pixmapItem);
ui->graphicsView->setScene (scene);


void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if ((event->button() == Qt::LeftButton)&& beginAnnotation) {
        .......   

        QPointF mousePoint = ui->graphicsView->mapToScene(event->pos());
        qDebug() << mousePoint;
    }
}

When I click the up-left corner of the image, I hope I can get (0,0), but I get (5,1) instead.

Please help me.

SOLUTION:

I think @effjae is right. My mainWindow capture the mousrPressEvent. And when I load an image into the Scene which contained by View, I use ui->graphicsView->adjustSize(); , So, I think View & Scene share the same coordinate system, am I right? For this reason, I update the picture to this:

enter image description here

Now, I take effjae's suggestion. I install an eventFilter on View, and now the mouseClick's coordinate is based on View & Scene. Thank you.

1

1 Answers

1
votes

I think the problem you're having here is that your mousePressEvent is coming from your main window, and not the actual QGraphicsView. The mousePressEvent is giving you coordinates for your window, this includes any borders or decorations.

To solve this you could subclass a QGraphicsView and handle the mousePressEvent in there, in exactly the same way as you have in your MainWindowClass.

A quick but perhaps less attractive solution would be to install an event filter on the QGraphicsView. Use the QObject's method installEventFilter to do this.