changeset 92:0c4bdbf0aead

improvements?
author windel
date Sat, 15 Dec 2012 23:56:26 +0100
parents 7ad4c66dd092
children f7ec7517cabb
files python/apps/diagrameditor.py python/apps/diagramitems.py
diffstat 2 files changed, 45 insertions(+), 13 deletions(-) [+]
line wrap: on
line diff
--- a/python/apps/diagrameditor.py	Mon Dec 10 18:55:40 2012 +0100
+++ b/python/apps/diagrameditor.py	Sat Dec 15 23:56:26 2012 +0100
@@ -4,7 +4,7 @@
 from PyQt4.QtCore import *
 import sys, json, base64
 
-from diagramitems import Connection, ResizeSelectionHandle, Block, DiagramScene
+from diagramitems import Connection, ResizeSelectionHandle, Block, DiagramScene, CodeBlock
 from icons import newicon, saveicon, loadicon
 
 """
@@ -42,6 +42,12 @@
       self.delShort = QShortcut(QKeySequence.Delete, self)
       self._model = None
       self.treeView = QTreeView()
+      self.treeView.activated.connect(self.itemActivated)
+   def itemActivated(self, idx):
+      b = idx.internalPointer()
+      s = b.scene()
+      s.clearSelection()
+      b.setSelected(True)
    def setDiagram(self, d):
       self.setScene(d)
       self.delShort.activated.connect(d.deleteItems)
@@ -61,7 +67,7 @@
             self.model.filename = QFileDialog.getSaveFileName(self)
          if self.model.filename:
             with open(self.model.filename, 'w') as f:
-               f.write(json.dumps(self.model.Dict))
+               f.write(json.dumps(self.model.Dict, indent=2))
    def load(self):
       filename = QFileDialog.getOpenFileName(self)
       if filename:
@@ -114,7 +120,7 @@
          name = bytes(event.mimeData().data('component/name')).decode()
          pos = self.mapToScene(event.pos())
          s = self.scene()
-         b = Block(s.uniqify(name))
+         b = CodeBlock(s.uniqify(name))
          b.setPos(pos)
          s.addItem(b)
          # TODO: do this in a cleaner way:
@@ -134,7 +140,10 @@
    def __init__(self):
       super(ModelHierarchyModel, self).__init__()
       self.rootDiagram = DiagramScene()
+      self.rootDiagram.changed.connect(self.cha)
       self.filename = None
+   def cha(self, region):
+      print(region)
    def setDict(self, d):
       self.rootDiagram.Dict = d
       self.modelReset.emit()
@@ -171,10 +180,18 @@
    def data(self, index, role):
       if index.isValid() and role == Qt.DisplayRole:
          b = index.internalPointer()
-         return b.name
+         if index.column() == 0:
+            return b.name
+         elif index.column() == 1:
+            return str(type(b))
    def headerData(self, section, orientation, role):
       if orientation == Qt.Horizontal and role == Qt.DisplayRole:
-         return "Element"
+         if section == 0:
+            return "Element"
+         elif section == 1:
+            return "Type"
+         else:
+            return "x"
    def rowCount(self, parent):
       if parent.column() > 0: 
          return 0
@@ -187,7 +204,7 @@
       else:
          return len(self.rootDiagram.blocks)
    def columnCount(self, parent):
-      return 1
+      return 2
 
 class LibraryWidget(QListView):
    def __init__(self):
--- a/python/apps/diagramitems.py	Mon Dec 10 18:55:40 2012 +0100
+++ b/python/apps/diagramitems.py	Sat Dec 15 23:56:26 2012 +0100
@@ -1,3 +1,7 @@
+"""
+ Contains all blocks that can be used to build models.
+"""
+
 from PyQt4.QtGui import *
 from PyQt4.QtCore import *
 
@@ -24,7 +28,7 @@
    return []
 
 class Connection(QGraphicsPathItem):
-   """ Implementation of a connection between blocks """
+   """ A connection between blocks """
    def __init__(self, fromPort=None, toPort=None):
       super(Connection, self).__init__()
       self.pos2 = self.fromPort = self.toPort = None
@@ -187,7 +191,7 @@
       self.block.sizerMoveEvent(self, event.scenePos())
 
 class Block(QGraphicsRectItem):
-   """ Represents a block in the diagram """
+   """ Represents a block in the diagram. """
    def __init__(self, name='Untitled', parent=None):
       super(Block, self).__init__(parent)
       self.selectionHandles = [ResizeSelectionHandle(i, self) for i in range(8)]
@@ -196,6 +200,7 @@
       self.setBrush(QBrush(Qt.lightGray))
       self.setFlags(self.ItemIsSelectable | self.ItemIsMovable | self.ItemSendsScenePositionChanges)
       self.setCursor(QCursor(Qt.PointingHandCursor))
+      self.setAcceptHoverEvents(True)
       self.label = QGraphicsTextItem(name, self)
       self.name = name
       # Create corner for resize:
@@ -244,8 +249,10 @@
       self.name = d['name']
       self.setPos(d['x'], d['y'])
       self.changeSize(d['width'], d['height'])
-      for inp in d['inputs']: self.addInput(InputPort(inp['name'], self))
-      for outp in d['outputs']: self.addOutput(OutputPort(outp['name'], self))
+      for inp in d['inputs']:
+         self.addInput(InputPort(inp['name'], self))
+      for outp in d['outputs']:
+         self.addOutput(OutputPort(outp['name'], self))
    Dict = property(getDict, setDict)
    def addInput(self, i):
       self.inputs.append(i)
@@ -269,10 +276,12 @@
 
       return super(Block, self).itemChange(change, value)
    def hoverEnterEvent(self, event):
-      self.repositionAndShowHandles()
+      if not self.isSelected():
+         self.repositionAndShowHandles()
       super(Block, self).hoverEnterEvent(event)
    def hoverLeaveEvent(self, event):
-      [h.setVisible(False) for h in self.selectionHandles]
+      if not self.isSelected():
+         [h.setVisible(False) for h in self.selectionHandles]
       super(Block, self).hoverLeaveEvent(event)
    def myDelete(self):
       for p in self.inputs + self.outputs:
@@ -330,7 +339,12 @@
       super(CodeBlock, self).__init__(name, parent)
       self.code = ''
    def setDict(self, d):
+      super(CodeBlock, self).setDict(d)
       self.code = d['code']
+   def getDict(self):
+      d = super(CodeBlock, self).getDict()
+      d['code'] = self.code
+      return d
    def gencode(self):
       c = ['def {0}():'.format(self.name)]
       if self.code:
@@ -348,11 +362,12 @@
       self.subModel.Dict = d['submodel']
 
 class DiagramScene(QGraphicsScene):
+   """ A diagram scene consisting of blocks and connections """
    def __init__(self):
       super(DiagramScene, self).__init__()
       self.startedConnection = None
 
-   blocks = property(lambda sel: [i for i in sel.items() if type(i) is Block])
+   blocks = property(lambda sel: [i for i in sel.items() if isinstance(i, Block)])
    connections = property(lambda sel: [i for i in sel.items() if type(i) is Connection])
    def setDict(self, d):
       for block in d['blocks']: