Important: Please read the Qt Code of Conduct -

Artificial MouseEvent and natural MouseEvent on QGraphicsView return different positions

  • Dear All,

    Since I am kind of a Qt-novice I apologize if this has been asked/cleared before but my forum search didn't yield any results that could solve my problem.

    I am trying to create a drawing app where the user can enter basic shapes like points and polygons. The app contains a menubar on the left which is a QWidget with some nested layout. On the right I created a QWidget which contains a subclassed QGraphicsView called inputViewer and some labels below, arranged in a layout aswell. The scenes that are displayed in the inputViewer are subclasses of QGraphicsScene called inputModel.

    To handle the drawing, I overwrote the mousePressEvent-functions on both, the QGraphicsView and the QGraphicsScene. The actual drawing by mouse where only the mousePressEvent-functions get called work as I would expect it and therefore I assume these are correct.

    I want the user to be able to also draw a point at the cursor-position when the Qt::Key_Return is pressed. For that I overwrote the inputViewer::keyPressEvent() and artificially triggered a QMousePressEvent. For the position of the QMousePressEvent I created a QCursor object in the inputViewer and get the position by calling cursor->pos() (returns global coordinates afaik) and map them to the inputViewer with mapFromGlobal(). The inputViewer::mousePressEvent() is not overwritten and therefore should propagate the event right down to the scene if I am not mistaken.

    The problem is that if I let the program output the coordinates that I get from points being drawn by mouse and points being drawn by keyboard, there is a little offset. For example if I click on my canvas, don't move the mouse and press Return the output of the program is not the same.

    I hope the example is sufficient and thank all of you for your help and patience in advance.



    The program:

    void inputViewer::keyPressEvent(QKeyEvent *event)
    ... some other if and elses to handle different keys ...
    else if(event->key() == Qt::Key_Return)
    QMouseEvent event =QMouseEvent(QEvent::MouseButtonPress,this->mapFromGlobal(cursor->pos()),Qt::LeftButton,Qt::LeftButton,Qt::NoModifier);

    void inputModel::mousePressEvent(QGraphicsSceneMouseEvent *event)
    std::cout << " Scene-coordinates are: " << event->scenePos().x() << " " << event->scenePos().y() << std::endl;
    ... some drawing functions like adding an ellipse ...

  • Lifetime Qt Champion

    Hi I dont know about mouse coors
    but Just wanted to make sure you saw
    Diagram Scene Example
    in case you could borrow stuff from that.