Time for action – Event handling in a custom item

Items, like widgets, can receive events in virtual functions. If you click on a scene (to be precise, you click on a view that propagates the event to the scene), the scene receives the mouse press event, and it then becomes the scene's responsibility to determine which item was meant by the click.

Let's override the SineItem::mousePressEvent function that is called when the user presses a mouse button inside the item:

void SineItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->button() & Qt::LeftButton) { float x = event->pos().x(); QPointF point(x, sin(x)); static const float r = 0.3; QGraphicsEllipseItem *ellipse = new QGraphicsEllipseItem(-r, -r, 2 * r, 2 * r, this); ellipse->setPen(Qt::NoPen); ...

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.