O'Reilly logo

Game Programming using Qt 5 Beginner's Guide - Second Edition by Lorenz Haas, Witold Wysota, Pavel Strakhov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required