问题
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.
回答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.
回答2:
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();
来源:https://stackoverflow.com/questions/17193286/size-qgraphicsitem-based-on-string-length