Search code examples
c++qtqpainter

How to get the sizes of the rendered text on a QPainter?


I draw in my Qt program on a QPainter the text and various elements round it. I need to get the sizes in pixels which will be occupied by this text.

Can I get somehow the sizes in pixels, knowing a text string and a font?

Thanks.


Solution

  • You can use QFontMetrics for the purpose. Following is sample from Qt Docs.

     QFont font("times", 24);
     QFontMetrics fm(font);
     int pixelsWide = fm.width("What's the width of this text?");
     int pixelsHigh = fm.height();