- Game Programming using Qt 5 Beginner's Guide
- Pavel Strakhov Witold Wysota Lorenz Haas
- 268字
- 2021-08-27 18:31:08
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.