我遇到了类似的问题,并通过在 QGraphicsScene 的子类中实现 mousePressEvent 和 mouseMoveEvent 并具有存储当前选定节点的变量来解决它。大致如下:
# Allows moving nodes across the scene updating the connections
def mouseLeftClickMoveEvent(self,event):
# If no node is selected, skip
if self.selected_item is None:
return
# QtConnections are not movable
if isinstance( self.selected_item, QtConnection ):
return
# Update the position of the selected node
new_pos = event.scenePos()
new_x = int(new_pos.x()/self.grid_size)*self.grid_size
new_y = int(new_pos.y()/self.grid_size)*self.grid_size
self.selected_item.setRect( QRectF(new_x,new_y,self.selected_item.node_size,self.selected_item.node_size) )
# Update the position of the connections to the node
for c in self.selected_item.incons:
x1 = c.line().p1().x()
y1 = c.line().p1().y()
x2 = self.selected_item.rect().center().x()
y2 = self.selected_item.rect().center().y()
c.setLine(x1,y1,x2,y2)
# Update the position of the connections from the node
for c in self.selected_item.outcons:
x1 = self.selected_item.rect().center().x()
y1 = self.selected_item.rect().center().y()
x2 = c.line().p2().x()
y2 = c.line().p2().y()
c.setLine(x1,y1,x2,y2)
# Update the scene to repaint the background
self.update()
为此,您还必须对 QGraphicsEllipseItem 进行子类化,以便您拥有一个包含传入和传出连接的数组。比如:
class QtNode(QGraphicsEllipseItem):
def __init__(self, node, layout):
super(QGraphicsEllipseItem, self).__init__()
self.id = node.id
self.node = node
self.incons = []
self.outcons = []
另外,更好的解决方案可能是为项目本身实现 mousePressEvent 和 mouseMoveEvent