⚠️ Forum Maintenance: Feb 6th, 8am - 14pm (UTC+2)

Get mouse coordinates relative to QGraphicsScene

  • I am attempting to detect if the user clicks on an object that is within the QGraphicsScene by using the following code:
    QPointF origin = ui->graphicsView->mapFromGlobal(QCursor::pos());
    qDebug() << scene->itemAt(origin, QTransform());@

    However, the problem is, itemAt() uses coordinates that are relative to the scene which considers (0,0) to be in the middle while mapFromGlobal() considers (0,0) to be at the top left of the scene. I attempted to use an int that was the width of the graphicsView/2 - the width of the object. I did the same for the height and this works until the user moves the object, at which point the trick no longer works. So I need some advice on how to translate the mouse coordinates to either be relative to Global or the QGraphicsScene.

  • Alright I think I have fixed this, with some help on IRC and documentation.

    QPoint origin = ui->graphicsView->mapFromGlobal(QCursor::pos());
    QPointF relativeOrigin = ui->graphicsView->mapToScene(origin);
    scene->removeItem(scene->itemAt(relativeOrigin, QTransform()));

Log in to reply