so.very.tired
so.very.tired

Reputation: 3086

PyQt: Controlling position of QGraphicsRectItem with setRect()

I am taking my first shot at PyQT, in order to eventually create quite basic graphic representation of some data.
I am currently trying to box two QGraphicsTextItems inside QGraphicsRectItem, and I have some question regarding some result I see.

class MyRect(QGraphicsRectItem):

    def __init__(self, parent = None):
        super(MyRect, self).__init__(parent)

        self.text_item  = QGraphicsTextItem('My Text Here', self)
        self.value_item = QGraphicsTextItem('My Value Here', self)
        self.text_item.setDefaultTextColor(QColor(Qt.blue))
        self.value_item.setDefaultTextColor(QColor(Qt.red))

        self.value_item.setPos(self.text_item.boundingRect().bottomLeft())

        width  = max(self.text_item.boundingRect().width(), self.value_item.boundingRect().width())
        height = self.text_item.boundingRect().height() + self.value_item.boundingRect().height()
        self.setRect(50, 50, width, height)


class MainFrame(QDialog):

    def __init__(self, parent = None):
        super(MainFrame, self).__init__(parent)

        ### setting up the scene
        self.view = QGraphicsView()
        self.scene = QGraphicsScene(self)
        self.view.setScene(self.scene)
        self.scene.setSceneRect(0, 0, 500, 500)

        ### setting up MyRect
        my_rect = MyRect()

        self.scene.addItem(my_rect)

        layout = QHBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)

        self.setWindowTitle("Basic test")

The above produce this:
enter image description here
which is not quite what I intended.
After some more experimenting, I found out that changing this:

self.setRect(50, 50, width, height)

to this:

self.setRect(0, 0, width, height)
self.setPos(50, 50)

made the trick:
enter image description here
How come? What's the difference between setting position of the rectangle with setRect(), and setting position explicitly with setPos()?

Upvotes: 3

Views: 1350

Answers (1)

Andrew W
Andrew W

Reputation: 415

The difference is that the functions are defined with respect to different coordinate systems. According to the documentation, setPos() defines the position of the rectangle in its parent's coordinate system, while setRect() defines the position and size of the rectangle within its own local coordinate system. So The (x,y) of setPos() and the (x,y) of setRect() do not have the same meaning.

With setPos(50, 50), you're saying the origin of the rectangle's local coordinate system is located at position (50, 50) in the coordinate system of the QGraphicsScene (its parent). Then with setRect(0, 0, width, height), you're saying the rectangle is located at the origin (0,0) in its own coordinate system (which is actually (50, 50) in the scene coordinate system).

Upvotes: 2

Related Questions