Ejemplo n.º 1
0
 def __init__(self, *args):
     self.seleccionado = False
     self.velocity = random.randint(1, 10)
     QGraphicsPixmapItem.__init__(self, *args)
     self.setPixmap(
         QPixmap("sprites/" + str(random.randint(1, 45)) + ".png"))
     self.setTransformOriginPoint(self.boundingRect().width() / 2.0,
                                  self.boundingRect().height() / 2.0)
     self.setZValue(10)
     ##menu contextual
     self.menu = QMenu()
     self.Actions = []  #arreglo de acciones
     self.Actions.append(self.menu.addAction("Seguir"))
     self.Actions.append(self.menu.addAction("Editar"))
     self.Actions.append(self.menu.addAction("girar clockwise"))
     self.Actions.append(self.menu.addAction("girar anti-clockwise"))
     self.Actions.append(self.menu.addAction("Colisiones"))
     self.Actions.append(self.menu.addAction("Duplicar"))
     self.Actions.append(self.menu.addAction("Eliminar"))
     self.menu.triggered[QAction].connect(self.test)
     ##offset para el arrastre
     self.offset = QPointF(0, 0)
     ##poligono de vision
     poligono = QPolygonF()
     poligono.append(QPointF(-1, 10))
     poligono.append(QPointF(-1, 20))
     poligono.append(QPointF(-30, 40))
     poligono.append(QPointF(-40, 15))
     poligono.append(QPointF(-30, -10))
     self.vision = QGraphicsPolygonItem(poligono, self, self.scene())
     self.vision.setBrush(QColor(255, 255, 0, 100))
     self.vision.setPen(QColor(255, 255, 0))
Ejemplo n.º 2
0
    def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color):
        OWPlotItem.__init__(self)
        self.outer_box = QGraphicsPolygonItem(self)
        self.inner_box = QGraphicsPolygonItem(self)

        self.i = i
        self.mu1 = mu1
        self.mu2 = mu2
        self.sigma1 = sigma1
        self.sigma2 = sigma2
        self.phi = phi

        self.twosigmapolygon = QPolygonF([
            QPointF(i, mu1 - sigma1),
            QPointF(i, mu1 + sigma1),
            QPointF(i + 1, mu2 + sigma2),
            QPointF(i + 1, mu2 - sigma2),
            QPointF(i, mu1 - sigma1)
        ])

        self.sigmapolygon = QPolygonF([
            QPointF(i, mu1 - .5 * sigma1),
            QPointF(i, mu1 + .5 * sigma1),
            QPointF(i + 1, mu2 + .5 * sigma2),
            QPointF(i + 1, mu2 - .5 * sigma2),
            QPointF(i, mu1 - .5 * sigma1)
        ])

        if isinstance(color, tuple):
            color = QColor(*color)
        color.setAlphaF(.3)
        self.outer_box.setBrush(color)
        self.outer_box.setPen(QColor(0, 0, 0, 0))
        self.inner_box.setBrush(color)
        self.inner_box.setPen(color)
Ejemplo n.º 3
0
    def _finish_add_area(self):    
        poligon = QPolygonF( self.current_op_stat['points'])        
        
        pol = QGraphicsPolygonItem(poligon)
        pol.setToolTip(self.current_op_stat['name'])
        pol.setPen(QPen(Qt.black, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))        
        
        HMItem.type(pol,HMItem.MAP_AREA)
        HMItem.select(pol,False)
        HMItem.name(pol,self.current_op_stat['name'])
        HMItem.level(pol, self.home_map_scene.current_level)
        
        pol.setVisible(True)
        pol.setZValue(1)
        
        

        self.home_map_scene.addItem(pol)        
        print "flags %x" % pol.flags()
        
        
        it_remove = QGraphicsPolygonItem()
        HMItem.module( it_remove, self.__class__.__name__)
        HMItem.type(it_remove,HMItem.OUTLINE_POINT)        
        self.home_map_scene.remove_by_item(it_remove)
        self.current_op = ''
        self.current_op_stat = None
Ejemplo n.º 4
0
 def __init__(self, parent, fromView, toView, distributedObjects):
     """ Constructor
     @param parent                parent for the QGraphicsPolygonItem-Constructor
     @param fromView              datagraph.htmlvariableview.HtmlVariableView, starting point of the Pointer
     @param toView                datagraph.htmlvariableview.HtmlVariableView, end point of the Pointer
     @param distributedObjects    distributedobjects.DistributedObjects, the DistributedObjects-Instance
     fromView and toView are QGraphicsWebViews
     """
     QGraphicsPolygonItem.__init__(self, parent)
     self.fromView = fromView
     fromView.addOutgoingPointer(self)
     self.toView = toView
     toView.addIncomingPointer(self)
     self.distributedObjects = distributedObjects
     self.setBrush( QBrush( self.bgcolor  ) )
     self.setPen( QPen(self.fgcolor,1) )
     QObject.connect(self.fromView, SIGNAL('geometryChanged()'), self.render)
     QObject.connect(self.toView, SIGNAL('geometryChanged()'), self.render)
     QObject.connect(self.fromView, SIGNAL('xChanged()'), self.render)
     QObject.connect(self.fromView, SIGNAL('yChanged()'), self.render)
     QObject.connect(self.toView, SIGNAL('xChanged()'), self.render)
     QObject.connect(self.toView, SIGNAL('yChanged()'), self.render)
     QObject.connect(self.fromView, SIGNAL('deleting()'), self.delete)
     QObject.connect(self.toView, SIGNAL('deleting()'), self.delete)
     
     self.render()
Ejemplo n.º 5
0
    def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color):
        OWPlotItem.__init__(self)
        self.outer_box = QGraphicsPolygonItem(self)
        self.inner_box = QGraphicsPolygonItem(self)

        self.i = i
        self.mu1 = mu1
        self.mu2 = mu2
        self.sigma1 = sigma1
        self.sigma2 = sigma2
        self.phi = phi

        self.twosigmapolygon = QPolygonF([
            QPointF(i, mu1 - sigma1), QPointF(i, mu1 + sigma1),
            QPointF(i + 1, mu2 + sigma2), QPointF(i + 1, mu2 - sigma2),
            QPointF(i, mu1 - sigma1)
        ])

        self.sigmapolygon = QPolygonF([
            QPointF(i, mu1 - .5 * sigma1), QPointF(i, mu1 + .5 * sigma1),
            QPointF(i + 1, mu2 + .5 * sigma2), QPointF(i + 1, mu2 - .5 * sigma2),
            QPointF(i, mu1 - .5 * sigma1)
        ])

        if isinstance(color, tuple):
            color = QColor(*color)
        color.setAlphaF(.3)
        self.outer_box.setBrush(color)
        self.outer_box.setPen(QColor(0, 0, 0, 0))
        self.inner_box.setBrush(color)
        self.inner_box.setPen(color)
Ejemplo n.º 6
0
 def __init__(self, parent):
     points = QPolygonF()
     self._mediator = ArrowMediator()
     for poly in (QPointF(7,0), QPointF(-7,7), QPointF(-5,2), QPointF(-11,2),
                  QPointF(-11,-2), QPointF(-5,-2), QPointF(-7,-7)):
         points.append(poly)
     QGraphicsPolygonItem.__init__(self, points, parent)
     self.setPen(Qt.darkCyan)
     self.setBrush(Qt.cyan)
Ejemplo n.º 7
0
    def _add_selection(self, item):
        """Add selection rooted at item
        """
        outline = self._selection_poly(item)
        selection_item = QGraphicsPolygonItem(self)
        #         selection_item = QGraphicsPathItem(self)
        selection_item.setPos(self.contentsRect().topLeft())
        #         selection_item.setPen(QPen(Qt.NoPen))
        selection_item.setPen(make_pen(width=1, cosmetic=True))

        transform = self._itemgroup.transform()
        path = transform.map(outline)
        margin = 4
        if item.node.is_leaf:
            path = QPolygonF(path.boundingRect().adjusted(
                -margin, -margin, margin, margin))
        else:
            pass
#             ppath = QPainterPath()
#             ppath.addPolygon(path)
#             path = path_outline(ppath, width=margin).toFillPolygon()

        selection_item.setPolygon(path)
        #         selection_item.setPath(path_outline(path, width=4))
        selection_item.unscaled_path = outline
        self._selection[item] = selection_item
        item.setSelected(True)
Ejemplo n.º 8
0
 def __init__(self,
              pen=QPen(Qt.black),
              brush=QBrush(Qt.white),
              xData=[],
              yData=[],
              tooltip=None):
     OWCurve.__init__(self, xData, yData, tooltip=tooltip)
     self._data_polygon = self.polygon_from_data(xData, yData)
     self._polygon_item = QGraphicsPolygonItem(self)
     self.set_pen(pen)
     self.set_brush(brush)
    def _add_selection(self, item):
        """Add selection rooted at item
        """
        outline = self._selection_poly(item)
        selection_item = QGraphicsPolygonItem(self)
#         selection_item = QGraphicsPathItem(self)
        selection_item.setPos(self.contentsRect().topLeft())
#         selection_item.setPen(QPen(Qt.NoPen))
        selection_item.setPen(make_pen(width=1, cosmetic=True))

        transform = self._itemgroup.transform()
        path = transform.map(outline)
        margin = 4
        if item.node.is_leaf:
            path = QPolygonF(path.boundingRect()
                             .adjusted(-margin, -margin, margin, margin))
        else:
            pass
#             ppath = QPainterPath()
#             ppath.addPolygon(path)
#             path = path_outline(ppath, width=margin).toFillPolygon()

        selection_item.setPolygon(path)
#         selection_item.setPath(path_outline(path, width=4))
        selection_item.unscaled_path = outline
        self._selection[item] = selection_item
        item.setSelected(True)
Ejemplo n.º 10
0
	def __init__(self, poly = None, dim = None):
		if not poly:
			if not dim:
				raise ValueError("need to set bounding rect!")
			else:
				poly = []
				for i in range(10):
					poly.append(planar.Point(
						random.randint(dim.left(),dim.right()),
						random.randint(dim.top(),dim.bottom())))
				poly = planar.Polygon.convex_hull(poly)
				poly = QPolygonF([QPointF(p.x,p.y) for p in poly])
			
		QGraphicsPolygonItem.__init__(self, poly)
		self.setConnectors([(0,random.random()),(len(poly)//2,random.random())])
Ejemplo n.º 11
0
 def __init__(self, *args):
       self.seleccionado = False
       self.velocity = random.randint(1,10)
       QGraphicsPixmapItem.__init__(self, *args)
       self.setPixmap(QPixmap("sprites/"+str(random.randint(1,45))+".png"))
       self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0)
       self.setZValue(10)
       ##menu contextual
       self.menu = QMenu()
       self.Actions =[] #arreglo de acciones 
       self.Actions.append( self.menu.addAction("Seguir") )
       self.Actions.append( self.menu.addAction("Editar") )
       self.Actions.append( self.menu.addAction("girar clockwise") )
       self.Actions.append( self.menu.addAction("girar anti-clockwise") )
       self.Actions.append( self.menu.addAction("Colisiones") )
       self.Actions.append( self.menu.addAction("Duplicar") )
       self.Actions.append( self.menu.addAction("Eliminar") )
       self.menu.triggered[QAction].connect(self.test)
       ##offset para el arrastre
       self.offset= QPointF(0,0)
       ##poligono de vision
       poligono = QPolygonF()
       poligono.append(QPointF(-1,10))
       poligono.append(QPointF(-1,20))
       poligono.append(QPointF(-30,40))
       poligono.append(QPointF(-40,15))
       poligono.append(QPointF(-30,-10))
       self.vision = QGraphicsPolygonItem(poligono,self,self.scene())
       self.vision.setBrush(QColor(255, 255, 0,100))
       self.vision.setPen(QColor(255, 255, 0))
Ejemplo n.º 12
0
    def __init__(self, width, height, label, color='#0000FF'):

        self.pol = QPolygonF()

        self.pol = QPolygonF()
        self.pol.append(QPointF(width / 2.0, 0))
        self.pol.append(QPointF(width, height / 2.0))
        self.pol.append(QPointF(width / 2.0, height))
        self.pol.append(QPointF(0, height / 2.0))
        self.pol.append(QPointF(width / 2.0, 0))

        self.label = label
        QGraphicsPolygonItem.__init__(self, self.pol)

        self.setBrush(QBrush(QColor(color)))
        self.setPen(QPen(QColor(color)))
Ejemplo n.º 13
0
	def paint(self, painter, option, widget = None):
		QGraphicsPolygonItem.paint(self, painter, option, widget)
		pen = QPen(QColor("yellow"))
		pen.setWidth(10)
		painter.setPen(pen)
		painter.drawPoint(self.entrance())

		pen.setColor(QColor("magenta"))
		painter.setPen(pen)
		painter.drawPoint(self.exit())
		for c in self.connectors[2:]:
			painter.drawPoint(c)

		pen.setColor(QColor(0,255,255))
		pen.setWidth(2)
		painter.setPen(pen)
		painter.drawEllipse(self.cog(), 5, 5)
Ejemplo n.º 14
0
class PolygonCurve(OWCurve):
    """
        A plot item that shows a filled or empty polygon.

        :param pen: The pen used to draw the polygon's outline
        :type pen: :obj:`.QPen`

        :param brush: The brush used to paint the polygon's inside
        :type brush: :obj:`.QBrush`

        :param xData: The list of x coordinates
        :type xData: list of float

        :param yData: The list of y coordinates
        :type yData: list of float

        :param tooltip: The tool tip shown when hovering over this curve
        :type tooltip: str
    """
    def __init__(self,
                 pen=QPen(Qt.black),
                 brush=QBrush(Qt.white),
                 xData=[],
                 yData=[],
                 tooltip=None):
        OWCurve.__init__(self, xData, yData, tooltip=tooltip)
        self._data_polygon = self.polygon_from_data(xData, yData)
        self._polygon_item = QGraphicsPolygonItem(self)
        self.set_pen(pen)
        self.set_brush(brush)

    def update_properties(self):
        self._polygon_item.setPolygon(self.graph_transform().map(
            self._data_polygon))
        self._polygon_item.setPen(self.pen())
        self._polygon_item.setBrush(self.brush())

    @staticmethod
    def polygon_from_data(xData, yData):
        """
            Creates a polygon from a list of x and y coordinates.

            :returns: A polygon with point corresponding to ``xData`` and ``yData``.
            :rtype: QPolygonF
        """
        if xData and yData:
            n = min(len(xData), len(yData))
            p = QPolygonF(n + 1)
            for i in range(n):
                p[i] = QPointF(xData[i], yData[i])
            p[n] = QPointF(xData[0], yData[0])
            return p
        else:
            return QPolygonF()

    def set_data(self, xData, yData):
        self._data_polygon = self.polygon_from_data(xData, yData)
        OWCurve.set_data(self, xData, yData)
Ejemplo n.º 15
0
class PolygonCurve(OWCurve):
    """
        A plot item that shows a filled or empty polygon.

        :param pen: The pen used to draw the polygon's outline
        :type pen: :obj:`.QPen`

        :param brush: The brush used to paint the polygon's inside
        :type brush: :obj:`.QBrush`

        :param xData: The list of x coordinates
        :type xData: list of float

        :param yData: The list of y coordinates
        :type yData: list of float

        :param tooltip: The tool tip shown when hovering over this curve
        :type tooltip: str
    """

    def __init__(self, pen=QPen(Qt.black), brush=QBrush(Qt.white), xData=[], yData=[], tooltip=None):
        OWCurve.__init__(self, xData, yData, tooltip=tooltip)
        self._data_polygon = self.polygon_from_data(xData, yData)
        self._polygon_item = QGraphicsPolygonItem(self)
        self.set_pen(pen)
        self.set_brush(brush)

    def update_properties(self):
        self._polygon_item.setPolygon(self.graph_transform().map(self._data_polygon))
        self._polygon_item.setPen(self.pen())
        self._polygon_item.setBrush(self.brush())

    @staticmethod
    def polygon_from_data(xData, yData):
        """
            Creates a polygon from a list of x and y coordinates.

            :returns: A polygon with point corresponding to ``xData`` and ``yData``.
            :rtype: QPolygonF
        """
        if xData and yData:
            n = min(len(xData), len(yData))
            p = QPolygonF(n + 1)
            for i in range(n):
                p[i] = QPointF(xData[i], yData[i])
            p[n] = QPointF(xData[0], yData[0])
            return p
        else:
            return QPolygonF()

    def set_data(self, xData, yData):
        self._data_polygon = self.polygon_from_data(xData, yData)
        OWCurve.set_data(self, xData, yData)
Ejemplo n.º 16
0
class ParallelCoordinatePolygon(OWPlotItem):
    def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color):
        OWPlotItem.__init__(self)
        self.outer_box = QGraphicsPolygonItem(self)
        self.inner_box = QGraphicsPolygonItem(self)

        self.i = i
        self.mu1 = mu1
        self.mu2 = mu2
        self.sigma1 = sigma1
        self.sigma2 = sigma2
        self.phi = phi

        self.twosigmapolygon = QPolygonF([
            QPointF(i, mu1 - sigma1), QPointF(i, mu1 + sigma1),
            QPointF(i + 1, mu2 + sigma2), QPointF(i + 1, mu2 - sigma2),
            QPointF(i, mu1 - sigma1)
        ])

        self.sigmapolygon = QPolygonF([
            QPointF(i, mu1 - .5 * sigma1), QPointF(i, mu1 + .5 * sigma1),
            QPointF(i + 1, mu2 + .5 * sigma2), QPointF(i + 1, mu2 - .5 * sigma2),
            QPointF(i, mu1 - .5 * sigma1)
        ])

        if isinstance(color, tuple):
            color = QColor(*color)
        color.setAlphaF(.3)
        self.outer_box.setBrush(color)
        self.outer_box.setPen(QColor(0, 0, 0, 0))
        self.inner_box.setBrush(color)
        self.inner_box.setPen(color)

    def update_properties(self):
        self.outer_box.setPolygon(self.graph_transform().map(self.twosigmapolygon))
        self.inner_box.setPolygon(self.graph_transform().map(self.sigmapolygon))
Ejemplo n.º 17
0
 def __init__(self, pen=QPen(Qt.black), brush=QBrush(Qt.white), xData=[], yData=[], tooltip=None):
     OWCurve.__init__(self, xData, yData, tooltip=tooltip)
     self._data_polygon = self.polygon_from_data(xData, yData)
     self._polygon_item = QGraphicsPolygonItem(self)
     self.set_pen(pen)
     self.set_brush(brush)
Ejemplo n.º 18
0
class auto(QGraphicsPixmapItem):
      def __init__(self, *args):
            self.seleccionado = False
            self.velocity = random.randint(1,10)
            QGraphicsPixmapItem.__init__(self, *args)
            self.setPixmap(QPixmap("sprites/"+str(random.randint(1,45))+".png"))
            self.setTransformOriginPoint(self.boundingRect().width()/2.0,self.boundingRect().height()/2.0)
            self.setZValue(10)
            ##menu contextual
            self.menu = QMenu()
            self.Actions =[] #arreglo de acciones 
            self.Actions.append( self.menu.addAction("Seguir") )
            self.Actions.append( self.menu.addAction("Editar") )
            self.Actions.append( self.menu.addAction("girar clockwise") )
            self.Actions.append( self.menu.addAction("girar anti-clockwise") )
            self.Actions.append( self.menu.addAction("Colisiones") )
            self.Actions.append( self.menu.addAction("Duplicar") )
            self.Actions.append( self.menu.addAction("Eliminar") )
            self.menu.triggered[QAction].connect(self.test)
            ##offset para el arrastre
            self.offset= QPointF(0,0)
            ##poligono de vision
            poligono = QPolygonF()
            poligono.append(QPointF(-1,10))
            poligono.append(QPointF(-1,20))
            poligono.append(QPointF(-30,40))
            poligono.append(QPointF(-40,15))
            poligono.append(QPointF(-30,-10))
            self.vision = QGraphicsPolygonItem(poligono,self,self.scene())
            self.vision.setBrush(QColor(255, 255, 0,100))
            self.vision.setPen(QColor(255, 255, 0))
      def info(self):
          return "Velocidad "+ str(self.velocity)+" posicion "+ str(self.pos())[20:]+"\n"
      def test(self,act):
            print act.text()
            if act.text()=="girar clockwise":
                  self.setRotation(self.rotation()-45)
            if act.text()=="girar anti-clockwise":
                  self.setRotation(self.rotation()+45)
            if act.text()=="Colisiones":
                  print "colisiones con",self.collidingItems(1),self.vision.collidingItems(1)
            if act.text()=="Duplicar":
                  self.scene().addItem(auto())
            if act.text()=="Eliminar":
                  self.scene().removeItem(self)
      def contextMenuEvent(self,event):
            self.menu.popup(event.screenPos())
      def mousePressEvent(self, event):
            p = event.pos()
            self.offset= QPointF(p.x()*1.0,p.y()*1.0)
            self.seleccionado = not self.seleccionado
      def mouseMoveEvent(self, event):
            self.setPos(event.scenePos()-self.offset)
      def avanza(self):
          if self.velocity !=0:
              """print velocity
              print "current pos (%f,%f)"%(self.pos().x(),self.pos().y())
              print "angle %f "%(self.rotation())"""
              radians = self.rotation()*0.0174532925
              """ print "angle rad %f "%(radians)"""
              nx = 1.0*self.velocity*cos(radians)
              ny = 1.0*self.velocity*sin(radians)
              """ print "avanzara a (%f,%f)"%(nx,ny) """
              self.setPos(self.pos().x()-nx,self.pos().y()-ny)
              """for i in self.collidingItems():
Ejemplo n.º 19
0
    def mouseDoubleClickEvent(self, mouseEvent):
        QGraphicsPolygonItem.mouseDoubleClickEvent(self, mouseEvent)

        self.toggleContentVisibility()
        self.updateGeometry()
Ejemplo n.º 20
0
    def mouseDoubleClickEvent(self, mouseEvent):
        QGraphicsPolygonItem.mouseDoubleClickEvent(self, mouseEvent)

        self.toggleContentVisibility()
        self.updateGeometry()
Ejemplo n.º 21
0
 def hoverLeaveEvent(self, mouseEvent):
     QGraphicsPolygonItem.hoverLeaveEvent(self, mouseEvent)
     self.toggleHighlight()
Ejemplo n.º 22
0
def polygon_name_face(node, *args, **kwargs):
    """create a wedge shaped face in the style of ARB

    Args:
    width (int): size in pixels for the width of the wedge
    height (int): size in pixels for the height of the wedge
    width_percent (float): change the angle of the point of the wedge.
    This must be a number between 0 and 1

    Returns:
    QGraphicsRectItem: The Qt graphics item of the polygon
    """

    n_leaves = len(node.get_leaves())
    closest_leaf_dist = node.get_closest_leaf()[1]
    farthest_leaf_dist = node.get_farthest_leaf()[1]

    base_height = 30
    width = 60
    height = math.log(n_leaves, 2) + base_height

    width_percent = closest_leaf_dist / farthest_leaf_dist

    #print(width, height, width_percent)

    points = [
    (0.0, 0.0), # top left point
    (width, 0.0), # top right point
    (width * width_percent, height), # bottom right point
    (0.0, height), # bottom left point
    (0.0, 0.0) # back to the beginning
    ]
    shape = QPolygonF()
    for i in points:
        shape << QtCore.QPointF(*i)

    ## Creates a main master Item that will contain all other elements
    ## Items can be standard QGraphicsItem
    masterItem = QGraphicsRectItem(0, 0, width, height)

    # Keep a link within the item to access node info
    masterItem.node = node

    # I dont want a border around the masterItem
    masterItem.setPen(QPen(QtCore.Qt.NoPen))

    polygon = QGraphicsPolygonItem(shape, masterItem)
    # Make the wedge grey in color
    polygon.setBrush(QBrush(QColor( '#D3D3D3')))

    # Print the name of the node
    # Center text according to masterItem size
    center = masterItem.boundingRect().center()

    text = QGraphicsSimpleTextItem(node.name)
    text.setParentItem(polygon)

    tw = text.boundingRect().width()
    th = text.boundingRect().height()
    text.setPos(center.x() + tw/2, center.y() - th/2)

    # this is a hack to prevent the name being printed twice
    # we set the node name to blank after we write it with the QGraphicsSimpleTextItem
    # it must be set to a blank string for it not to be printed later
    node.name = ''


    # print the number of collapsed leaves in the polygon
    leaves_count_text = QGraphicsSimpleTextItem('('+str(n_leaves)+')')
    leaves_count_text.setParentItem(polygon)
    leaves_count_text.setFont(QFont('Veranda', 6))
    leaves_count_text.setPos(masterItem.boundingRect().x() + 5, center.y() - leaves_count_text.boundingRect().height()/2)

    polygon.setPos(0, masterItem.boundingRect().y()/1.5)

    return masterItem
Ejemplo n.º 23
0
 def hoverLeaveEvent(self, mouseEvent):
     QGraphicsPolygonItem.hoverLeaveEvent(self, mouseEvent)
     self.toggleHighlight()
Ejemplo n.º 24
0
	def __init__(self, world):

		QGraphicsPolygonItem.__init__(self)
		
		#############################
		### Build graph
		#############################

		graph = pydot.Dot()
		graph.set_node_defaults(color = 'red', fontcolor = 'red', label = '\<orphan\>')
		graph.set('overlap', 'prism')
		
		# build adjacency graph from world
		for area in world.areas:
		
			# create node for each room
			node = pydot.Node(area.id)
			node.set( 'label', area.name )
			if area == world.player.currentArea:
				node.set( 'color', 'blue' )
				node.set( 'fontcolor', 'blue' )
			else:
				node.set( 'color', 'black' )
				node.set( 'fontcolor', 'black' )

			graph.add_node(node)

			# link to adjacent rooms
			for feature in area.features:
				for action in feature.actions:
					finalEvent = None
					for event in action.events:
						if type(event) == events.PlayerMoveEvent:
							finalEvent = pydot.Edge( src=area.id, dst=event.properties['destination'] )

					if finalEvent is not None:
						graph.add_edge( finalEvent )
	
		################################
		### Generate SVG from graph
		################################

		ps = graph.create_svg(prog='neato')

		#########################################
		### Build graphics items from SVG
		#########################################

		# build xml tree
		ns = {'svg': 'http://www.w3.org/2000/svg'}
		doc = ET.fromstring(ps)

		# grab the root node properties
		rootNode = doc.xpath('/svg:svg/svg:g[1]', namespaces=ns)[0]
		polygon = rootNode.xpath('./svg:polygon', namespaces=ns)[0]
		pointStr = polygon.xpath('./@points', namespaces=ns)[0]
		penColor = QString(polygon.xpath('./@stroke', namespaces=ns)[0])
		fillColor = QString(polygon.xpath('./@fill', namespaces=ns)[0])

		# parse root polygon path
		path = QPolygonF()
		for pair in pointStr.split(' '):
			dims = pair.split(',')
			point = QPointF( float(dims[0]), float(dims[1]) )
			path.append(point)
		self.setPolygon(path)

		# fill in root node colors
		if QColor.isValidColor(penColor):
			self.setPen( QColor(penColor) )
		if QColor.isValidColor(fillColor):
			self.setBrush( QColor(fillColor) )

		# build each graph node
		for xmlNode in rootNode.xpath('./svg:g', namespaces=ns):

			group = QGraphicsRectItem(self)
			group.setPen( Qt.transparent )
			group.setBrush( Qt.transparent )


			if xmlNode.attrib['class'] == 'node':

				# find the area object
				name = xmlNode.xpath('./svg:title', namespaces=ns)[0].text
				group.setData( 0, QString(world.areas[world.areaLookup[name]].id) )
				
				# get the ellipse info
				ellipseNode = xmlNode.xpath('./svg:ellipse', namespaces=ns)[0]
				elProps = { k: float(ellipseNode.attrib[k]) for k in ['cx', 'cy', 'rx', 'ry']}
				rect = QRectF( elProps['cx']-elProps['rx'], elProps['cy']-elProps['ry'], 2*elProps['rx'], 2*elProps['ry'])
				penColor = QString(ellipseNode.attrib['stroke'])
				ellipseItem = QGraphicsEllipseItem(rect, group)
				if QColor.isValidColor(penColor):
					ellipseItem.setPen( QColor(penColor) )

				# get the text info
				textNode = xmlNode.xpath('./svg:text', namespaces=ns)[0]
				text = textNode.text
				textItem = QGraphicsTextItem(text, group)
				penColor = textNode.attrib.get('fill', 'black')
				nodePoint = QPointF(float(textNode.attrib['x']), float(textNode.attrib['y']))
				textItem.setPos( nodePoint - textItem.boundingRect().center() + QPointF(0.0,-4.0))
				if QColor.isValidColor(penColor):
					textItem.setDefaultTextColor( QColor(penColor) )

				group.setRect( ellipseItem.boundingRect() )
				group.setFlags( QGraphicsRectItem.ItemIsSelectable )

			elif xmlNode.attrib['class'] == 'edge':

 				# parse the line portion of the arrow
 				line = xmlNode.xpath('./svg:path', namespaces=ns)[0]
				path = QPainterPath()

				# pull info from xml file
				linePath = line.attrib['d']
				lineColor = line.attrib['stroke']
					
				# parse path coords
				points = re.findall( '(-?\d+\.\d+),(-?\d+\.\d+)', linePath )
				if len(points) != 4:
					continue
				startPoint = QPointF( float(points[0][0]), float(points[0][1]) )
				path.moveTo(startPoint)
				curvePoints = []
				for pointCoord in points[1:]:
					curvePoints.append( QPointF(float(pointCoord[0]), float(pointCoord[1])) )
				path.cubicTo( curvePoints[0], curvePoints[1], curvePoints[2] )

				# construct path item
				pathItem = QGraphicsPathItem(path, group)
				if QColor.isValidColor(lineColor):
					pathItem.setPen( QColor(lineColor) )

				polyNode = xmlNode.xpath('./svg:polygon', namespaces=ns)[0]

				# pull info from xml file
				pointStr = polyNode.xpath('./@points', namespaces=ns)[0]
				penColor = QString(polyNode.xpath('./@stroke', namespaces=ns)[0])
				fillColor = QString(polyNode.xpath('./@fill', namespaces=ns)[0])

				# parse polygon path
				path = QPolygonF()
				for pair in pointStr.split(' '):
					dims = pair.split(',')
					point = QPointF( float(dims[0]), float(dims[1]) )
					path.append(point)

				# construct polygon item
				polygonItem = QGraphicsPolygonItem(path, group)
				if QColor.isValidColor(penColor):
					polygonItem.setPen( QColor(penColor) )
				if QColor.isValidColor(fillColor):
					polygonItem.setBrush( QColor(fillColor) )

				group.setRect( pathItem.boundingRect() and polygonItem.boundingRect() )
Ejemplo n.º 25
0
class ParallelCoordinatePolygon(OWPlotItem):
    def __init__(self, i, mu1, mu2, sigma1, sigma2, phi, color):
        OWPlotItem.__init__(self)
        self.outer_box = QGraphicsPolygonItem(self)
        self.inner_box = QGraphicsPolygonItem(self)

        self.i = i
        self.mu1 = mu1
        self.mu2 = mu2
        self.sigma1 = sigma1
        self.sigma2 = sigma2
        self.phi = phi

        self.twosigmapolygon = QPolygonF([
            QPointF(i, mu1 - sigma1),
            QPointF(i, mu1 + sigma1),
            QPointF(i + 1, mu2 + sigma2),
            QPointF(i + 1, mu2 - sigma2),
            QPointF(i, mu1 - sigma1)
        ])

        self.sigmapolygon = QPolygonF([
            QPointF(i, mu1 - .5 * sigma1),
            QPointF(i, mu1 + .5 * sigma1),
            QPointF(i + 1, mu2 + .5 * sigma2),
            QPointF(i + 1, mu2 - .5 * sigma2),
            QPointF(i, mu1 - .5 * sigma1)
        ])

        if isinstance(color, tuple):
            color = QColor(*color)
        color.setAlphaF(.3)
        self.outer_box.setBrush(color)
        self.outer_box.setPen(QColor(0, 0, 0, 0))
        self.inner_box.setBrush(color)
        self.inner_box.setPen(color)

    def update_properties(self):
        self.outer_box.setPolygon(self.graph_transform().map(
            self.twosigmapolygon))
        self.inner_box.setPolygon(self.graph_transform().map(
            self.sigmapolygon))
Ejemplo n.º 26
0
class auto(QGraphicsPixmapItem):
    def __init__(self, *args):
        self.seleccionado = False
        self.velocity = random.randint(1, 10)
        QGraphicsPixmapItem.__init__(self, *args)
        self.setPixmap(
            QPixmap("sprites/" + str(random.randint(1, 45)) + ".png"))
        self.setTransformOriginPoint(self.boundingRect().width() / 2.0,
                                     self.boundingRect().height() / 2.0)
        self.setZValue(10)
        ##menu contextual
        self.menu = QMenu()
        self.Actions = []  #arreglo de acciones
        self.Actions.append(self.menu.addAction("Seguir"))
        self.Actions.append(self.menu.addAction("Editar"))
        self.Actions.append(self.menu.addAction("girar clockwise"))
        self.Actions.append(self.menu.addAction("girar anti-clockwise"))
        self.Actions.append(self.menu.addAction("Colisiones"))
        self.Actions.append(self.menu.addAction("Duplicar"))
        self.Actions.append(self.menu.addAction("Eliminar"))
        self.menu.triggered[QAction].connect(self.test)
        ##offset para el arrastre
        self.offset = QPointF(0, 0)
        ##poligono de vision
        poligono = QPolygonF()
        poligono.append(QPointF(-1, 10))
        poligono.append(QPointF(-1, 20))
        poligono.append(QPointF(-30, 40))
        poligono.append(QPointF(-40, 15))
        poligono.append(QPointF(-30, -10))
        self.vision = QGraphicsPolygonItem(poligono, self, self.scene())
        self.vision.setBrush(QColor(255, 255, 0, 100))
        self.vision.setPen(QColor(255, 255, 0))

    def info(self):
        return "Velocidad " + str(self.velocity) + " posicion " + str(
            self.pos())[20:] + "\n"

    def test(self, act):
        print act.text()
        if act.text() == "girar clockwise":
            self.setRotation(self.rotation() - 45)
        if act.text() == "girar anti-clockwise":
            self.setRotation(self.rotation() + 45)
        if act.text() == "Colisiones":
            print "colisiones con", self.collidingItems(
                1), self.vision.collidingItems(1)
        if act.text() == "Duplicar":
            self.scene().addItem(auto())
        if act.text() == "Eliminar":
            self.scene().removeItem(self)

    def contextMenuEvent(self, event):
        self.menu.popup(event.screenPos())

    def mousePressEvent(self, event):
        p = event.pos()
        self.offset = QPointF(p.x() * 1.0, p.y() * 1.0)
        self.seleccionado = not self.seleccionado

    def mouseMoveEvent(self, event):
        self.setPos(event.scenePos() - self.offset)

    def avanza(self):
        if self.velocity != 0:
            """print velocity
              print "current pos (%f,%f)"%(self.pos().x(),self.pos().y())
              print "angle %f "%(self.rotation())"""
            radians = self.rotation() * 0.0174532925
            """ print "angle rad %f "%(radians)"""
            nx = 1.0 * self.velocity * cos(radians)
            ny = 1.0 * self.velocity * sin(radians)
            """ print "avanzara a (%f,%f)"%(nx,ny) """
            self.setPos(self.pos().x() - nx, self.pos().y() - ny)
            """for i in self.collidingItems():