I am trying to understand the differences between

fontmetrics.horizontalAdvance(str) and fontmetrics.boundingRect(str).width().

I understand it's related to kerning, but with my experiments, the bounding rect just doesnt "bound" the string.
Also, with monospaced fonts kerning should not be a concern, right?

Consider this code:

Qt Code:
  1. {
  2. QFont fixedfont = QFontDatabase::systemFont(QFontDatabase::FixedFont);
  3. fixedfont.setPointSize(9);
  4. QFontMetrics fontmetrics = QFontMetrics(fixedfont);
  5. QString str = "abcdefghijk 0123456789";
  7. int a = fontmetrics.horizontalAdvance(str);
  8. int b = fontmetrics.boundingRect(str).width();
  9. int c = fontmetrics.averageCharWidth() * str.length();
  10. assert(b == c);
  12. QPixmap pixmap(QSize(b, fontmetrics.height()));
  13. pixmap.fill(Qt::white);
  14. QPainter painter(&pixmap);
  15. painter.setFont(fixedfont);
  16. painter.drawText(QPoint(0,fontmetrics.height()), str);
  17. pixmap.save("fontm.bmp", "bmp");
  19. }
To copy to clipboard, switch view to plain text mode 

Whereas horizontalAdvance gives the correct result:


boundingRect.width() truncates the text:


I would understand if HA had some extra space at the end. But as is, BR just doesnt bound the text. Why not?

In other words, I dont understand why with a fixed-width font, averageCharWidth * str.length() doesnt equal the pixels the string occupies when drawn at (0,0).