我正在尋找最有效的方法來根據給定的QString
的長度來確定QGraphicsItem
的大小,以便文本始終包含在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);
}
可以將哪些代碼添加到構造函數中以使我的需求有效?根據字符串的總長度設置寬度,對每個字符佔用多少像素空間進行假設是最明顯的解決方案,但我正在尋找一些更優雅的東西。有任何想法嗎?預先感謝您的任何幫助。
正是我在找的,謝謝。 – c0nn