I have a problem with PySide coordinate system. I create a custom item (NodeItem) that inherits from QGraphicsRectItem and is positioned in the scene. This custom item has a child (LabelItem) that inherits from QGraphicsTextItem. When I add the parent item (NodeItem) to the scene is positioned in 150,150 in scene coordinates but the child LabelItem is positioned in scene coordinates not in his parent coordinates (NodeItem).
As you see in the image, “R1” LabelItem is in the origin of the scene not the origin of the NodeItem (the rectangle).
from PySide6.QtWidgets import QGraphicsRectItem, QGraphicsTextItem, QGraphicsScene, QGraphicsView, QApplication
from PySide6.QtGui import QColor, QPen, QBrush
from PySide6.QtCore import QRectF
from PySide6 import QtWidgets
class LabelItem(QtWidgets.QGraphicsTextItem):
def __init__(self, parent=None):
super().__init__(parent)
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | QtWidgets.QGraphicsItem.ItemIsSelectable)
self.setZValue(2)
class NodeItem(QGraphicsRectItem):
def __init__(self, x, y, width, height):
super().__init__(x, y, width, height)
pen = QPen(QColor("#000000"))
brush = QBrush(QColor("#FFD700"))
self.setPen(pen)
self.setBrush(brush)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsSelectable)
self.setFlag(QtWidgets.QGraphicsItem.ItemIsFocusable)
self.setFlag(QtWidgets.QGraphicsItem.ItemSendsGeometryChanges)
# LabelItem created as a child of this item
self.label = LabelItem(self) #Child item
self.label.setPlainText("R1")
self.update_label_position()
print(self.label.parentItem())
def update_label_position(self):
self.label.setPos(0, 0) #Child item positioned at 0,0
class MyGraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
self.setScene(QGraphicsScene(self))
self.setMouseTracking(True)
# Node item creation and positioned at 150,150 of the scene
node_item = NodeItem(150, 150, 100, 50)
self.scene().addItem(node_item)
if __name__ == "__main__":
app = QApplication([])
view = MyGraphicsView()
view.setSceneRect(0, 0, 400, 300)
view.show()
app.exec()