[Interest] [QGView] Center align text item that ignores inherited transformation

Ch'Gans chgans at gna.org
Wed Nov 23 01:45:26 CET 2016


Hi there,

I'm trying to add a QGraphicsSimpleTextItem as a child of another (shape) item.
I want the text to not follow scaling of the view (I use
QGraphicsItem::ItemIgnoreTransformations flag), *and* be always
centered on it's parent shape.
Ideally, i'm looking at a solution that doesn't require to create a
custom QGItem.

My problem is the centering of the text item itself, without
centering, here is what i do:
------------------------------------------------------------------------------------------
auto item = new ...
...
auto text = new QGraphicsSimpleTextItem(item);
text->setText(...);
text->setFlag(QGraphicsItem::ItemIgnoresTransformations);
auto itemCenter = QPointF(item->boundingRect().width()/2.0,
                                            item->boundingRect().height()/2.0);
text->setPos(itemCenter);
------------------------------------------------------------------------------------------

This work fine, but (as expected) the top-left of the text is
positioned on the center of the parent item.
To center-align, I tried:
-------------------------------------------------------------------------------------------
auto textCenter = QPointF(text->boundingRect().width()/2.0,
                                           text->boundingRect().height()/2.0);
text->setTransform(QTransform::fromTranslate(-textCenter.x, -textCenter));
-------------------------------------------------------------------------------------------

But this doesn't work because textCenter is an offset in a coordinate
system that doesn't follow view scaling... and the text transform
seems to be applied in the "scaled space".

Basically my problem is that it seems that I need a dynamic
positioning wrt the parent that depends on the view transform...

Does anyone know some tricks on how to achieve this?

Thanks,
Chris



More information about the Interest mailing list