1

Is there anyway to calculate the text's length when TextWidth = -1?.

I have a rectangle that has a QGraphicsTextItem in it, and I want to change the rectangle's width when characters exceed the rectangle.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Baris Atamer
  • 700
  • 7
  • 13

3 Answers3

8

I found this post by stopping on the same problem.

i'm using text->boundingRect().width()to get the width.

Perhaps it helps anybody

Alexander
  • 494
  • 5
  • 12
0

textWidth = -1 means, that

"[...] the text will not be broken into multiple lines unless it is enforced through an explicit line break or a new paragraph."

(QTextDocument::textWidth())

So, if you want to get the length of your QGraphicsTextItem you can't use textWidth, but instead you need the actual length of the String within this QGraphicsTextItem. Have a look at QGraphicsTextItem::toPlainText(), which returns a QString. Call size() on that string.

int length = my_graphics_text_item.toPlainText().size() 

Now you have the number of characters in this string and can implement a resize function to make your rectangle grow, when there are too many characters. It's a kind of workaround, but I hope it helps solving your problem.

Exa
  • 4,020
  • 7
  • 43
  • 60
  • 2
    Also I found that : qreal w = text.document()->size().width(); – Baris Atamer Feb 01 '11 at 09:04
  • > Have a look at QGraphicsTextItem::toPlainText(), which returns a > QString. Call size() on that string. Unfortunately, that only works if you are in a fixed width font, like Courier. Instead, use item->boundingRect().width() –  Sep 29 '11 at 16:38
0

You could also create a QFontMetrics([font of your QGraphicsTextItem]) instance and call its width(QString) function to obtain the width of the passed string in pixels, were it drawn in the specified fontfamily/-size/-weight. Just obtaining the character count is only reasonable when using a monospaced font. In all other cases it's not a good idea.

DerManu
  • 702
  • 4
  • 12
  • From all sources I have read, QFontMetrics has been bugged beyond usability for years. There appears to be no fix in sight. – optikradio Apr 03 '13 at 06:56
  • @optikradio: Hm, I've been using QFontMetrics alot and have noticed only one slight annoyance (It was a jitter from call to call of some bounding box function due to internal rounding) in all that time. So the Class seems okay to me. You should name your sources, I'm very interested. – DerManu Apr 06 '13 at 14:45