Solved QFontMetrics give wrong width
-
Qt5.9.2 msvc2017 and Qt5.6.3 msvc2015
os : win10 64bitsint 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); img.fill(QColor(0,0,0)); qDebug()<<img.size(); QPainter p(&img); p.setPen(QPen(Qt::green)); p.setFont(monospace); p.drawText(img.rect(), str); ui->labelImg->setPixmap(QPixmap::fromImage(img));
QFontMetrics always generate smaller width for a font of google fonts.As you can see, the 9 is always clipped.
-
@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 fontswidth() == boundingRect().width()
, but this font is italicized/slanted hence they are different.