我有類似的問題,並通過實現mousePressEvent和mouseMoveEvent在QGraphicsScene的一個子類,並且具有存儲當前選擇的節點的變量解決它。沿着這些路線的東西:
# 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用於項目本身
你必須勾勒出你詳細做什麼。例如,爲什麼不能將這條線作爲橢圓的父親? ([見這個近來對可能相關的問題Q&A](http://stackoverflow.com/questions/21745025/))父子關係不把事情一起移動,只是一個方便的,如果它的唯一途徑適合。您可以完全避免親子關係,觀看移動通知,並根據您的喜好調整迴應。 *請注意,你可以編輯你的問題與編輯按鈕添加更多詳細信息... * – HostileFork
這只是什麼,我已經嘗試過一個例子,我只是想行跟隨點,當他們移動,這也正是我以爲會工作 – Rooxo
嘗試尋找在[彈性節點樣品(http://qt-project.org/doc/qt-5.0/qtwidgets/graphicsview-elasticnodes.html),看看有沒有什麼幫助你。 – HostileFork