Time for action – Changing the item's size

Our custom graphics item always displays the graph for x values between 0 and 50. It would be neat to make this a configurable setting. Declare a private float m_maxX field in the SineItem class, remove the MAX_X constant, and replace its uses with m_maxX in the rest of the code. As always, you must set the initial value of the field in the constructor, or bad things can happen. Finally, implement a getter and a setter for it, as shown:

float SineItem::maxX()
{
    return m_maxX;
}

void SineItem::setMaxX(float value)
{
    if (m_maxX == value) {
        return;
    }
    prepareGeometryChange();
    m_maxX = value;
}

The only non-trivial part here is the prepareGeometryChange() call. This method is inherited from QGraphicsItem and notifies the scene that our boundingRect() function will return a different value on the next update. The scene caches bounding rectangles of the items, so if you don't call prepareGeometryChange(), the change of the bounding rectangle may not take effect. This action also schedules an update for our item.

When the bounding rect does not change but the actual content of the item changes, you need to call update() on the item to notify the scene that it should repaint the item.