Search code examples
c++qt5.6qfontmetrics

QFontMetrics boundingRect


I'm having problems with the QFontMetrics 'boundingRect' function, it doesn't return the correct results.

    mfntArial = QFont("Arial", 12, QFont::Bold);
    QFontMetrics objMetrics(mfntArial);
    QRect rctLine = objMetrics.boundingRect("LOS");

In the debugger, rctLine contains:

    x1 : 1
    x2 : 26
    y1 : -16
    y2 : 4

This is very confusing, I would expect x1 and y1 to both be 0 since there is no reference position passed and I would expect both x2 and y2 to be positive.

The rectangle returned is not correct and if I use it with drawText and alignment then part of the string is missing from the display.

I know there are other posts regarding how this function returns the wrong results and I've looked at these, they didn't help me.

I am using Qt5.6 on RedHat 7.2.

I've also tried:

    QRect rctParent = pobjParent->geometry();
    QRect rctLine = objMetrics.boundingRect(rctParent, intAlign, "LOS");

Where pobjParent is the parent widget and rctParent contains:

    x1 : 8
    x2 : 289
    y1 : 24
    y2 : 447

intAlign contains 33 (left, top)

In this case rctLine returns:

    x1 : 8
    x2 : 35
    y1 : 24
    y2 : 44

But the bounding rextangle is still to small and part of the 'S' is missing when rendered.

Official Qt documentation on QFontMetrics


Solution

  • I have fixed my problem by calculating the width of what I think is one of the widest characters, 'M'.

        QRect rctCapM = objMetrics.boundingRect(rctParent, intAlign, "M");
    

    I then use this as a typical and then calculate the required bounding rectangle for other strings:

        QRect rctBounds(0, 0, rctCapM.width() * strLine.length(), rctCapM.height());
    

    Where 'strLine' contains the string to display and calculate the bounds for, this works for me.