2

I am experimenting to build a tool that can display modified text (i.e, with some additional stroke) on screen using QWidget. So, to put the stroke in its correct position, I need to know the ascent height of the character the stroke is being put on.

And I'm a tad stuck on retrieving the actual ascent of a character. I have tried some of the following things:

  • The method QFontMetrics::ascent() will give me the ascent of the whole font; so this is not what I need.
  • The method QFontMetrics::boundingRect(&char).height() will give me what I want as long as the character does not use any of its descent part. If the character, however, does use some of the descent, then the method will return me the actual height of the character. If the character does use all its descent (i.e, the font descent); then I can minus that out to get the actual ascent. But I just don't know how to settle the case, where the character just use a tad of it's descent.

Is there any method, or any way I can go about solving this problem? Can anyone please give me a push on this problem?

Thank you so much in advance,

user49685
  • 151
  • 1
  • 7
  • 1
    If you have that specific requirements, a last resort could be to write the text (or character) into a `QPixmap` and looking for non-white / non-transparent pixels in scan lines beginning from the top... (I wouldn't have considered such an idea until I saw your [tag:calligraphy] tag.) ;-) – Scheff's Cat Jul 31 '21 at 09:02
  • @Scheff'sCat Thank you very much for your advice. I think this is manageable, and it won't take much time for the CPU to handle a small string of text. But it's not very scalable, when you have a bunch of texts. But still, in my case, I think scanning the character should be fine. I just thought that all the information is stored somewhere in the font file, and we just need the right way to extract the info? : – user49685 Jul 31 '21 at 09:14
  • 1
    I don't understand why `QFontMetrics::boundingRect` can't provide the info you require. Instead of of using `QFontMetrics::boundingRect(&char).height()` try using `-QFontMetrics::boundingRect(c).top()` (note the unary `-`). – G.M. Jul 31 '21 at 09:28
  • @G.M. I'm feeling so dumb now. =((((( Can you just give a brief answer below, so that I can mark it as accepted? It may help someone in the future, who may just happen to need it. Thank you so much, :* – user49685 Jul 31 '21 at 09:39
  • 1
    It's always simple if you know the trick... ;-) – Scheff's Cat Jul 31 '21 at 10:20

1 Answers1

3

You can use QFontMetrics::boundingRect. The QRect returned will have its origin at (0, 0) with the ascent for character c represented by...

-QFontMetrics::boundingRect(c).top()

and, similarly, the descent by...

QFontMetrics::boundingRect(c).bottom()
G.M.
  • 12,232
  • 2
  • 15
  • 18