您可以在GraphicsView中使用定时器来创建GraphicsRectItem并实现直线运动。下面是一个示例代码:
”`python from PyQt5.QtWidgets import QGraphicsScene, QGraphicsView, QGraphicsRectItem, QApplication from PyQt5.QtCore import QTimer, QPointF
class CustomRectItem(QGraphicsRectItem):
def __init__(self):
super().__init__()
self.setRect(0, 0, 50, 50) # 设置矩形大小和位置
self.start_pos = QPointF(0, 0) # 起始位置
self.end_pos = QPointF(200, 200) # 终点位置
self.current_pos = self.start_pos # 当前位置
def updatePosition(self):
delta_x = (self.end_pos.x() - self.start_pos.x()) / 100.0
delta_y = (self.end_pos.y() - self.start_pos.y()) / 100.0
self.current_pos.setX(self.current_pos.x() + delta_x)
self.current_pos.setY(self.current_pos.y() + delta_y)
if abs(self.current_pos.x() - self.end_pos.x()) < abs(delta_x):
if abs(self.current_pos.y() - self.end_pos.y()) < abs(delta_y):
# 达到终点位置后停止移动
return False
self.setPos(self.current_pos)
return True
class GraphicsView(QGraphicsView):
def __init__(self):
super().__init__()
scene = QGraphicsScene()
<br/><br/><br/><font size=1 color=#CCCCCC>内容由零声教学AI助手提供,问题来源于学员提问</font>