Getting QGraphicsTextItem length?

4.7k views Asked by At

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.

3

There are 3 answers

2
Exa On BEST ANSWER

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.

0
Alexander On

I found this post by stopping on the same problem.

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

Perhaps it helps anybody

2
DerManu On

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.