Time for action – Implementing the ability to create and delete elements with mouse

Let's allow the users to create new instances of our sine item when they click on the view with the left mouse button and delete the items if they use the right mouse button. Reimplement the View::mousePressEvent virtual function, as follows:

void View::mousePressEvent(QMouseEvent *event)
{
    QGraphicsView::mousePressEvent(event);
    if (event->isAccepted()) {
        return;
    }
    switch (event->button()) {
        case Qt::LeftButton: {
            SineItem *item = new SineItem();
            item->setPos(mapToScene(event->pos()));
            scene()->addItem(item);
            event->accept();
            break;
        }
        case Qt::RightButton: {
            QGraphicsItem *item = itemAt(event->pos());
            if (item) {
                delete item;
            }
            event->accept();
            break;
        }
        default:
            break;
    }
}

Here, we first check whether the event was accepted by the scene or any of its items. If not, we determine which button was pressed. For the left button, we create a new item and place it in the corresponding point of the scene. For the right button, we search for an item at that position and delete it. In both cases, we accept the event. When you run the application, you will note that if the user clicks on an existing item, a new circle will be added, and if the user clicks outside of any items, a new sine item will be added. That's because we properly set and read the accepted property of the event.

You may note that the scene jumps within the view when we add a new item. This is caused by changes of the scene rect. To prevent this, you can set a constant rect using setSceneRect() or change the alignment using setAlignment(Qt::AlignTop | Qt::AlignLeft) in the view's constructor.