title: Qt C++ How to Scale Text to Width w/QPainter
body: <p>I am looking for an effective way to use the <code>drawText</code> method of QPainter according to a QRect. For example if I were to have a QRect as the origin with a size of 50x50: <code>QRect(0, 0, 50, 50);</code> and wanted to fit text so it fits from left to right. Here are a few of the examples that I currently have, but to no extent can I get them to move fluently.</p>
  
  <p>Example 1:</p>
  
  <pre><code>font.setStyleHint(QFont::AnyStyle, QFont::PreferAntialias);
  painter.setRenderHint(QPainter::TextAntialiasing);
  
  QStyleOptionGraphicsItem option;
  qreal lod = option.levelOfDetailFromTransform(painter.worldTransform());
  QRectF r = textRect;
  QFont f = font;
  qreal aspectRatio = painter.fontMetrics().lineSpacing() / painter.fontMetrics().averageCharWidth();
  int pixelsize = sqrt(r.width() * r.height() / aspectRatio / (m_text.length() * 3)) * aspectRatio;
  f.setPixelSize(pixelsize);
  int flags = Qt::AlignCenter | Qt::TextDontClip | Qt::TextWordWrap;
  if ((pixelsize * lod) &lt; 13)
      flags |= Qt::TextWrapAnywhere;
  QFontMetricsF fm(f);
  QRectF tbr = fm.boundingRect(r, flags, m_text);
  pixelsize = f.pixelSize() * qMin(r.width() * 0.65 / tbr.width(), r.height() * 0.65 / tbr.height());
  f.setPixelSize(pixelsize);
  painter.setFont(f);
  painter.drawText(r, flags, m_text);
  </code></pre>
  
  <p>However this leaves me with jittery text that is not smooth.</p>
  
  <p>Example 2:</p>
  
  <pre><code>float factor = (rectangle.width() / painter.fontMetrics().width(m_text))/2;
  if ((factor &lt; 1) || (factor &gt; 1.25))
  {
      font.setPointSizeF(font.pointSizeF()*factor);
      painter.setFont(font);
  }
  QPainterPath textPath;
  textPath.addText(textRect.topLeft(), font, m_text);
  painter.drawPath(textPath);
  </code></pre>
  
  <p>Example 3:</p>
  
  <pre><code>QImage image(size(), QImage::Format_ARGB32_Premultiplied);
  {
      QPainter p(&amp;image);
      p.setRenderHint(QPainter::TextAntialiasing);
  
      QFont font;
      font.setFamily("Roboto medium");
      font.setPointSize((double)scalar/10);
      font.setStyleHint(QFont::Helvetica, QFont::PreferAntialias);
  
      p.setPen(Qt::black);
      p.setFont(font);
  
      p.drawText(rect(), Qt::AlignLeft , m_text);
  }
  painter.drawImage(rectangle, image);
  </code></pre>
  
  <p>Honestly I am using these method to make circular buttons that can either have text, text+icon, or just an icon. I would like them to be scalable. Any method that can do as such would be greatly appreciated. Thank you very much.</p>