根据字符串长度大小QGraphicsItem

Size QGraphicsItem based on string length

本文关键字:QGraphicsItem 字符串      更新时间:2023-10-16

我正在寻找基于给定QString的长度来确定QGraphicsItem大小的最有效方法,以便文本始终包含在QGraphicsItem的边界内。这个想法是保持QGraphicsItem尽可能小,同时仍然包含一个易读的大小的文本。以一定的宽度阈值换行到多行也是理想的。例如,

TestModule::TestModule(QGraphicsItem *parent, QString name) : QGraphicsPolygonItem(parent)
{
    modName = name;
    // what would be the best way to set these values?
    qreal w = 80.0; 
    qreal h = 80.0;
    QVector<QPointF> points = { QPointF(0.0, 0.0),
                                QPointF(w, 0.0),
                                QPointF(w, h),
                                QPointF(0.0, h) };
    baseShape = QPolygonF(points);
    setPolygon(baseShape);
}
void TestModule::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QBrush *brush = new QBrush(Qt::gray, Qt::SolidPattern);
    painter->setBrush(*brush);
    painter->drawPolygon(baseShape);
    painter->drawText(QPointF(0.0, 40.0), modName);
}

我可以添加什么代码到构造函数使我的需求工作?根据字符串的总长度设置宽度,假设每个字符占用多少像素空间是最明显的解决方案,但我正在寻找更优雅的方法。什么好主意吗?提前感谢您的帮助

QFontMetrics类有一个叫做boundingRect的函数,它接受你想要打印的字符串,并根据你用来初始化QFontMetrics的QFont返回字符串的QRect。

如果你想换行,那么你需要计算出字符串中允许boundingRect返回符合QGraphicsItem的boundingRect的QRect的最大单词数

看一下QFontMetrics

你可以向你的小部件询问字体

检查QFontMetrics文档

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

编辑:正如梅林在评论中所说,使用

QRect QFontMetrics::boundingRect (const QString &文本)const所以:

int pixelwide = fm。boundingRect(" text的width是多少").width();