我正在尝试获取QGraphicsRectItem的子类的boundingRect(),同时由用户移动它。但是,当矩形在场景中移动时,boundingRect()返回的rect始终返回边界矩形的原始值。以下示例演示了此问题。当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_()
答案 0 :(得分:3)
QGraphicsItem
的{{1}}始终处于自己的坐标中。移动项目不会改变其相对于自身的边界矩形。
如果您需要相对于场景的项目的边界框,请使用sceneBoundingRect()