def paint(self, painter, option, widget=None): if not self.pixmap: painter.setBrush(self.dragOver and self.color.light(130) or self.color) painter.drawRoundedRect(-10, -30, 20, 30, 25, 25, QtCore.Qt.RelativeSize) painter.setBrush(QtCore.Qt.white) painter.drawEllipse(-7, -3 - 20, 7, 7) painter.drawEllipse(0, -3 - 20, 7, 7) painter.setBrush(QtCore.Qt.black) painter.drawEllipse(-5, -1 - 20, 2, 2) painter.drawEllipse(2, -1 - 20, 2, 2) painter.setPen(QtGui.QPen(QtCore.Qt.black, 2)) painter.setBrush(QtCore.Qt.NoBrush) painter.drawArc(-6, -2 - 20, 12, 15, 190 * 16, 160 * 16) else: painter.scale(.2272, .2824) painter.drawPixmap(QtCore.QPointF(-15 * 4.4, -50 * 3.54), self.pixmap)
def dropEvent(self, event): """dropEvent handler for the EditorSceneBackground. If the dragged item is already on this scene, it moves the item. If the dragged item is dragged from the library scene, a new item is created.""" if event.mimeData().hasText(): tiType, tiId, ox, oy, point = event.mimeData().text().split("#") if int(tiId) < 0: event.setDropAction(Qt.CopyAction) event.accept() self.editor.createTrackItem(tiType, event.scenePos()) else: event.setDropAction(Qt.MoveAction) event.accept() clickPos = QtCore.QPointF(float(ox), float(oy)) self.editor.moveTrackItem(tiId, event.scenePos(), clickPos, point) else: event.ignore()
def addAlgorithm(self, alg, parametersMap, valuesMap, outputsMap, dependencies): self.algs.append(alg) self.algParameters.append(parametersMap) self.algOutputs.append(outputsMap) self.dependencies.append(dependencies) for value in valuesMap.keys(): self.paramValues[value] = valuesMap[value] algPos = self.getPositionForAlgorithmItem() self.algPos.append(algPos) pos = {} i = 0 from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for out in outputsMap: pos[out] = algPos + QtCore.QPointF( ModelerGraphicItem.BOX_WIDTH, i * ModelerGraphicItem.BOX_HEIGHT) i += 1 self.outputPos.append(pos)
def getTargetList(self): ## should probably do some caching here. items = self.activeItems() locations = [] occArea = QtGui.QPainterPath() for i in items: if isinstance(i, TargetOcclusion): occArea |= i.mapToView(i.shape()) for i in items: pts = i.listPoints() for j in range(len(pts)): p = pts[j] point = QtCore.QPointF(p[0], p[1]) if occArea.contains(point): i.setTargetPen(j, QtGui.QPen(QtGui.QColor(0,0,0,160))) else: locations.append(p) i.setTargetPen(j, None) return locations
def adjust(self): if not self.source or not self.dest: return line = QtCore.QLineF(self.mapFromItem(self.source, 0, 0), self.mapFromItem(self.dest, 0, 0)) length = line.length() self.prepareGeometryChange() if length > 20.0: edgeOffset = QtCore.QPointF((line.dx() * 10) / length, (line.dy() * 10) / length) self.sourcePoint = line.p1() + edgeOffset self.destPoint = line.p2() - edgeOffset else: self.sourcePoint = line.p1() self.destPoint = line.p1()
def paintVerticalSection(self, painter, sectionRect, logicalLeafIndex, hv, styleOptions, leafIndex): oldBO = QtCore.QPointF(painter.brushOrigin()) left = sectionRect.x() indexes = self.parentIndexes(leafIndex) for i in range(len(indexes)): realStyleOptions = QtGui.QStyleOptionHeader(styleOptions) #if( i<indexes.size()-1 # && # ( realStyleOptions.state.testFlag(QStyle::State_Sunken) # || realStyleOptions.state.testFlag(QStyle::State_On))) #{ # QStyle::State t(QStyle::State_Sunken | QStyle::State_On); # realStyleOptions.state&=(~t); #} left = self.paintVerticalCell(painter, hv, indexes[i], leafIndex, logicalLeafIndex, realStyleOptions, sectionRect, left) painter.setBrushOrigin(oldBO)
def update(self, dt_): """Updates the position of the robot. """ # Make shortcuts for wheel radius and base length (m) R = self._robot.info()["wheels"]["radius"] L = self._robot.info()["wheels"]["baseLength"] # Make shortcuts for wheels velocity (rad/s) vel_l = self._robot.getLeftWheelSpeed() vel_r = self._robot.getRightWheelSpeed() # Convert to robot speed and angular velocity (in m and rad/s) v, w = self.diff2Uni(vel_l, vel_r) # Current angle of the robot (rad) theta = self._robot.angle() # Position of the robot in the scene referential x,y = self._robot.pos().x(), self._robot.pos().y() # Calculate robot's position and angle increment if w == 0: dtheta = 0 x += v*cos(theta)*dt_ y += v*sin(theta)*dt_ else: dtheta = w*dt_ x += 2*v/w*cos(theta + dtheta/2)*sin(dtheta/2) y += 2*v/w*sin(theta + dtheta/2)*sin(dtheta/2) theta += dtheta # Update number of revolutions l_rev = self._robot.leftRevolutions() + vel_l*dt_/2/pi r_rev = self._robot.rightRevolutions() + vel_r*dt_/2/pi # Set revolutions self._robot.setLeftRevolutions(l_rev) self._robot.setRightRevolutions(r_rev) # Set new robot positions self._robot.setPos(QtCore.QPointF(x, y)) self._robot.setAngle((theta + pi)%(2*pi) - pi)
def setPos(self, *pos): # print time.time(),'posSET' # if self.moved != None: # return if len(pos) == 1: pos = pos[0] elif len(pos) == 2: pos = QtCore.QPointF(*pos) _from = self.pos() to = pos if self.moved == None: QtGui.QGraphicsObject.setPos(self, pos) if self.animation and _from != to: self.POSanimation(_from, to) else: self.POSanim.stop()
def renderEdge(self, eid, einfo, points): scene = self.scene() # If we have been drawn already, get rid of it. gproxy = einfo.get('gproxy') if gproxy: scene.removeItem(gproxy) qpoints = [QtCore.QPointF(x, y) for (x, y) in points] qpoly = QtGui.QPolygonF(qpoints) ecolor = self._vg_graph.getMeta('edgecolor', '#000') ecolor = einfo.get('color', ecolor) pen = QtGui.QPen(QtGui.QColor(ecolor)) gproxy = self.scene().addPolygon(qpoly, pen=pen) gproxy.setZValue(-1.0) einfo['gproxy'] = gproxy
def _paintAlternate(self, painter): altHeight = self.parentItem().alternateHeight() spacing = self._qScore.scale painter.setPen(self._qScore.palette().text().color()) painter.drawLine(0, self._base, self.width() - spacing * 2, self._base) painter.drawLine(0, self._base, 0, altHeight - spacing * 2 + self._base) font = painter.font() font.setItalic(True) painter.setFont(font) if self._alternate is None: self._alternate = QtCore.QRectF(0, 0, 0, 0) text = self._measure.alternateText textWidth = QtGui.QFontMetrics(font).width(text) self._alternate.setSize(QtCore.QSizeF(textWidth, altHeight)) bottomLeft = QtCore.QPointF(2 * spacing, altHeight - spacing + self._base) self._alternate.setBottomLeft(bottomLeft) painter.drawText(2 * spacing, altHeight - spacing + self._base, text)
def writeEdge(edge, width, color, moveBy): qpolf = QtGui.QPolygonF(len(edge)) for i, (x, y) in enumerate(edge): qpolf[i] = QtCore.QPointF(x, y) + moveBy result = "\n" if qpolf.size() == 2: result += '<line x1="' + str(qpolf[0].x()) + '" y1="' + str( qpolf[0].y()) + '" ' result += 'x2="' + str(qpolf[1].x()) + '" y2="' + str(qpolf[1].y()) elif qpolf.size() > 2: result += '<polyline points="' + str(qpolf[0].x()) + '" y1="' + str( qpolf[0].y()) for pos in range(1, qpolf.size()): result += ' ' + str(qpolf[pos].x()) + '" y1="' + str( qpolf[pos].y()) result += '"\n style="stroke:' + color + '; stroke-width:' + str( width if width > 0 else 0.5) + ';\n' result += ' stroke-linejoin:bevel; stroke-linecap:butt;"/>\n' return result
def __init__(self, input, output, value, parent): QtGui.QAbstractSlider.__init__(self, parent) #log.debug("MixerNode.__init__( %i, %i, %i, %s )" % (input, output, value, str(parent)) ) self.pos = QtCore.QPointF(0, 0) self.input = input self.output = output self.setOrientation(Qt.Qt.Vertical) self.setRange(0, pow(2, 16) - 1) self.setValue(value) self.connect(self, QtCore.SIGNAL("valueChanged(int)"), self.internalValueChanged) self.setSmall(False) self.bgcolors = ColorForNumber() self.bgcolors.addColor(0.0, QtGui.QColor(0, 0, 0)) self.bgcolors.addColor(1.0, QtGui.QColor(0, 0, 128)) self.bgcolors.addColor(math.pow(2, 6), QtGui.QColor(0, 255, 0)) self.bgcolors.addColor(math.pow(2, 14), QtGui.QColor(255, 255, 0)) self.bgcolors.addColor(math.pow(2, 16) - 1, QtGui.QColor(255, 0, 0)) self.setContextMenuPolicy(Qt.Qt.ActionsContextMenu) self.mapper = QtCore.QSignalMapper(self) self.connect(self.mapper, QtCore.SIGNAL("mapped(const QString&)"), self.directValues) self.spinbox = QtGui.QDoubleSpinBox(self) self.spinbox.setRange(-40, 12) self.spinbox.setSuffix(" dB") self.connect(self.spinbox, QtCore.SIGNAL("valueChanged(const QString&)"), self.directValues) action = QtGui.QWidgetAction(self) action.setDefaultWidget(self.spinbox) self.addAction(action) for text in ["3 dB", "0 dB", "-3 dB", "-20 dB", "-inf dB"]: action = QtGui.QAction(text, self) self.connect(action, QtCore.SIGNAL("triggered()"), self.mapper, QtCore.SLOT("map()")) self.mapper.setMapping(action, text) self.addAction(action)
def read_points_Blines(self): f=open('%s/B_lines_file.txt'%PATH) maxnum_x,minnum_x,maxnum_y,minnum_y=self.find_max_min('%s/pde_p.txt'%PATH)#这里由于数据格式问题,使用模型中的最大最小值,而非剖分文件中的值 window_width,window_height=self.find_geometry_size() Qtpoints=[] for a in f: a=a.split('\t') b=[float(i) for i in a] point_num=len(b) for i in range(0,point_num,4): qpoints=[] for m in range(0,2): qpoint=QtCore.QPointF() qpoint.setX((b[i+2*m]-minnum_x)*window_width/(maxnum_x-minnum_x)) qpoint.setY((window_height-(b[i+1+2*m]-minnum_y)*window_height/(maxnum_y-minnum_y))) qpoints.append(qpoint) Qtpoints.append(qpoints) f.close() return Qtpoints
def fitAirfoilInView(self): if len(self.parent.airfoils) == 0: return nothing_selected = True for id, airfoil in enumerate(self.parent.airfoils): if airfoil.contour_item.isSelected(): nothing_selected = False break if nothing_selected: id = 0 # get bounding rect in scene coordinates item = self.parent.airfoils[id].contour_item rectf = item.boundingRect() rf = copy.deepcopy(rectf) # scale by 2% (seems to be done also by scene.itemsBoundingRect()) # after loading a single airfoil this leads to the same zoom as # if onViewAll was called center = rf.center() w = 1.02 * rf.width() h = 1.02 * rf.height() rf.setWidth(w) rf.setHeight(h) # shift center of rectf cx = center.x() # not easy to understand (at least for me) # this is needed due to the Airfoil.shiftContours() function cy = center.y() + item.pos().y() rf.moveCenter(QtCore.QPointF(cx, cy)) self.parent.view.fitInView(rf, mode=QtCore.Qt.KeepAspectRatio) # adjust airfoil marker size to MARKERSIZE setting self.parent.view.adjustMarkerSize() # cache view to be able to keep it during resize self.parent.view.getSceneFromView()
def addControlConnectorShape(self, blockPath, distanceToCenter, appendRight): # get the initial point info and set the currentConnectorPath to use the self._lineTo self._curveTo methods self.startPoint = blockPath.currentPosition() self.socketPoint = QtCore.QPointF( self.startPoint.x() + (distanceToCenter if appendRight else -distanceToCenter), self.startPoint.y()) self.currentConnectorPath = blockPath if (appendRight): #then the centerPoint is to the right of the current location on the generalPath self._lineTo( distanceToCenter - BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, 0) # update starting point for self._curveTo self.startPoint = blockPath.currentPosition() self._curveTo(BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, BlockConnectorShape.CONTROL_PLUG_HEIGHT * 4 / 3, BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, BlockConnectorShape.CONTROL_PLUG_HEIGHT * 4 / 3, BlockConnectorShape.CONTROL_PLUG_WIDTH, 0) else: # then the centerPoint is to the left of the current location on the generalPath self._lineTo( -distanceToCenter + BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, 0) #update starting point for self._curveTo self.startPoint = blockPath.currentPosition() self._curveTo(-BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, BlockConnectorShape.CONTROL_PLUG_HEIGHT * 4 / 3, -BlockConnectorShape.CONTROL_PLUG_WIDTH / 2, BlockConnectorShape.CONTROL_PLUG_HEIGHT * 4 / 3, -BlockConnectorShape.CONTROL_PLUG_WIDTH, 0) # to catch bugs self.currentConnectorPath = None return self.socketPoint
def ball_grav(self): imp = ch.pm.Vec2d(0,-700) imp.rotate(self.little_ball.chipBody.getAngleToWorldPoint((380,-450))) imp.rotate(ch.math.pi/2) imp=imp+ch.pm.Vec2d(0,-200) #print(imp, self.little_ball.chipBody.getAngleToWorldPoint((380,-450))) self.little_ball.chipBody.apply_absolute_impulse_at_local_point(imp,(0,0)) self.little_ball.chipBody.angle = self.little_ball.chipBody.getAngleToWorldPoint((380,-450)) - ch.math.pi/8 if self.getTimerManager().getTimerDelayPassed('DOT'): dot = QtGui.QGraphicsEllipseItem(QtCore.QRectF(0,0,5,5), scene = self) dot.setBrush(QtGui.QColor(0,0,0)) x,y = self.little_ball.chipBody.position dot.setPos(QtCore.QPointF(x-2,y-2)) self.dots.append(dot) if len(self.dots) > 400: d=self.dots.pop(0) self.dots[10].setBrush(QtGui.QColor(255,255,255)) self.dots[10].setPen(QtGui.QColor(255,255,255)) self.dots[25].setBrush(QtGui.QColor(0,0,200)) self.dots[25].setPen(QtGui.QColor(0,0,200)) self.dots[35].setBrush(QtGui.QColor(0,200,0)) self.dots[35].setPen(QtGui.QColor(0,200,0)) self.dots[45].setBrush(QtGui.QColor(200,200,0)) self.dots[45].setPen(QtGui.QColor(200,200,0)) self.dots[55].setBrush(QtGui.QColor(255,0,0)) self.dots[55].setPen(QtGui.QColor(255,0,0)) self.removeItem(d) ''' vec = -800 an = self.v_bod.chipBody.angle self.v_bod.getChipBody().apply_impulse_at_local_point((vec*ch.math.cos(ch.math.pi/2-an), vec*ch.math.sin(ch.math.pi/2-an)),(75,20)) ''' pass
def set_position(self, x=None, y=None): if x is None: x = self.v_line.getXPos() if y is None: y = self.h_line.getYPos() item_coords = self.imageItem.getViewBox().mapFromViewToItem( self.imageItem, QtCore.QPointF(x, y)) #item_coords = self.imageItem.mapFromScene(mouse_event) item_x, item_y = item_coords.x(), item_coords.y() max_x, max_y = self.imageItem.image.shape if item_x < 0 or item_x > max_x or item_y < 0 or item_y > max_y: return self.v_line.setPos(x) self.h_line.setPos(y) #(min_view_x, max_view_x), (min_view_y, max_view_y) = self.imageItem.getViewBox().viewRange() self.x_cross_index = max(min(int(item_x), max_x - 1), 0) self.y_cross_index = max(min(int(item_y), max_y - 1), 0) z_val = self.imageItem.image[self.x_cross_index, self.y_cross_index] self.update_cross_section()
def __init__(self, simulation, parameters): """ Constructor for the SignalItem class.""" super().__init__(simulation, parameters) reverse = parameters["reverse"] self.tiType = "S" signalTypeName = parameters["signaltype"] self._signalType = simulation.signalTypes[signalTypeName] self._routesSetParams = eval(str(parameters["routesset"])) or {} self._trainNotPresentParams = eval(str(parameters["trainpresent"])) \ or {} try: xb = float(parameters["xn"]) except TypeError: xb = self.origin.x() - 40 try: yb = float(parameters["yn"]) except TypeError: yb = self.origin.y() + 5 self._berthOrigin = QtCore.QPointF(xb, yb) self._berthRect = None self.setBerthRect() self._activeAspect = self._signalType.getDefaultAspect() self._reverse = reverse self._previousActiveRoute = None self._nextActiveRoute = None self._trainId = None self.defaultZValue = 50 sgi = helper.TrackGraphicsItem(self, SignalItem.SIGNAL_GRAPHIC_ITEM) sgi.setPos(self.origin) sgi.setCursor(Qt.PointingHandCursor) sgi.setToolTip(self.toolTipText) sgi.setZValue(self.defaultZValue) if reverse: sgi.setRotation(180) self._gi[SignalItem.SIGNAL_GRAPHIC_ITEM] = sgi self.simulation.registerGraphicsItem(sgi) bgi = helper.TrackGraphicsItem(self, SignalItem.BERTH_GRAPHIC_ITEM) bgi.setPos(self._berthOrigin) bgi.setCursor(Qt.PointingHandCursor) bgi.setZValue(self.defaultZValue) self._gi[SignalItem.BERTH_GRAPHIC_ITEM] = bgi self.simulation.registerGraphicsItem(bgi) self.updateGraphics()
def snap_point(self, position): point = Point(position.x(), position.y()) w = 2 h = 2 for graphics_item in self.scene().items(point.x - w / 2.0, point.y - h / 2.0, w, h): if graphics_item == self: continue if graphics_item.is_selectable: road_item = graphics_item.road_item if hasattr(road_item, "position"): if point.distance(road_item.position) < 1.0: return road_item.position else: for p in road_item.polyline: if point.distance(p) < 1.0: return QtCore.QPointF(p.x, p.y) return None
def paintEvent(self, event): painter = QtGui.QPainter(self) painter.setRenderHint(painter.Antialiasing) rect = event.rect() gauge_rect = QtCore.QRect(rect) size = gauge_rect.size() pos = gauge_rect.center() gauge_rect.moveCenter( QtCore.QPoint(pos.x() - size.width(), pos.y() - size.height())) gauge_rect.setSize(size * .9) gauge_rect.moveCenter(pos) refill_rect = QtCore.QRect(gauge_rect) size = refill_rect.size() pos = refill_rect.center() refill_rect.moveCenter( QtCore.QPoint(pos.x() - size.width(), pos.y() - size.height())) # smaller than .9 == thicker gauge refill_rect.setSize(size * .9) refill_rect.moveCenter(pos) painter.setPen(QtCore.Qt.NoPen) painter.drawPixmap(rect, self._bg) painter.save() grad = QtGui.QConicalGradient(QtCore.QPointF(gauge_rect.center()), 270.0) grad.setColorAt(.75, QtCore.Qt.green) grad.setColorAt(.5, QtCore.Qt.yellow) grad.setColorAt(.25, QtCore.Qt.red) painter.setBrush(grad) painter.drawPie(gauge_rect, 225.0 * 16, self._value * 16) painter.restore() painter.setBrush(QtGui.QBrush(self._bg.scaled(rect.size()))) painter.drawEllipse(refill_rect) super(GaugeWidget, self).paintEvent(event)
def paintEvent(self, event): """Draw little circles in the position of the Calpha atoms of p.""" diameter = 2 avgCalphaDistance = 4 zmin = -avgCalphaDistance * len(self.protein) zmax = avgCalphaDistance * len(self.protein) self.calphaList.sort(self.atomZSort) painter = QtGui.QPainter(self) painter.setRenderHint(QtGui.QPainter.Antialiasing, 1) painter.translate(self.width() / 2, self.height() / 2) xscale = 1.5 * self.width() / (avgCalphaDistance * len(self.protein)) yscale = 1.5 * self.height() / (avgCalphaDistance * len(self.protein)) scale = min(xscale, yscale) painter.scale(scale, scale) myGradient = QtGui.QRadialGradient(QtCore.QPointF(0, 0), 72) myGradient.setColorAt(0, QtCore.Qt.white) myGradient.setColorAt(1, QtCore.Qt.black) painter.setBrush(QtGui.QBrush(myGradient)) painter.translate(-self.centralAtom.position()[0], -self.centralAtom.position()[1]) for a in self.calphaList: pos = a.position() if pos[2] < zmin: zscale = 0.1 elif pos[2] > zmax: zscale = 5.0 else: zscale = (pos[2] - zmin) / (zmax - zmin) * 4.9 + 0.1 painter.save() painter.translate(pos[0], pos[1]) painter.scale(zscale * diameter / 100, zscale * diameter / 100) painter.drawEllipse(-50, -50, 100, 100) painter.restore() painter.setWorldMatrixEnabled(0) painter.drawText(5,self.height() -5 , QtCore.QString("E=%s" % self.protein.energy())) painter.setWorldMatrixEnabled(1)
def __init__(self, obj, parent=None, scene=None,\ brush=QtGui.QBrush(), pen=QtGui.QPen(Qt.blue, 0, Qt.SolidLine)) : """Adds QGraphics(Rect)Item to the scene. Parameters obj : QPointF or shape type e.g. QRectF obj is QPointF - shape parameters are defined at first mouse click obj is QRectF - it will be drawn as is """ GUDragBase.__init__(self, parent, brush, pen) rect = None if isinstance(obj, QtCore.QPointF): rect = QtCore.QRectF(obj, obj + QtCore.QPointF(5, 5)) self._mode = ADD elif isinstance(obj, QtCore.QRectF): rect = obj else: print 'GUDragRect - wrong init object type:', str(obj) parent_for_base = None QGraphicsRectItem.__init__(self, rect, parent_for_base, scene) if self._mode == ADD: self.grabMouse() # makes available mouseMoveEvent self.setAcceptHoverEvents(True) #self.setAcceptTouchEvents(True) self.setAcceptedMouseButtons(Qt.LeftButton) self.setPen(self._pen_pos) self.setBrush(self._brush) # Flags: ItemIsPanel, ItemClipsChildrenToShape, ItemIsSelectable, # ItemIsMovable, itemClipsToShape, ItemSendsScenePositionChanges self.setFlags(self.ItemIsSelectable) #self.setEnabled(False) # is visible, but do not receive events #self.setVisible(False) # is not visible, do not receive events #self.setSelected(True) self.setHandlesChildEvents(True) # will responsive to child events
def plot_all_events(self, rp_model, rp_view): """ * Description: Issues a command to rp_view to add a new event_plot_item. * Return: * Arguments: - event: The event to be plotted. """ events = rp_model._event_manager._events # Tell rp view to plot the event for event in events: rp_view.plot_new_event(event._data, event._duration, event._amplitude, \ rp_model._event_manager.is_selected(event)) # Select all events self.select_all_events(rp_model, rp_view) # Set targeted event self.change_targeted_event(rp_model, rp_view, rp_model._event_manager._targeted_event) # Set stats roi durs = [event._duration for event in rp_model._event_manager._events] amps = [event._amplitude for event in rp_model._event_manager._events] p0 = (min(durs), min(amps)) #p1 = (min(durs), max(amps)) size = (max(durs), max(amps)) #p2 = (max(durs), max(amps)) #p3 = (max(durs), min(amps)) handles = rp_view._stats_plot_roi.getHandles() rp_view._stats_plot_roi.movePoint(handles[0], pg.Point(QtCore.QPointF(p0[0], p0[1]))) rp_view._stats_plot_roi.setSize(size) #rp_view._stats_plot_roi.movePoint(handles[1], pg.Point(QtCore.QPointF(p1[0], p1[1]))) #rp_view._stats_plot_roi.movePoint(handles[2], pg.Point(QtCore.QPointF(p2[0], p2[1]))) #rp_view._stats_plot_roi.movePoint(handles[3], pg.Point(QtCore.QPointF(p3[0], p3[1]))) print type(handles[0]) return
def adjust(self): """ Adjust length and angle of edge based on movement of nodes. """ if not self.source or not self.dest: return line = QtCore.QLineF(self.mapFromItem(self.source, 0, 0), self.mapFromItem(self.dest, 0, 0)) self.setLine(line) length = line.length() if length == 0.0: return edgeOffset = QtCore.QPointF((line.dx() * 20) / length, (line.dy() * 20) / length) self.prepareGeometryChange() self.sourcePoint = line.p1() + edgeOffset self.destPoint = line.p2() - edgeOffset
def make_rectangle_around_line(self, point1, point2, extension=0.5, width=3.0): dx = point2.x - point1.x dy = point2.y - point1.y mag = math.hypot(dx, dy) x = dx * extension / mag y = dy * extension / mag dx = dx * width / mag dy = dy * width / mag path = QtGui.QPainterPath( QtCore.QPointF(point1.x - x - dy, point1.y - y + dx)) path.lineTo(point1.x - x + dy, point1.y - y - dx) path.lineTo(point2.x + x + dy, point2.y + y - dx) path.lineTo(point2.x + x - dy, point2.y + y + dx) path.closeSubpath() return path
def movePointInDirection(self, QPoint, direction): moveBy = self.__config.getSize() if direction == Direction.N: newPosition = QPoint + QtCore.QPointF(0, -1 * moveBy) if direction == Direction.NE: newPosition = QPoint + QtCore.QPointF(moveBy, -1 * moveBy) if direction == Direction.E: newPosition = QPoint + QtCore.QPointF(moveBy, 0) if direction == Direction.SE: newPosition = QPoint + QtCore.QPointF(moveBy, 1 * moveBy) if direction == Direction.S: newPosition = QPoint + QtCore.QPointF(0, moveBy) if direction == Direction.SW: newPosition = QPoint + QtCore.QPointF(-1 * moveBy, moveBy) if direction == Direction.W: newPosition = QPoint + QtCore.QPointF(-1 * moveBy, 0) if direction == Direction.NW: newPosition = QPoint + QtCore.QPointF(-1 * moveBy, -1 * moveBy) return newPosition
def load(self, device): self.m_frames = [] stream = QtCore.QDataStream(device) self.m_name = stream.readQString() frameCount = stream.readInt() for i in range(frameCount): nodeCount = stream.readInt() frame = Frame() frame.setNodeCount(nodeCount) for j in range(nodeCount): pos = QtCore.QPointF() stream >> pos frame.setNodePos(j, pos) self.m_frames.append(frame)
def paintEvent(self, paintevent): """Called whenever the widget needs to redraw""" painter = QtGui.QPainter(self) painter.setRenderHint(QtGui.QPainter.Antialiasing) rect = self.contentsRect() painter.setPen(QtGui.QColor(255, 255, 255, 0)) painter.setClipRect(rect) painter.translate(rect.center()) painter.rotate(self.step * self.inc) self._drawCogwheel(painter) r = (self.size / 2.0) * 0.3 painter.setBrush(QtGui.QBrush(self.color.light(150))) painter.drawEllipse(QtCore.QPointF(0, 0), r, r) if self.running: self.inc += 1
def itemChange(self, change, value): if (change == QtGui.QGraphicsItem.ItemPositionChange): newpos = value.toPointF() div = 0 if newpos.y() < self.pos().y(): div = 1 if newpos.y() > self.pos().y(): div = -1 hit = 0 rect = self.scene().sceneRect() if (newpos.y() >= self.lower): newpos.setY(self.lower) hit = 1 if (newpos.y() <= self.upper): newpos.setY(self.upper) hit = 1 if not (hit): self.attenChanged.emit(div) return QtCore.QPointF(self.pos().x(), newpos.y()) return QtGui.QGraphicsItem.itemChange(self, change, value)
def DrawPolygon(self, vertices, color, shape=None, closed=True): """ Draw a wireframe polygon given the world vertices vertices (tuples) with the specified color. """ poly = QtGui.QPolygonF() pen = QtGui.QPen(QtGui.QColor(*color.bytes)) for v in vertices: poly += QtCore.QPointF(*v) if closed: item = self.scene.addPolygon(poly, pen=pen) self.temp_items.append(item) else: path = QtGui.QPainterPath() path.addPolygon(poly) #contour=QtGui.QGraphicsPathItem(path) #contour.setPen(pen) item = self.scene.addPath(path, pen=pen) self.temp_items.append(item)