Mouse Events on QGraphicsview and Object Movement

  • I implemented a Graphicsview in which I load an Image and the user can add different Item such as rectangle or line. The user has also the possibility to move these objects in the scene. Up to here everything is ok.

    Now I tried to implement some mouse events in this way:

    bool MainWindow::eventFilter(QObject *obj, QEvent *event)
        if (obj == ui->graphicsView && enable_mouse_event==true)
          if (event->type() == QEvent::MouseButtonPress)
              QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
              point_mouse = ui->graphicsView->mapFrom(ui->graphicsView, mouseEvent->pos());
              return true;
          if (event->type() ==  QEvent::MouseMove)
                  int scroll_x, scroll_y;
                  scroll_x = ui->graphicsView->horizontalScrollBar()->value();
                  scroll_y = ui->graphicsView->verticalScrollBar()->value();
                  QMouseEvent  *mouseEvent = static_cast<QMouseEvent*>(event);
                  point_mouse_move = ui->graphicsView->mapFrom(ui->graphicsView, mouseEvent->pos());
                  QRect rect(point_mouse_move.x()+scroll_x-50, point_mouse_move.y()+scroll_y-50, 100, 100);
                  zoom_image = image_clone.copy(rect);
                  return true;
        return false

    with in MainWindow.cpp


    In this way the press event is recognized while the move event is recognized only on the border of the Qgraphicview object (the property mouseTracking is set to true) and I'm still able to move the other object.

    To solve the problem of the move event I tried to modify the code by adding:


    to the graphicview object.

    In this way both the mouse events (press and move) work correctly but I'm no longer able to move the other objects (rect and line)

    Any Idea how can I recognize all the mouse events and at the same time move the other objects??


  • From the docs on installEventFilter:
    "In your reimplementation of this function, if you want to filter the event out, i.e. stop it being handled further, return true; otherwise return false."

    You return true on the MouseButtonPress. The GraphicsItems will no longer see these events, therefore many things won't work anymore.

  • @Asperamanca

    Oh yes! you're right! very stupid error! thanks!