PDA

View Full Version : Maximum number of characters in width



ralphmerridew
25th May 2008, 23:17
For various reasons, I need to be able to do the following:
Given a String, a Font, and a width, what is the largest number of characters I can take from the front of the string that can be rendered within that width?

Inefficient implementation:
int i;
for (i = 1; i < str.length(); ++ i)
if (metric.width(str.left(i)) > max_width)
return i - 1;
return i;

This could be improved by using a binary chop based method, but that still would take log(n) tries.

Is there a method to get the answer with a single pass over the data?

(It would ultimately look like
rem_width -= char_width(str[0]);
for (i = 1; i < str.length() && rem_width >= 0; ++ i)
rem_width -= pair_width (str[i-1], str[i]);
Or call a function that ultimately did that.)

jacek
26th May 2008, 02:32
See QFontMetrics::boundingRect() (the one with QRect or width & height parameters).

ralphmerridew
27th May 2008, 01:38
That's not what I want. The function I'd like to see would return an integer (number of characters), not a rectangle.

jacek
27th May 2008, 01:55
That's not what I want. The function I'd like to see would return an integer (number of characters), not a rectangle.
Indeed, that's what happens when you answer questions at 3 A.M. ;)

Then maybe you will find something in QTextLayout?