QFontMetrics give wrong width

  • Qt5.9.2 msvc2017 and Qt5.6.3 msvc2015
    os : win10 64bits

        int const id = QFontDatabase::addApplicationFont(font_name);
        QString family = QFontDatabase::applicationFontFamilies(id).at(0);
        qDebug()<<"string family:"<<family;
        QFont monospace(family, 32, 10, false);
        QFontMetrics metrics(monospace);
        QImage img(metrics.width("0123456789"), metrics.height(), QImage::Format_ARGB32);
        QPainter p(&img);
        p.drawText(img.rect(), str);

    QFontMetrics always generate smaller width for a font of google fonts.As you can see, the 9 is always clipped.

    alt text

  • @tham
    Forgive me, you probably know a lot more about this than I do, but from http://doc.qt.io/qt-5/qfontmetrics.html#width:

    int QFontMetrics::width(const QString &text, int len = -1) const

    Note that this value is not equal to boundingRect().width(); boundingRect() returns a rectangle describing the pixels this string will cover whereas width() returns the distance to where the next string should be drawn.

    Should you not be using boundingRect().width() for what you seem to want for drawing the image (a bit more to the right), given the slope on the characters? Otherwise the pic looks correct as it is now.

  • @JNBarchan Thanks, you are right, this is my stupid mistake

  • @tham
    Pleasure. I don't think it was a "stupid mistake". Presumably for most fonts width() == boundingRect().width(), but this font is italicized/slanted hence they are different.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.