QFontMetrics::horizontalAdvance() returns inconsistent results

365 Views Asked by At

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?

0

There are 0 best solutions below