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 – 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); ...

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