QGraphicsTextItem alignment char to top-left corner
-
Hello!
I want to draw character which is alignment to top-left corner of parent.QGraphicsTextItem * tItem = new QGraphicsTextItem(parent); tItem->setPlainText("a"); tItem->setPos(QPointF(0,0));
Picture below presents output of my code (grey rectangle is parent of QGraphicsTextItem)
I want to get result sth like this:
I try to use Qt::AlignLeft and Qt::AlignTop but without good result.
-
Consider that even if your TextItem is properly positioned on the top left, the font properties demand certain spacing from the edge. Look at e.g. https://en.wikipedia.org/wiki/Typeface#Font_metrics to find out more.
That means, if you want your character stuck to the edge like you show, you have to offset these font spacings by giving the item negative coordinates. How negative? That of course depends on the font you use.
Maybe QFontMetricsF::tightBoundingRect can give you the information you need to calculate the necessary offset. This is pretty complicated, because different characters use different amounts of space in different fonts. The "a" in your example doesn't use the upper part of the available space. Hopefully, if you let QFontMetricsF calculate a tightBoundingRect for the character you want to display, you get the right numbers. -
-
Thanks for replays but I think that it if not solution.
I try to use QFontMetricsF::tightBoundingRect.
Blue rect represent tightBoundingRect.
Red rect - QFontMetricsF::boundingRect
Yellow rect - QGraphicsTextItem::boundingRectSo size of yellow doesnt correspond to others. How to find position of 'a' in yellow rect?
-
@kjnm
The tightBoundingRect looks to have about the right size for the character without any extra space. That's a good start.
Unless you need any extra features of QGraphicsTextItem, I would recommend writing a little custom QGraphicsItem that displays the character directly in paint. You can use the tightBoundingRect to calculate the correct boundingRect for your item. Side benefit: QGraphicsTextItem is pretty heavyweight, due to it's ability to display formatted text.