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)
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)
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
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)
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)
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))
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))
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():
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() )
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():