2013-06-19 38 views
0

我正在尋找最有效的方法來根據給定的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); 
} 

可以將哪些代碼添加到構造函數中以使我的需求有效?根據字符串的總長度設置寬度,對每個字符佔用多少像素空間進行假設是最明顯的解決方案,但我正在尋找一些更優雅的東西。有任何想法嗎?預先感謝您的任何幫助。

回答

1

QFontMetrics類有一個名爲boundingRect的函數,它根據您用於初始化QFontMetrics的QFont,接收您希望打印的字符串並返回字符串的QRect。

如果你想包裝,那麼你需要計算出你的字符串中允許boundingRect返回符合你的QGraphicsItem的boundingRect的QRect的最大字數。

+0

正是我在找的,謝謝。 – c0nn

1

看看到QFontMetrics

你可以問你的widget爲font

而且從QFontMetrics文檔檢查這個片段

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

編輯:作爲梅林評論說,使用

QRect QFontMetrics::boundingRect (const QString & text) const 所以:

int pixelsWide = fm.boundingRect(「這是什麼寬度的文本?」)。

+2

width()不會返回文本佔用的像素,但會被定義爲返回「到下一個字符串應繪製到的位置的距離」,這可能是也可能不是正確的值,特別是如果它用於包裝文本,如要求。 – TheDarkKnight

+1

編輯,謝謝 – Trompa

相關問題