Код: Выделить всё
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Circle(QGraphicsRectItem):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.orgpos = None
self.lastpos = None
class Scene(QGraphicsScene):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
circ = Circle(0,0,100,50)
circ.setPos(500,500)
self.addItem(circ)
self.selected = [circ]
circ2 = Circle(0,0,100,50)
circ2.setPos(0,100)
self.addItem(circ2)
def mousePressEvent(self, event):
self.offset = event.scenePos()
for x in self.selected:
x.orgpos = x.pos()
def mouseMoveEvent(self, event):
for item in self.selected:
item.setPos(event.scenePos()-self.offset+item.orgpos)
if len(item.collidingItems(Qt.IntersectsItemShape))>0:
for x in self.selected:
x.setPos(x.lastpos)
break
item.lastpos = item.pos()
if __name__ == '__main__':
app = QApplication(sys.argv)
scene = Scene(0, 0, 1000, 800)
view = QGraphicsView(scene, renderHints=QPainter.Antialiasing)
view.show()
sys.exit(app.exec_())
Код также использует список элементов и применяет одинаковое движение ко всем, поэтому в случае, если один элемент сталкивается и выбрано несколько, все они не перемещаются и оставайтесь вместе.
Подробнее здесь: https://stackoverflow.com/questions/791 ... collisions
Мобильная версия