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)
-
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): super().__init__() self.button = PushButton(text) self.setFlags(self.ItemIsFocusable | self.ItemIsMovable | self.ItemIsSelectable| self.ItemSendsGeometryChanges) proxy = QGraphicsProxyWidget(parent=self) proxy.setWidget(self.button) proxy.setParentItem(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.
-
Hi, not sure if I am best off replying here or creating a new thread but this is what comes up when Googling for the problem so I thought I'd reply to this first.
I am trying like the original question to position an item via its center point rather than the top left point as is default unfortunately your suggestion does not work? I set the transform point to boundingRect.center() I then call setPos but it is still positioned by the top left corner of the item. Any ideas?
Cheers!
-
Re: Position a QGraphicsItem by its center point (not top left corner)
void Item::updatePaintPath() { setTransformOriginPoint(boundingRect().center()); }
This is an alternative to doing the centering by hand as in above posts. However, my paintPath is still off-center, don't know if related.
You call the above base method at the end of each subclass udpatePaintPath() method, which is where we expect a change in the bounding rect say if there are nested nodes.
I know it works because I commented out my centerPoint() code and just returned pos() and the cursor still centers on the item when I go to place a node.