Solved how to resize a text automatically to fit the qpushbutton ?
-
I tried many methods but still the same result.
Does anyone have an idea to solve this problem ( I'm using qt5 widgets ) -
auto text_rect = QFontMetrics( your_font ).tightBoundingRect( your text );
if text_rect.width() is bigger than the button width, reduce font size. You need a few loops. -
QString str = _translation.getButton_confirm_storagewithdraw(); // text QPushButton *BTNConfirmRetrieve = new QPushButton(this); BTNConfirmRetrieve->setFixedSize(QSize(1000,141)); qreal oldFontSize, newFontSize; oldFontSize = BTNConfirmRetrieve->font().pointSizeF(); qDebug() << " old font size = " << oldFontSize; QFont font; int h = BTNConfirmRetrieve->rect().height() - 8; int w = BTNConfirmRetrieve->rect().width() - 8; qDebug() << " h and w = " << h << w; qreal step = 0.5; QRect textRect = BTNConfirmRetrieve->fontMetrics().boundingRect(str); while (textRect.width() > w) { oldFontSize -= step; newFontSize = oldFontSize; font.setPointSizeF(newFontSize); BTNConfirmRetrieve->setFont(font); oldFontSize = newFontSize; } font.setPointSizeF(oldFontSize); BTNConfirmRetrieve->setText(str); BTNConfirmRetrieve->setFont(font); ui->LayoutControlRetrieve->addWidget(BTNConfirmRetrieve); ** I tried this method but always the same problem **
-
I use it a lot and do not have any issues on Linux.
I found some note:
The current style, which is used to render the content of all standard Qt widgets, is free to choose to use the widget font, or in some cases, to ignore it (partially, or completely). In particular, certain styles like GTK style, Mac style, and Windows Vista style, apply special modifications to the widget font to match the platform's native look and feel. Because of this, assigning properties to a widget's font is not guaranteed to change the appearance of the widget. Instead, you may choose to apply a styleSheet.
Note: If Qt Style Sheets are used on the same widget as setFont(), style sheets will take precedence if the settings conflict.
at https://doc.qt.io/qt-5/qwidget.html#font-prop
You can also try to use style sheet to change font.
-
@JoeCFD thank you Joe,
I found the solution on github
https://github.com/jonaias/DynamicFontSizeWidgets