如何让QGraphicsItem跟随某点移动
时间: 2023-12-13 11:02:45 浏览: 30
要让QGraphicsItem跟随某点移动,可以定义一个QPointF类型的变量来保存该点的坐标,然后在QGraphicsItem的paint()方法中,通过该点的坐标来设置该QGraphicsItem的位置。具体实现步骤如下:
1. 在QGraphicsItem的构造函数中定义一个QPointF类型的变量,用于保存该点的坐标。
2. 在QGraphicsItem的paint()方法中,通过该点的坐标来计算出该QGraphicsItem的位置,并将其设置为该QGraphicsItem的位置。
下面是一个示例代码,展示如何实现让QGraphicsItem跟随某点移动:
```python
class MyItem(QGraphicsItem):
def __init__(self, point):
super().__init__()
self.point = point # 定义一个QPointF类型的变量,用于保存该点的坐标
def paint(self, painter, option, widget):
# 通过该点的坐标来计算出该QGraphicsItem的位置,并将其设置为该QGraphicsItem的位置
self.setPos(self.point.x() - self.boundingRect().width() / 2, self.point.y() - self.boundingRect().height() / 2)
# 绘制该QGraphicsItem
painter.drawRect(self.boundingRect())
```
在上述代码中,我们定义了一个名为MyItem的QGraphicsItem子类,并在其构造函数中定义了一个QPointF类型的变量point,用于保存该点的坐标。在其paint()方法中,我们通过该点的坐标来计算出该QGraphicsItem的位置,并将其设置为该QGraphicsItem的位置。最后,我们绘制该QGraphicsItem的边框。