Time for action – adding an item to a scene

Let's have a first try and add an item to the scene:

QGraphicsScene scene;
QGraphicsRectItem *rectItem = new QGraphicsRectItem(0,0,50,50);
scene.addItem(rectItem);

What just happened?

Nothing complicated here. You create a scene, create an item of type QGraphicsRectItem, define the geometry of the item's rectangle, and then set the item to the scene by calling addItem(). Pretty straightforward. But what you do not see here is what this implies for the scene. The scene is now responsible for the added item! First of all, the ownership of the item is transferred to the scene. For you, this means that you do not have to worry about freeing the item's memory because deleting the scene also deletes all items ...

Get Game Programming Using Qt 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.