0

I'm working on a function that determines the maximum number of characters that can fit in a given width (in pixels) based on the widest character in the string and then chops the string accordingly. I'm using the horizontalAdvance method of QFontMetrics and I've been noticing some inconsistencies.

Take the following code for instance:

QFont        myFont("Times New Roman", 12);
QFontMetrics fm(myFont);
qDebug() << "Width of 'w': " << fm.horizontalAdvance('w');
qDebug() << "Width of 'wwww': " << fm.horizontalAdvance("wwww");

The output is

Width of 'w':  9
Width of 'wwww':  35

You would expect the width of the second one to be 36, right? Interestingly enough, adding one 'w' in the second string yields:

Width of 'w':  9
Width of 'wwwww':  43

Which should be 45. horizontalAdvance returns an int because it's measuring in pixels, but it almost looks like there's a decimal value being lost in the calculation somewhere.

Is this a bug or am I missing something?

Nihilish
  • 105
  • 1
  • 16
  • This is just a guess but the docs say the function returns an integer indicating the number of pixels. If the real width is a fractional value but it's just rounding to the nearest integer, then the calculation of the number of pixels could be different when stringing multiple characters together. – JarMan May 11 '22 at 16:02
  • @JarMan That's what I figured, but I guess if the width can have fractional values, it shouldn't return an int because there's a potential loss of precision. – Nihilish May 11 '22 at 16:23
  • 1
    Have you tried [`QFontMetricsF::horizontalAdvance`](https://doc.qt.io/qt-6/qfontmetricsf.html#horizontalAdvance)? It returns a `qreal`. – G.M. May 11 '22 at 19:38
  • @G.M. Thanks, I can't believe I missed that! – Nihilish May 11 '22 at 19:49

0 Answers0