Maximum number of characters in width
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.)
Re: Maximum number of characters in width
See QFontMetrics::boundingRect() (the one with QRect or width & height parameters).
Re: Maximum number of characters in width
That's not what I want. The function I'd like to see would return an integer (number of characters), not a rectangle.
Re: Maximum number of characters in width
Quote:
Originally Posted by
ralphmerridew
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?