我需要一个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
}

09-10 04:02
查看更多