Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Resizing Qlabel text upon resizing window
So I know that the Qlabel widget itself will decide its size based on the layout its placed in. But its text does not do that, staying the same font size initially given to it. How would one change its font size whenever the application window is resized?
You can use the resize event to alter the font size using QFontMetrics to find at what font size your text stays in the rectangle of the label.
Hope it helps
Thanks for the reply! Can you be more specific though? Which widget has the resize event? Ideally I'd like there to be a resize signal sent by the MainWindow that I can connect to a function that resizes QLabel. I haven't found anything similar though
Subclass QLabel and reimplement the resizeEvent method.
@SGaist Thanks again, that led me further down the path to solving the problem. Now I'm at another hurdle.
So far I've re-implemented resizeEvent for the MainWindow and had it emit a signal
void MainWindow::resizeEvent(QResizeEvent* event)
THEN I subclassed QLabel and created a slot to catch the signal and resize itself
void resizeLabel(int size);
void MyLabel::resizeLabel(int size)
After which I connected the two in MainWindow.cpp:
connect(this, SIGNAL(windowResized(int)), ui->label, SLOT(resizeLabel(int));
HOWEVER this doesn't seem to resize the QLabel when making the MainWindow bigger/smaller. It remains a static font size. When debugging, I see that the point size for the font is indeed changing but it doesn't seem to be translating to the label.
Your resizeLabel function does not in fact do anything on the widget size, it just modifies the font size
@SGaist That is exactly what I want though. The widget should just resize itself based on the layout its placed in, right? But this alone does not increase its font size
I believe I've solved it! Instead of setting the font in resizeLabel for the MyLabel class, just set the stylesheet, as so:
void MyLabel::resizeLabelH1(int size)
"font-size: " + QString::number(size) + "pt;"
HOWEVER, if you've set the font size of the QLabel in the ui form editor, then it will use that size over the size you use in the stylesheet. In other words, styles set in the HTML text take precedent over styles set in the stylesheet. So for this to work, the original ui form text has to be as plain as can be
Are you sure your function is called ?
@SGaist Positive, set a breakpoint within the function and it's called every time I resize the window
Which version are you currently using ? The QFont or stylesheet ?