Forked from earthday/dynamic_font_size_in_qlabel_based_on_text_length.cpp
Created
May 27, 2022 07:41
-
-
Save flyfire/f75725ddeac5c8655c3ed543bd6fca7c 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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