Time for action – Adding text to a custom rectangle

Let's add a number to each of the corner circles:

child->setPos(pos);
QGraphicsSimpleTextItem *text =
    new QGraphicsSimpleTextItem(QString::number(i), child);
text->setBrush(Qt::green);
text->setPos(-text->boundingRect().width() / 2,
             -text->boundingRect().height() / 2);

The QString::number(i) function returns the string representation of number i. The text item is a child of the circle item, so its position is relative to the circle's origin point (in our case, its center). As we saw earlier, the text is displayed to the top-left of the item's origin, so if we want to center the text within the circle, we need to shift it up and right by half of the item's size. Now the text is positioned ...

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.