Michael Hasselmann

Postings by Michael on January 24, 2011

QGraphicsItem: When you're doing it wrong

When you read through the Qt GraphicsView documentation, you might miss the detail that QGraphicsItem::pos() refers to the center of an item: "Their coordinates are usually centered around its center point (0, 0), [...] At item's position is the coordinate of the item's center point in its parent's coordinate system;".

Oh great, so the word "usually" indicates it is not enforced, and everyone can choose his own semantics when implementing QGraphicsItems ... which is precisely what I did, accidentally. My QGraphicsItems' pos() refers to their top left corner. One chooses the semantics when overriding boundingRect() (which apparently uses an item's postion to map the bounding rect into the parent's space). So let's check the boundingRect documentation, whether it contains this hint. Hm, no. But it contains an example:

QRectF CircleItem::boundingRect() const
    qreal penWidth = 1;
    return QRectF(-radius - penWidth / 2, -radius - penWidth / 2,
                   diameter + penWidth, diameter + penWidth);

Damn, so the bounding rect does not start at (0, 0), even though it's in item's coordinate space ... I ended up introducing a policy for differentiating between graphics items who do it right (by following the Qt conventions), and for those that I created, for whenever I have to deal with item positions. The other possibility - to fix every item to follow the Qt convention - would have been too much work, sadly.

I wish I had discovered this earlier. (Extra rant: That's why too much documentation that is more about story telling than about being to the point is just as wrong as no documention.)