qttextqgraphicstextitem

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 when characters exceed the rectangle.


Solution

  • 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.