Search code examples
qtpyqtqt5pyqt5qgraphicstextitem

QGraphicsTextItem: Increasing size equally in both directions (left and right)


Background

I'm using QGraphicsTextItem inside a QGraphicsScene and would like to center the text and slowly and smoothly make it larger as time passes.

For QGraphicsTextItem there's no setWidth()/setRight() function, instead I use setScale() to increase the size. The position will remain the same though, since I haven't found any way to center align the graphics item, so I need to also change the position using setPos()

The problem is that setPos() and setScale() doesn't combine well since the first uses pixels and the second is relative

Question

How can I center the text and increase it's size in both (left/right) directions equally?

Grateful for help with this!


Solution

  • The transformations are with respect to a point, this point can be changed through the function setTransformOriginPoint (), as it is required that the object does not move and only scale then you must establish that point in the center of the item.

    item.setTransformOriginPoint(item.boundingRect().center())
    item.setScale(factor)
    

    Example:

    if __name__ == '__main__':
        import sys
    
        app = QApplication(sys.argv)
        w = QGraphicsView()
        w.setScene(QGraphicsScene(QRectF(0, 0, 640, 480)))
        w.show()
        it = QGraphicsTextItem("test")
        w.scene().addItem(it)
        it.setPos(320, 240)
        it.setTransformOriginPoint(it.boundingRect().center())
        timeline = QTimeLine()
        timeline.setFrameRange(1, 10)
        timeline.setCurveShape(QTimeLine.CosineCurve)
        timeline.frameChanged.connect(it.setScale)
        timeline.start()
        sys.exit(app.exec_())