QtWidgets.QGraphicsEllipseItem
をQGraphicsScene
に追加すると、モバイルになります。 QtWidgets.QGraphicsItemGroup
を親として持つように割り当てる場合は、シーンに親を追加してください。これはモバイルです。親をQGraphicsSceneに追加した後でQt子を作成すると、固定されません。
子を追加する前に親をシーンに追加すると、不動です。どうして?
以下は、自己完結型の例です。コードを実行すると、Point
を4つ作成することができます。これらはすべてモバイルであり、その親が5番目のPoint
に追加された後は不動になります。これはQt4のケースではありませんでした。ドキュメントから
from PyQt5.QtWidgets import (QApplication, QGraphicsView,\
QGraphicsScene, QGraphicsItem)
from PyQt5 import QtWidgets, QtGui, QtCore
class Point(QtWidgets.QGraphicsEllipseItem):
def __init__(self, pos):
super(Point, self).__init__(0,0,10,10)
self.setPos(pos)
self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | \
QtWidgets.QGraphicsItem.ItemIsSelectable)
class Graphics(QGraphicsItem):
def __init__(self):
super(Graphics, self).__init__()
self.numPoints = 0
self.polygon = QtWidgets.QGraphicsItemGroup()
def paint(self, painter, option, widget):
pass
def boundingRect(self):
return QtCore.QRectF(0,0,300,300)
def mousePressEvent(self, event):
pos = event.pos()
itemAt = self.scene().itemAt(pos, QtGui.QTransform())
# If nothing is under the mouse, create a new point and accept the event
if not isinstance(itemAt, Point):
# Add the point to the scene and set its parent
pt = Point(pos)
pt.setParentItem(self.polygon)
if pt.scene() is None:
self.scene().addItem(pt)
else:
print "The item was implicitly added to the scene by its parent"
# On the fifth point, add the polygon to the scene
self.numPoints += 1
if self.numPoints == 4:
self.scene().addItem(self.polygon)
event.accept()
super(Graphics, self).mousePressEvent(event)
class MainWindow(QGraphicsView):
def __init__(self):
super(MainWindow, self).__init__()
scene = QGraphicsScene(self)
scene.addItem(Graphics())
scene.setSceneRect(0, 0, 300, 300)
self.setScene(scene)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
sys.exit(app.exec_())