How to center a variable QGraphicsSimpleTextItem in a rectangle

  • I want to add a simple text item (one word) to a QGraphicsScene and so use a QGraphicsSimpleTextItem. The scene coordinates of the text item defines the upper left corner of the text.

    Now, I want the text to be horizontally centered in a rectangle. If the text is static you can figure out what the upper left corner of the text should be to have it centered in the rectangle. Problem is when the text changes, you should each time reposition the text item to have it properly centered.

    Any idea on how to do this or alternative solutions?

  • Simple approach: Write a function that moves the item into the right position. Call it every time after calling setText

    Safer approach: Wrap the QGraphicsSimpleTextItem in your own class. Write a class deriving from QGraphicsItem, which has one single private child member: The QGraphicsSimpleTextItem. Write public interfaces for those methods you need, including setText. Now you know exactly when the text changes, and when to re-align the item.

Log in to reply