如何使用 QPainter 缩放文本以适应边界框?

How to scale text to fit inside a bounding box with QPainter?

我需要在盒子上画一个标签。

理想情况下,我会根据框的大小缩放标签,但我不确定是否有任何内置功能可以进行这种缩放。

目前我正在将对象缩放到边界框的高度,但我不确定如何实现宽度缩放,因为绘制文本的宽度取决于符号的特定顺序(由于字距)。

这种缩放是否有一些内置功能?

void total_control_roi_item::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    QGraphicsRectItem::paint(painter, option, widget);
    painter->save();
    const auto rect = boundingRect();
    auto font = painter->font();
    auto height_of_box = rect.height()*0.7;
    font.setPointSizeF(height_of_box);
    painter->setFont(font);
    const auto label = QString("%1").arg(id_);
    painter->drawText(rect, label, Qt::AlignHCenter | Qt::AlignVCenter);
    painter->restore();
}

您可以使用QFontMetrics的信息进行文字升级。

#include <QtWidgets>

class RectItem: public QGraphicsRectItem
{
public:
    using QGraphicsRectItem::QGraphicsRectItem;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
    {
        const QString id_ = "Stack Overflow";
        const auto label = QString("%1").arg(id_);
        QGraphicsRectItem::paint(painter, option, widget);
        if(label.isEmpty()) return;
        const auto rect = boundingRect();
        QFontMetrics fm(painter->font());
        qreal sx = rect.width()*1.0/fm.width(id_);
        qreal sy = rect.height()*1.0/fm.height();
        painter->save();
        painter->translate(rect.center());
        painter->scale(sx, sy);
        painter->translate(-rect.center());
        painter->drawText(rect, label, Qt::AlignHCenter | Qt::AlignVCenter);
        painter->restore();
    }
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QGraphicsScene scene;
    QGraphicsView w(&scene);
    scene.addItem(new RectItem(0, 0, 300, 200));
    w.resize(640, 480);
    w.show();

    return a.exec();
}