Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width
Here is my code the fit (in heigth) a text, works quite well (error < 2% I guess)
void scalePainterFontSizeToFit(QPainter &painter, QFont &r_font, float _heightToFitIn)
{
float oldFontSize, newFontSize, oldHeight;
// Init
oldFontSize=r_font.pointSizeF();
// Loop
for (int i=0 ; i<3 ; i++)
{
oldHeight = painter.fontMetrics().boundingRect('D').height();
newFontSize = (_heightToFitIn / oldHeight) * oldFontSize;
r_font.setPointSizeF(newFontSize);
painter.setFont(r_font);
oldFontSize = newFontSize;
//qDebug() << "OldFontSize=" << oldFontSize << "HtoFitIn=" << _heightToFitIn << " fontHeight=" << oldHeight << " newFontSize=" << newFontSize;
}
// End
r_font.setPointSizeF(newFontSize);
painter.setFont(r_font);
}