Search code examples
c++qtqgraphicsview

How to select a position and add an item in a QGraphicsView by mouse click?


I would like to select positions and items in a QGraphicsView by mouse click and add items to the connected view at this position/item. Do I need to implement my own subclass of QGraphicsView or is there a shorter solution, e.g. with signal/slot?


Solution

  • There are few ways to do it:

    • Reimplement mousePressEvent(QMouseEvent*) (so, you need to implement subclass of QGraphicsView),

    • Call installEventFilter(QObject *) for QGraphicsView and implement bool eventFilter(QObject *, QEvent *) to catch all events (and process only QEvent::MouseButtonPress inside this function). In this case you do not need to implement subclass of QGraphicsView.

    See also: Click event for QGraphicsView Qt and How to draw a point (on mouseclick) on a QGraphicsScene