changeset 392:bb4289c84907

Added some sort of drop event test
author Windel Bouwman
date Fri, 16 May 2014 13:05:10 +0200
parents a139da1f44f6
children 6ae782a085e0
files python/other/diagrameditor.py python/other/diagramitems.py test/testdiagrameditor.py
diffstat 3 files changed, 134 insertions(+), 100 deletions(-) [+]
line wrap: on
line diff
--- a/python/other/diagrameditor.py	Fri May 16 12:30:10 2014 +0200
+++ b/python/other/diagrameditor.py	Fri May 16 13:05:10 2014 +0200
@@ -23,11 +23,11 @@
 
 
 def indent(lines):
-   return ['   ' + line for line in lines]
+    return ['   ' + line for line in lines]
 
 
 class ParameterDialog(QtWidgets.QDialog):
-   def __init__(self, block, parent = None):
+    def __init__(self, block, parent = None):
       super(ParameterDialog, self).__init__(parent)
       self.block = block
       self.button = QPushButton('Ok', self)
@@ -39,7 +39,7 @@
       l.addRow('Code:', self.codeEdit)
       l.addWidget(self.button)
       self.button.clicked.connect(self.OK)
-   def OK(self):
+    def OK(self):
       self.block.name = self.nameEdit.text()
       self.block.code = self.codeEdit.toPlainText()
       self.close()
@@ -128,7 +128,7 @@
    def wheelEvent(self, event):
       pos = event.pos()
       posbefore = self.mapToScene(pos)
-      degrees = event.delta() / 8.0
+      degrees = event.angleDelta().y() / 8.0
       sx = (100.0 + degrees) / 100.0
       self.scale(sx, sx)
       event.accept()
@@ -214,7 +214,7 @@
       if index.isValid():
          block = index.internalPointer()
          if block.scene() == self.rootDiagram:
-            return QModelIndex()
+            return QtCore.QModelIndex()
          else:
             print(block)
             outerBlock = block.scene().containingBlock
@@ -354,11 +354,10 @@
       ev.accept()
 
 if __name__ == '__main__':
-   if sys.version_info.major != 3:
-      print('Please use python 3.x')
-      sys.exit(1)
-   app = QtWidgets.QApplication(sys.argv)
-   main = Main()
-   main.show()
-   app.exec_()
-
+    if sys.version_info.major != 3:
+        print('Please use python 3.x')
+        sys.exit(1)
+    app = QtWidgets.QApplication(sys.argv)
+    main = Main()
+    main.show()
+    app.exec_()
--- a/python/other/diagramitems.py	Fri May 16 12:30:10 2014 +0200
+++ b/python/other/diagramitems.py	Fri May 16 13:05:10 2014 +0200
@@ -42,18 +42,22 @@
 class Connection(QtWidgets.QGraphicsPathItem):
    """ A connection between blocks """
    def __init__(self, fromPort=None, toPort=None):
-      super(Connection, self).__init__()
-      self.pos2 = self.fromPort = self.toPort = None
-      self.setFlags(self.ItemIsSelectable | self.ItemClipsToShape)
-      pen = QtGui.QPen(Qt.blue, 2, cap=Qt.RoundCap)
-      self.setPen(pen)
-      self.arrowhead = QtGui.QGraphicsPathItem(self)
-      self.arrowhead.setPath(buildPath([QPointF(0.0, 0.0), QPointF(-6.0, 10.0), QPointF(6.0, 10.0), QPointF(0.0, 0.0)]))
-      self.arrowhead.setPen(pen)
-      self.arrowhead.setBrush(QtGui.QBrush(pen.color()))
-      self.vias = []
-      self.setFromPort(fromPort)
-      self.setToPort(toPort)
+        super(Connection, self).__init__()
+        self.pos2 = self.fromPort = self.toPort = None
+        self.setFlags(self.ItemIsSelectable | self.ItemClipsToShape)
+        pen = QtGui.QPen(Qt.blue, 2, cap=Qt.RoundCap)
+        self.setPen(pen)
+        self.arrowhead = QtWidgets.QGraphicsPathItem(self)
+        self.arrowhead.setPath(buildPath([QtCore.QPointF(0.0, 0.0),
+                                        QtCore.QPointF(-6.0, 10.0),
+                                        QtCore.QPointF(6.0, 10.0),
+                                        QtCore.QPointF(0.0, 0.0)]))
+        self.arrowhead.setPen(pen)
+        self.arrowhead.setBrush(QtGui.QBrush(pen.color()))
+        self.vias = []
+        self.setFromPort(fromPort)
+        self.setToPort(toPort)
+
    def getDict(self):
       d = {}
       d['fromBlock'] = self.fromPort.block.name
@@ -91,14 +95,17 @@
          return self.fromPort.scenePos()
    def setBeginPos(self, pos1): self.updateLineStukken()
    def setEndPos(self, endpos):
-      self.pos2 = endpos
-      self.updateLineStukken()
+        self.pos2 = endpos
+        self.updateLineStukken()
    def itemChange(self, change, value):
-      if change == self.ItemSelectedHasChanged:
-         for via in self.vias:
-            via.setVisible(value)
-      return super(Connection, self).itemChange(change, value)
-   def shape(self): return self.myshape
+        if change == self.ItemSelectedHasChanged:
+            for via in self.vias:
+                via.setVisible(value)
+        return super(Connection, self).itemChange(change, value)
+
+   def shape(self):
+        return self.myshape
+
    def updateLineStukken(self):
       """
          This algorithm determines the optimal routing of all signals.
@@ -109,13 +116,13 @@
       if pos1 is None or pos2 is None:
          return
       scene = self.scene()
-      vias = [pos1 + QPointF(20, 0)] + self.vias + [pos2 + QPointF(-20, 0)]
+      vias = [pos1 + QtCore.QPointF(20, 0)] + self.vias + [pos2 + QtCore.QPointF(-20, 0)]
       if scene:
-         litem = QtGui.QGraphicsLineItem()
+         litem = QtWidgets.QGraphicsLineItem()
          litem.setFlags(self.ItemIsSelectable)
          scene.addItem(litem)
          for p1, p2 in zip(vias[:-1], vias[1:]):
-            line = QLineF(p1, p2)
+            line = QtCore.QLineF(p1, p2)
             litem.setLine(line)
             citems = scene.collidingItems(litem)
             citems = [i for i in citems if type(i) is Block]
@@ -135,7 +142,7 @@
    """ Represents a port to a subsystem """
    def __init__(self, name, block):
       super(PortItem, self).__init__(block)
-      self.textItem = QtGui.QGraphicsTextItem(self)
+      self.textItem = QtWidgets.QGraphicsTextItem(self)
       self.connection = None
       self.block = block
       self.setCursor(QtGui.QCursor(Qt.CrossCursor))
@@ -160,17 +167,22 @@
          return value
       return super(PortItem, self).itemChange(change, value)
 
+
 class OutputPort(PortItem):
-   def __init__(self, name, block, d=10.0):
-      super(OutputPort, self).__init__(name, block)
-      self.setPath(buildPath([QPointF(0.0, -d), QPointF(d, 0), QPointF(0.0, d)]))
-   def mousePressEvent(self, event):
-      self.scene().startConnection(self)
+    def __init__(self, name, block, d=10.0):
+        super().__init__(name, block)
+        self.setPath(buildPath([QtCore.QPointF(0.0, -d), QtCore.QPointF(d, 0),
+                                QtCore.QPointF(0.0, d)]))
+
+    def mousePressEvent(self, event):
+        self.scene().startConnection(self)
+
 
 class InputPort(PortItem):
-   def __init__(self, name, block, d=10.0):
-      super(InputPort, self).__init__(name, block)
-      self.setPath(buildPath([QPointF(-d, -d), QPointF(0, 0), QPointF(-d, d)]))
+    def __init__(self, name, block, d=10.0):
+        super().__init__(name, block)
+        self.setPath(buildPath([QtCore.QPointF(-d, -d), QtCore.QPointF(0, 0),
+                                QtCore.QPointF(-d, d)]))
 
 class Handle(QtWidgets.QGraphicsEllipseItem):
    """ A handle that can be moved by the mouse """
@@ -186,21 +198,24 @@
       p = self.mapToParent(event.pos())
       self.setPos(p)
 
+
 class ResizeSelectionHandle(Handle):
-   def __init__(self, position, block):
-      super(ResizeSelectionHandle, self).__init__(dx=12, parent=block)
-      self.position = position
-      self.block = block
-      if position in [Position.TOP_LEFT, Position.BOTTOM_RIGHT]:
-         self.setCursor(QtGui.QCursor(Qt.SizeFDiagCursor))
-      elif position in [Position.TOP_RIGHT, Position.BOTTOM_LEFT]:
-         self.setCursor(QCursor(Qt.SizeBDiagCursor))
-      elif position in [Position.TOP, Position.BOTTOM]:
-         self.setCursor(QCursor(Qt.SizeVerCursor))
-      elif position in [Position.LEFT, Position.RIGHT]:
-         self.setCursor(QtGui.QCursor(Qt.SizeHorCursor))
-   def mouseMoveEvent(self, event):
-      self.block.sizerMoveEvent(self, event.scenePos())
+    def __init__(self, position, block):
+        super(ResizeSelectionHandle, self).__init__(dx=12, parent=block)
+        self.position = position
+        self.block = block
+        if position in [Position.TOP_LEFT, Position.BOTTOM_RIGHT]:
+            self.setCursor(QtGui.QCursor(Qt.SizeFDiagCursor))
+        elif position in [Position.TOP_RIGHT, Position.BOTTOM_LEFT]:
+            self.setCursor(QtGui.QCursor(Qt.SizeBDiagCursor))
+        elif position in [Position.TOP, Position.BOTTOM]:
+            self.setCursor(QtGui.QCursor(Qt.SizeVerCursor))
+        elif position in [Position.LEFT, Position.RIGHT]:
+            self.setCursor(QtGui.QCursor(Qt.SizeHorCursor))
+
+    def mouseMoveEvent(self, event):
+        self.block.sizerMoveEvent(self, event.scenePos())
+
 
 class Block(QtWidgets.QGraphicsRectItem):
    """ Represents a block in the diagram. """
@@ -230,17 +245,23 @@
       self.inputs = []
       self.outputs = []
       self.changeSize(2,2)
+
    def editParameters(self):
-      pd = ParameterDialog(self, self.window())
-      pd.exec_()
+        pd = ParameterDialog(self, self.window())
+        pd.exec_()
+
    def newInputPort(self):
-      names = [i.name for i in self.inputs + self.outputs]
-      self.addInput(InputPort(uniqify('in', names), self))
+        names = [i.name for i in self.inputs + self.outputs]
+        self.addInput(InputPort(uniqify('in', names), self))
+
    def newOutputPort(self):
-      names = [i.name for i in self.inputs + self.outputs]
-      self.addOutput(OutputPort(uniqify('out', names), self))
+        names = [i.name for i in self.inputs + self.outputs]
+        self.addOutput(OutputPort(uniqify('out', names), self))
+
    def setName(self, name): self.label.setPlainText(name)
+
    def getName(self): return self.label.toPlainText()
+
    name = property(getName, setName)
    def getDict(self):
       d = {'x': self.scenePos().x(), 'y': self.scenePos().y()}
@@ -259,14 +280,17 @@
       for outp in d['outputs']:
          self.addOutput(OutputPort(outp['name'], self))
    Dict = property(getDict, setDict)
+
    def addInput(self, i):
-      self.inputs.append(i)
-      self.updateSize()
+        self.inputs.append(i)
+        self.updateSize()
+
    def addOutput(self, o):
-      self.outputs.append(o)
-      self.updateSize()
+        self.outputs.append(o)
+        self.updateSize()
+
    def contextMenuEvent(self, event):
-      menu = QMenu()
+      menu = QtWidgets.QMenu()
       pa = menu.addAction('Parameters')
       pa.triggered.connect(self.editParameters)
       menu.exec_(event.screenPos())
@@ -281,13 +305,13 @@
 
       return super(Block, self).itemChange(change, value)
    def hoverEnterEvent(self, event):
-      if not self.isSelected():
-         self.repositionAndShowHandles()
-      super(Block, self).hoverEnterEvent(event)
+        if not self.isSelected():
+            self.repositionAndShowHandles()
+        super().hoverEnterEvent(event)
    def hoverLeaveEvent(self, event):
-      if not self.isSelected():
-         [h.setVisible(False) for h in self.selectionHandles]
-      super(Block, self).hoverLeaveEvent(event)
+        if not self.isSelected():
+            [h.setVisible(False) for h in self.selectionHandles]
+        super().hoverLeaveEvent(event)
    def myDelete(self):
       for p in self.inputs + self.outputs:
          if p.connection: p.connection.myDelete()
@@ -328,18 +352,18 @@
       for outp, y in zip(self.outputs, equalSpace(len(self.outputs), h)):
          outp.setPos(w, y)
    def setCenterAndSize(self, center, size):
-      self.changeSize(size.width(), size.height())
-      p = QPointF(size.width(), size.height())
-      self.setPos(center - p / 2)
+        self.changeSize(size.width(), size.height())
+        p = QtCore.QPointF(size.width(), size.height())
+        self.setPos(center - p / 2)
    def changeSize(self, w, h):
-      minw = 150
-      minh = 50
-      h = minh if h < minh else h
-      w = minw if w < minw else w
-      self.setRect(0.0, 0.0, w, h)
-      rect = self.label.boundingRect()
-      self.label.setPos((w - rect.width()) / 2, (h - rect.height()) / 2)
-      self.updateSize()
+        minw = 150
+        minh = 50
+        h = minh if h < minh else h
+        w = minw if w < minw else w
+        self.setRect(0.0, 0.0, w, h)
+        rect = self.label.boundingRect()
+        self.label.setPos((w - rect.width()) / 2, (h - rect.height()) / 2)
+        self.updateSize()
 
 
 class CodeBlock(Block):
@@ -367,22 +391,22 @@
 
 class DiagramBlock(Block):
     def __init__(self, name='Untitled', parent=None):
-      super(DiagramBlock, self).__init__(name, parent)
-      self.subModel = DiagramScene()
-      self.subModel.containingBlock = self
+        super(DiagramBlock, self).__init__(name, parent)
+        self.subModel = DiagramScene()
+        self.subModel.containingBlock = self
 
     def setDict(self, d):
         self.subModel.Dict = d['submodel']
 
     def mouseDoubleClickEvent(self, event):
-      # descent into child diagram
-      #self.editParameters()
-      print('descent')
-      scene = self.scene()
-      if scene:
-         for view in scene.views():
-            view.diagram = self.subModel
-            view.zoomAll()
+        # descent into child diagram
+        #self.editParameters()
+        print('descent')
+        scene = self.scene()
+        if scene:
+            for view in scene.views():
+                view.diagram = self.subModel
+                view.zoomAll()
 
 
 class DiagramScene(QtWidgets.QGraphicsScene):
--- a/test/testdiagrameditor.py	Fri May 16 12:30:10 2014 +0200
+++ b/test/testdiagrameditor.py	Fri May 16 13:05:10 2014 +0200
@@ -9,9 +9,10 @@
     sys.path.insert(0, otherpath)
     import diagrameditor
 
-    from PyQt5.QtWidgets import QApplication
+    from PyQt5.QtWidgets import QApplication, QGraphicsItem
     from PyQt5.QtTest import QTest
-    from PyQt5.QtCore import Qt, QTimer
+    from PyQt5.QtCore import Qt, QTimer, QMimeData, QPointF
+    from PyQt5.QtGui import QDropEvent
     skip_it = False
 
     # When creating an app per testcase, this fails horribly..
@@ -47,10 +48,21 @@
         print(editor, type(editor))
         QTest.mouseMove(editor)
         QTest.mouseRelease(editor, Qt.LeftButton)
+        mimedata = QMimeData()
+        mimedata.setData('component/name', 'Block:blk'.encode('ascii'))
+        de = QDropEvent(QPointF(10, 10), Qt.CopyAction, mimedata,
+                        Qt.LeftButton,
+                        Qt.NoModifier)
+        editor.dropEvent(de)
+
+    def resizePlacedItem(self):
+        i = self.main.findChild(QGraphicsItem, "sizer_top_right")
+        print(i)
 
     def testScenario1(self):
         self.cmdNewModel()
         self.dragItemIntoScene()
+        self.resizePlacedItem()
 
     def testB(self):
         print('b')
@@ -58,4 +70,3 @@
 
 if __name__ == '__main__':
     unittest.main()
-