Size QGraphicsItem based on string length
Asked Answered
A

2

0

I'm looking for the most effective way to size a QGraphicsItem based on the length of a given QString, so that the text is always contained within the QGraphicsItem's boundaries. The idea is to keep the QGraphicsItem as small as possible, while still containing the text at a legible size. Wrapping onto multiple lines at a certain width threshold would be ideal as well. For example,

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

what code could I add to the constructor to make my requirement work? Setting the width based on the total length of the string, making assumptions for how much pixel space each character takes up is the most obvious solution, but I'm looking for something a little more elegant. Any ideas? Thank you in advance for any help.

Assumption answered 19/6, 2013 at 14:1 Comment(0)
H
1

The QFontMetrics class has a function called boundingRect which takes the string that you're wanting to print and returns the QRect for the string, based on the QFont that you used to initalise QFontMetrics.

If you want to wrap, then you'd need to work out the maximum number of words in your string that will allow boundingRect to return a QRect that fits within your QGraphicsItem's boundingRect.

Hohenlinden answered 19/6, 2013 at 14:12 Comment(0)
L
1

Take a look to QFontMetrics

You can ask your widget for the font

And check this snippet from QFontMetrics docs

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

Edit: As Merlin said in comment, use

QRect QFontMetrics::boundingRect ( const QString & text ) const So:

int pixelsWide = fm.boundingRect("What's the width of this text?").width();

Linnea answered 19/6, 2013 at 14:19 Comment(1)
width() does not return the pixels taken up by the text, but is defined as returning "the distance to where the next string should be drawn", which may or may not be the correct value, especially if it is used to wrap the text, as requested.Hohenlinden

© 2022 - 2024 — McMap. All rights reserved.