Getting QGraphicsTextItem length?
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 whe开发者_开发知识库n characters exceed the rectangle.
I found this post by stopping on the same problem.
i'm using text->boundingRect().width()
to get the width.
Perhaps it helps anybody
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.
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.
精彩评论