Search code examples
qttextword-wrap

Qt get substring of a large QString that fits inside fixed QRect


I have a large string, a fixed font and a fixed rectangle to draw that string into.

  • If the string doesn't fit, I would like to know the length of substring that does fit into that rectangle
  • if the string does fit, then I would like to know bounding rectangle height

I searched the web all day and found nothing.


Solution

  • Using the QFontMetrics class and its boundingRect class, get the rect used by the string provided

    // assumes myFont has been instantiated
    QFontMetrics fm(myFont);
    QRect bounds = fm.boundingRect("Some text here");
    

    Compare the size of bounds with the area with which to test if the string will fit.

    If the string doesn't fit, I would like to know the length of substring that does fit into that rectangle

    If the bounds of the returned rect from boundingRect is too large, recursively remove characters until the width fits into your target rect.

    bool bFits = false;
    QString str = "String to test boundary";
    QFontMetrics fm(myFont);
    QRect bounds;
    do
    {    
        bounds = fm.boundingRect(str);
        // Assume testBoundary is the defined QRect of the area to hold the text
        if(!testBoundary.contains(bounds) && (!str.isEmpty()) )
             str.chop(1);
        else
            bFits = true;
    }while(!bFits);
    

    if the string does fit, then I would like to know bounding rectangle height

    This is simply the height of the returned rect from the call to boundingRect.

    int height = bounds.height();