Position a QGraphicsItem by its center point (not top left corner)

  •     def setPos(self, pos):
            rect = self.boundingRect()
            offset = rect.center()
            super().setPos(pos - offset)

    This code gets called but has no effect (does same thing as without it)

  • Moderators

    I don't know python that much but setPos is not virtual in C++ (when called on a pointer to base class the base will be called).

    Instead of doing this manually use setTransformOriginPoint() to set the transform origin to the center and then use the usual setPos() without offset.

  • I tried setTransformationOriginPoint, I'll try it again mixed with this solution that does work:

        def __init__(self, text):
            self.button = PushButton(text)
            self.setFlags(self.ItemIsFocusable | self.ItemIsMovable | self.ItemIsSelectable| self.ItemSendsGeometryChanges)
            proxy = QGraphicsProxyWidget(parent=self)
            w = self.button.width()
            h = self.button.height()
            proxy.setPos(-w/2, -h/2)
        def boundingRect(self):
            w = self.button.width()
            h = self.button.height()
            rect = QRectF(-w/2, -h/2, w, h)

    Note that I set the position of the child that determines this QGraphicsObject's size, as well as translated the boundingRect.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.