I also added a little border to not have the text touching the rectangle:
Qt Code:
  1. {
  2. // [...]
  3.  
  4. // Leave a 1 pixel wide border around the text
  5. const qreal borderSize = 1;
  6. const qreal doubleBorder = borderSize * 2;
  7. // Calculate how much to scale the text to fit the rectangle
  8. qreal scaleX = textRectangle.width() / (textSize.width() + doubleBorder);
  9. qreal scaleY = textRectangle.height() / (textSize.height() + doubleBorder);
  10. // Apply the scale factors
  11. rotationMatrix.scale(scaleX, -scaleY);
  12. // Center the text (because of the border)
  13. qreal offsetX = borderSize;
  14. qreal offsetY = borderSize;
  15. // Draw the text
  16. QPainterPath textPath;
  17. textPath.addText(QPointF(offsetX, -(offsetY + fm.descent())), font, text);
  18.  
  19. // [...]
  20. }
To copy to clipboard, switch view to plain text mode 

Now I have troubles in getting exact font size because QFontMetricsF seems to be very inaccurate and often the text goes outside the rectangle because it is bigger than what is reported.
Probably I'll make another post for this problem , anyway I think it is not easily solvable (Qt or X11 or KDE Bug?).