2

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

理想情况下,我会用盒子的大小来缩放标签,但我不确定是否有任何内置功能可用于这种缩放。

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

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

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();
}
4

1 回答 1

2

您可以使用 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();
}
于 2019-01-10T20:37:07.643 回答