具有自动缩放功能的 QLabel

QLabel with automatic scaling

本文关键字:功能 QLabel 缩放      更新时间:2023-10-16

我需要一个Qt小部件,它显示自动缩放的纯文本。这意味着当我调整布局中包含此小部件的窗口大小时,字体大小会调整为小部件的大小,以尽可能大的字体显示文本,以适应布局指示的大小。自动换行可能是一个奖励。

我想,有人已经实现了这样的小部件,但我无法谷歌它。

您可以在窗口的调整大小事件上执行此操作:

void MainWindow::resizeEvent(QResizeEvent*)
{
    QFont f = label->font(); //Get label font
    QFontMetrics metrics(f);
    QSize size = metrics.size(0, label->text()); //Get size of text
    float factorw = label->width() / (float)size.width(); //Get the width factor
    float factorh = label->height() / (float)size.height(); //Get the height factor
    float factor = qMin(factorw, factorh); //To fit contents in the screen select as factor
                                           //the minimum factor between width and height
    f.setPointSizeF(f.pointSizeF() * factor); //Set font size
    label->setFont(f); //Set the adjusted font to the label
}