mimo
mimo

Reputation: 2629

Get mouse position in child QGraphicsScene

In Qt5, I have a main window with a scene:

MyWindow::MyWindow(QWidget *parent) : QMainWindow(parent)
{
    view = new QGraphicsView();
    scene = new QGraphicsScene();
    scene->installEventFilter(this);
    view->setScene(scene);
    ...
    setCentralWidget(view);
}

view and scene are both private members of MyWindow. I want to know, in the MyWindow class, the mouse position when I click on the scene. That's why I use installEventFilter above. And I have tried to catch the event with this:

bool MyWindow::eventFilter(QObject *target, QEvent *event)
{
    if (target == scene)
    {
        if (event->type() == QEvent::GraphicsSceneMousePress)
        {
            const QGraphicsSceneMouseEvent* const me = static_cast<const QGraphicsSceneMouseEvent*>(event);
            const QPointF position = me->pos();
            cout << position.x() << "," << position.y() << endl;
        }
    }
    return QMainWindow::eventFilter(target, event);
}

This code does not work as expected: The position it prints when I click on the scene is always 0,0. Any clue about what is wrong?

Upvotes: 4

Views: 5813

Answers (1)

Tony O
Tony O

Reputation: 513

QGraphicsSceneMouseEvent.pos() returns position in coordinates of item on which you clicked. Your scene has no items so it returns (0,0). If you want to get position in scene coordinates use scenePos().

const QPointF position = me->scenePos();

Upvotes: 3

Related Questions