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.
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.
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.
textWidth = -1 means, that
(QTextDocument::textWidth())
So, if you want to get the length of your
QGraphicsTextItem
you can't usetextWidth
, but instead you need the actual length of the String within thisQGraphicsTextItem
. Have a look at QGraphicsTextItem::toPlainText(), which returns a QString. Callsize()
on that string.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.