Scale QLabel based on text
Solved
General and Desktop
-
Hi. I have some text in a QLabel.
According to my code, the size of the two QLabels are 100px. I was wondering whether is a way of scaling the QLabel's size based on the length of text. I am aware that setScaledContents is a thing, but that one is for QPixmaps and only scales the Pixmap instead of the QLabel.I would like the QLabel to be scaled because I am trying to place the QLabel's center exactly under the QFrames (the vertical bars).
QFrame *frontLine = new QFrame(this); frontLine->setStyleSheet("border: 10px solid #000080;"); frontLine->setGeometry(X, Y, SPLITLINEWIDTH, SPLITLINEHEIGHT); QLabel *iniTemp = new QLabel(this); iniTemp->setText("REEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE"); iniTemp->setStyleSheet("color: navy; background: green; font: 12px; alignment: left;"); iniTemp->setFrameShadow(QFrame::Raised); iniTemp->setFrameStyle(QFrame::Panel); iniTemp->setLineWidth(2); qDebug() << (iniTemp->width()); //How can this be 0? iniTemp->move(X - (iniTemp->width()-65), Y+SPLITLINEHEIGHT+LABELDISTANCE); QFrame *backLine = new QFrame(this); backLine->setStyleSheet("border: 10px solid #000080;"); X = MAINLINEX + MAINLINEW - SPLITLINEWIDTH/2; backLine->setGeometry(X, Y, SPLITLINEWIDTH, SPLITLINEHEIGHT); QLabel *finTemp = new QLabel(this); finTemp->setText("Final Temp"); finTemp->setStyleSheet("color: navy; background: green; font: 12px; alignment: center;"); finTemp->setFrameShadow(QFrame::Raised); finTemp->setFrameStyle(QFrame::Panel); finTemp->setLineWidth(2); qDebug() << (finTemp->width()); finTemp->move(X - (finTemp->width())/2, Y+SPLITLINEHEIGHT+LABELDISTANCE);
Please let me know if more information is required.
-
@Dummie1138 You can use https://doc.qt.io/qt-6/qfontmetrics.html to figure out how wide your QLabel has to be to show the given string with the given font.