QGraphicsItem size based on string length
I'm looking for the most efficient way to size QGraphicsItem
based on the length given QString
so that the text is always contained within the bounds of the QGraphicsItem. The idea is to keep QGraphicsItem
as small as possible while keeping the text in a legible size. The ideal would be to combine several lines with a certain threshold width. 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 fulfill my requirement? Setting the width based on the total line length makes assumptions about how many pixels each character takes up is the most obvious solution, but I'm looking for something more elegant. Any ideas? Thanks in advance for any help.
source to share
The QFontMetrics class has a boundingRect function that takes the string you want to print and returns a QRect for the string based on the QFont you used to initalize the QFontMetrics.
If you want to wrap, then you will need to work out the maximum number of words in your string, which will allow boundingRect to return a QRect that fits within your boundingRect QGraphicsItem object.
source to share
Take a look at QFontMetrics
You can set your font widget
And check this snippet from the QFontMetrics docs
QFont font("times", 24);
QFontMetrics fm(font);
int pixelsWide = fm.width("What the width of this text?");
int pixelsHigh = fm.height();
Edit: As Merlin said in a comment, use
QRect QFontMetrics :: boundingRect (const QString and text) const So:
int pixelsWide = fm.boundingRect ("What's the width of this text?"). width ();
source to share