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: ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.