2017-03-29 15 views
0

QtWidgets.QGraphicsEllipseItemQGraphicsSceneに追加すると、モバイルになります。 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_()) 

答えて

1

A QGraphicsItemGroup 1つの項目(すなわち、すべての子供のためのすべてのイベントとジオメトリが一緒にマージされている)として、それ自体とそのすべての子供たちを治療する化合物アイテムの特殊なタイプです。アイテムの移動やコピーを簡単にするために、いくつかの小さなアイテムを1つの大きなアイテムにグループ化したい場合、プレゼンテーションツールでアイテムグループを使用するのが一般的です。

self.polygon内のすべてのPoint(s)は、単一のオブジェクトとして扱われるので、このオブジェクトは可動自体する必要があります:あなたはあなたの「ポイント」は彼らの親QGraphicsItemGroupの内側に移動可能にしたい場合は

self.polygon.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)

です適切な選択肢ではなく、GraphicsRectItemまたはQGraphicsPolygonItemなどを使用できます。

関連する問題