5

我试图在用户移动 QGraphicsRectItem 的子类时获取它的 boundingRect() 。但是,当矩形在场景中移动时,boundingRect() 返回的矩形总是返回边界矩形的原始值。下面的示例演示了该问题。当 RectItem 在场景中移动时,每次鼠标移动都会打印 boundinRect() 的值。为什么 boundingRect() 不返回新的边界矩形?我究竟做错了什么?

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_()
4

1 回答 1

6

QGraphicsItem'sboundingRect()总是在它自己的坐标中。移动项目不会改变其相对于自身的边界矩形。

如果您需要项目相对于场景的边界框,请使用sceneBoundingRect()

于 2013-07-01T18:12:01.280 回答