For Qt 4.6.x, how to auto-size text to fit in a specified width?

前端 未结 8 1223
情书的邮戳
情书的邮戳 2020-12-31 04:11

Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width

8条回答
  •  生来不讨喜
    2020-12-31 04:45

    Johannes from qtcentre.org offered the following solution:

    float factor = rect().width() / painter->fontMetrics().width(name);
     if ((factor < 1) || (factor > 1.25))
     {
      QFont f = painter->font();
      f.setPointSizeF(f.pointSizeF()*factor);
      painter->setFont(f);
     }
    

    I gave it a try in my program and so far, it seems to work quite well. I like it because it produces results in one pass, but it assumes that font width scales like its height.

    http://www.qtcentre.org/threads/27839-For-Qt-4-6-x-how-to-auto-size-text-to-fit-in-a-specified-width

提交回复
热议问题