Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mouse position in child QGraphicsScene

Tags:

qt

qt5

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?

like image 822
mimo Avatar asked Nov 03 '25 08:11

mimo


1 Answers

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();
like image 174
Tony O Avatar answered Nov 05 '25 16:11

Tony O



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!