Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save earthday/7cb3cb9b00f033e05834 to your computer and use it in GitHub Desktop.
Save earthday/7cb3cb9b00f033e05834 to your computer and use it in GitHub Desktop.
Dynamic font size in QLabel based on text length which is copied from http://www.qtforum.org/article/32092/dynamic-font-size-in-qlabel-based-on-text-length.html
int fit = false;
this->testLabel->setText("");
QLabel *myLabel = this->testLabel;
QFont myFont = myLabel->font();
QString str = "this is the new string. this is the new string. this is the new string. super long. don't fit. please please please overflow the box";
while (!fit)
{
QFontMetrics fm( myFont );
QRect bound = fm.boundingRect(0,0, myLabel->width(), myLabel->height(), Qt::TextWordWrap | Qt::AlignLeft, str);
if (bound.width() <= myLabel->width() &&
bound.height() <= myLabel->height())
fit = true;
else
myFont.setPointSize(myFont.pointSize() - 1);
}
myLabel->setFont(myFont);
myLabel->setText(str);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment