【问题标题】:How to get the sizes of the rendered text on a QPainter?如何在 QPainter 上获取渲染文本的大小?
【发布时间】:2013-06-02 01:56:38
【问题描述】:

我在 QPainter 上的 Qt 程序中绘制文本和围绕它的各种元素。我需要获取此文本将占用的像素大小。

如果我知道文本字符串和字体,我能以某种方式获得以像素为单位的大小吗?

谢谢。

【问题讨论】:

    标签: c++ qt qpainter


    【解决方案1】:

    您可以为此目的使用 QFontMetrics。以下是来自 Qt Docs 的示例。

     QFont font("times", 24);
     QFontMetrics fm(font);
     int pixelsWide = fm.width("What's the width of this text?");
     int pixelsHigh = fm.height();
    

    【讨论】:

    • 请注意,QPainter 的 boundingRect() 方法也会这样做,使用画家的当前字体。
    【解决方案2】:

    QPainter 的 boundingRect() 将返回一个矩形,您可以使用它来获取“宽度”和“高度”:

            QPainter qp(this);
            QFont font = qp.font();
            font.setPixelSize(24);
            qp.setFont(font);
            qp.setPen(Qt::white);
            QString text = "Hello, World!";
            QRect br = qp.boundingRect(0, 0, 150, 30, 0, text);
            qDebug() << br.width();
            qDebug() << br.height();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多