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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With