Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QGraphicsRectItem.boundingRect() not updated during move

I'm trying to get the boundingRect() of a subclass of a QGraphicsRectItem while it is being moved by the user. However, as the rectangle is moved in the scene, the rect returned by boundingRect() always returns the original value for the bounding rectangle. The example below demonstrates the issue. The value of boundinRect() is printed for every mouse move while the RectItem is moved around the scene. Why isn't boundingRect() returning the new bounding rectangle? What am I doing wrong?

from sys import argv

from PyQt4.Qt import QApplication
from PyQt4.QtCore import QPointF, QRectF, Qt
from PyQt4.QtGui import (
    QGraphicsItem,
    QGraphicsRectItem,
    QGraphicsScene,
    QGraphicsView,
)


class RectItem(QGraphicsRectItem):
    def __init__(self, parent):
        super(RectItem, self).__init__(parent)
        self.setFlag(QGraphicsItem.ItemIsMovable, enabled=True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, enabled=True)

    def mouseMoveEvent(self, event):
        super(RectItem, self).mouseMoveEvent(event)
        print self.boundingRect()


class ViewItem(QGraphicsRectItem):
    def __init__(self, x, y, width, height, parent=None, scene=None):
        super(ViewItem, self).__init__(parent, scene)
        self.setRect(QRectF(x, y, width, height))
        self.create_child_item(100, 100)

    def create_child_item(self, x, y):
        self.child_item = RectItem(self)
        self.child_item.setRect(x, y, 200, 100)
        self.child_item.setSelected(True)


class View(QGraphicsView):
    def __init__(self, parent=None):
        super(View, self).__init__(parent)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setInteractive(True)
        self.graphics_scene = QGraphicsScene(self)
        self.setScene(self.graphics_scene)
        self.setAlignment(Qt.AlignTop)
        self.add_view_item()

    def add_view_item(self):
        self.view_item = ViewItem(0.0, 0.0, 1024.0, 768.0)
        self.graphics_scene.addItem(self.view_item)


if __name__ == '__main__':
    app = QApplication(argv)
    view = View()
    view.setGeometry(100, 100, 1024, 768)
    view.setWindowTitle('View Test')
    view.show()
    app.exec_()
like image 506
Vincent Vega Avatar asked Jul 01 '13 18:07

Vincent Vega


1 Answers

QGraphicsItem's boundingRect() is always in its own coordinate. Moving a item doesn't change its bounding rect relative to itself.

If you need the bounding box of the item relative to the scene, use sceneBoundingRect()

like image 68
Stephen Chu Avatar answered Sep 25 '22 03:09

Stephen Chu