Important: Please read the Qt Code of Conduct -

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);

    Picture below presents output of my code (grey rectangle is parent of QGraphicsTextItem)
    0_1534258299501_Screen Shot 2018-08-14 at 16.48.27.png

    I want to get result sth like this:
    0_1534258849260_Screen Shot 2018-08-14 at 17.00.16.png

    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. 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.

  • @kjnm
    You can get the information you need to move the text from the QFontMetrics class.
    You should look at the values such as height, ascent, decent, leading, bearing etc.
    The bounding rectangle can give you the overall size to work with.

  • 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::boundingRect

    So size of yellow doesnt correspond to others. How to find position of 'a' in yellow rect?

    0_1534405163696_Screen Shot 2018-08-16 at 09.39.12.png

  • @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.

  • This post is deleted!

  • Thanks everyone for help.
    For me solution is using QGraphicsSimpleTextItem and translate by value calculate by QFontMetricsF::tightBoundingRect / QFontMetricsF::boundingRect.
    0_1534407229176_Screen Shot 2018-08-16 at 10.13.05.png
    Now yellow is QGraphicsSimpleTextItem::boundingRect.