I needed this functionality myself - here is what I came up with:
qreal lod = option->levelOfDetailFromTransform(painter->worldTransform());
QFont f
= painter
->font
();
qreal aspectRatio = painter->fontMetrics().lineSpacing() / painter->fontMetrics().averageCharWidth();
int pixelsize = sqrt(r.width()*r.height()/aspectRatio/(stitle.length()*3))*aspectRatio;
f.setPixelSize(pixelsize);
int flags = Qt::AlignCenter|Qt::TextDontClip|Qt::TextWordWrap;
if ((pixelsize * lod) < 13)
flags |= Qt::TextWrapAnywhere;
QRectF tbr
= fm.
boundingRect(r,flags,stitle
);
pixelsize = f.pixelSize()*qMin(r.width()*0.95/tbr.width(),r.height()*0.95/tbr.height());
f.setPixelSize(pixelsize);
painter->setFont(f);
painter->drawText(r,flags,stitle);
qreal lod = option->levelOfDetailFromTransform(painter->worldTransform());
QRectF r = boundingRect();
QFont f = painter->font();
qreal aspectRatio = painter->fontMetrics().lineSpacing() / painter->fontMetrics().averageCharWidth();
int pixelsize = sqrt(r.width()*r.height()/aspectRatio/(stitle.length()*3))*aspectRatio;
f.setPixelSize(pixelsize);
int flags = Qt::AlignCenter|Qt::TextDontClip|Qt::TextWordWrap;
if ((pixelsize * lod) < 13)
flags |= Qt::TextWrapAnywhere;
QFontMetricsF fm(f);
QRectF tbr = fm.boundingRect(r,flags,stitle);
pixelsize = f.pixelSize()*qMin(r.width()*0.95/tbr.width(),r.height()*0.95/tbr.height());
f.setPixelSize(pixelsize);
painter->setFont(f);
painter->drawText(r,flags,stitle);
To copy to clipboard, switch view to plain text mode
The idea of the first attempt to calculate a pixelsize is to calculate how big a letter can be if you want to distribute a certain amount of letters on the available space.
numberOfLetters = width / charWidth * height / (charWidth*aspectRatio)
=> pixelSize = charWidth * aspectRatio = sqrt ( width * height / numberOfLetters / aspectRatio) * aspectRatio;
For my scenario numberOfLetters is 3 times the amount of text I want to display, because I don't want to cover the whole item with text.
With this guess I call QFontMetricF::boundingRect and fine tune the result accordingly.
This works fine for my purpose.
HIH
Johannes
Bookmarks