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.