Search code examples
c++qtqfontmetrics

How to get the height from the top of character to its base line (i.e, its actual ascent) in QWidget?


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

How do I solve this problem?


Solution

  • 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()