I am looking for an effective way to use the drawText
method of QPainter according to a QRect. For example if I were to have a QRect as the origin with a size of 50x50: QRect(0, 0, 50, 50);
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.
Example 1:
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) < 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);
However this leaves me with jittery text that is not smooth.
Example 2:
float factor = (rectangle.width() / painter.fontMetrics().width(m_text))/2;
if ((factor < 1) || (factor > 1.25))
{
font.setPointSizeF(font.pointSizeF()*factor);
painter.setFont(font);
}
QPainterPath textPath;
textPath.addText(textRect.topLeft(), font, m_text);
painter.drawPath(textPath);
Example 3:
QImage image(size(), QImage::Format_ARGB32_Premultiplied);
{
QPainter p(&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);
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.