def paint(self, painter, option, widget): path = QPainterPath() path.addRoundedRect(self._rect, 5, 5) anchor = self.mapFromParent(self._chart.mapToPosition(self._anchor)) if not self._rect.contains(anchor) and not self._anchor.isNull(): point1 = QPointF() point2 = QPointF() # establish the position of the anchor point in relation to _rect above = anchor.y() <= self._rect.top() aboveCenter = (anchor.y() > self._rect.top() and anchor.y() <= self._rect.center().y()) belowCenter = (anchor.y() > self._rect.center().y() and anchor.y() <= self._rect.bottom()) below = anchor.y() > self._rect.bottom() onLeft = anchor.x() <= self._rect.left() leftOfCenter = (anchor.x() > self._rect.left() and anchor.x() <= self._rect.center().x()) rightOfCenter = (anchor.x() > self._rect.center().x() and anchor.x() <= self._rect.right()) onRight = anchor.x() > self._rect.right() # get the nearest _rect corner. x = (onRight + rightOfCenter) * self._rect.width() y = (below + belowCenter) * self._rect.height() cornerCase = ((above and onLeft) or (above and onRight) or (below and onLeft) or (below and onRight)) vertical = abs(anchor.x() - x) > abs(anchor.y() - y) x1 = (x + leftOfCenter * 10 - rightOfCenter * 20 + cornerCase * int(not vertical) * (onLeft * 10 - onRight * 20)) y1 = (y + aboveCenter * 10 - belowCenter * 20 + cornerCase * vertical * (above * 10 - below * 20)) point1.setX(x1) point1.setY(y1) x2 = (x + leftOfCenter * 20 - rightOfCenter * 10 + cornerCase * int(not vertical) * (onLeft * 20 - onRight * 10)) y2 = (y + aboveCenter * 20 - belowCenter * 10 + cornerCase * vertical * (above * 20 - below * 10)) point2.setX(x2) point2.setY(y2) path.moveTo(point1) path.lineTo(anchor) path.lineTo(point2) path = path.simplified() painter.setBrush(QColor(255, 255, 255)) painter.drawPath(path) painter.drawText(self._textRect, self._text)
def __init__(self, chart): QGraphicsItem.__init__(self, chart) self._chart = chart self._text = "" self._textRect = QRectF() self._anchor = QPointF() self._font = QFont() self._rect = QRectF()
def _draw_text_helper(painter, point, text, flags): # We want an arbitrarily large size, so that we don't have to worry about text being cut off size = 1000000.0 new_x = point.x() new_y = point.y() - size if flags & Qt.AlignHCenter: new_x -= size / 2.0 elif flags & Qt.AlignRight: new_x += size / 2.0 if flags & Qt.AlignVCenter: new_y += size / 2.0 elif flags & Qt.AlignTop: new_y += size else: flags |= Qt.AlignBottom rect = QRectF(QPointF(new_x, new_y), QSizeF(size, size)) painter.drawText(rect, flags, text)
def __init__(self, size, period=0, yZero=0): """ @param size: Spline size (scene coords) @type size: int @param period: Spline period (scene coords.) or 0 @type period: int @param yZero: curve origin is (0, yZero) @type yZero: int """ super().__init__(size, fixedPoints=None, parentItem=None, baseCurve=(QPoint(0, yZero), QPoint(size, yZero))) self.period = period self.yZero = yZero # x-coordinates of the curve self.xCoords = np.arange(size + 2 * self.periodViewing) - self.periodViewing self.spline = [QPointF(x, yZero) for x in self.xCoords] # scene coord.
def __init__(self): self.parent_country = None self.population = Population(self) self.size_type = 0 self.r = 10 self.transport_density = 1.0 self.is_epidemic = False self.vaccination_quota = 0 self.norm_color = CITY_NORMAL_COLOR self.infect_color = CITY_INFECTED_COLOR self.epid_color = CITY_EPIDEMIC_COLOR self.alpha = 255 self.pos = QPointF(0, 0)
def testquadToQuad(self): q1 = QPolygonF() q1.append(QPointF(10.0, 10.0)) q1.append(QPointF(20.0, 10.0)) q1.append(QPointF(10.0, -10.0)) q1.append(QPointF(20.0, -10.0)) q2 = QPolygonF() q2.append(QPointF(20.0, 20.0)) q2.append(QPointF(30.0, 20.0)) q2.append(QPointF(20.0, -20.0)) q2.append(QPointF(30.0, -20.0)) t1 = QTransform() r1 = QTransform.quadToQuad(q1, q2, t1) r2 = QTransform.quadToQuad(q1, q2) self.assertTrue(r1) self.assertTrue(r2) self.assertEqual(t1, r2)
def paint(self, qpainter, options, widget): """ Overrides QGraphicsItemGroup paint @param qpainter: @param options: @param widget: @return: """ # local coordinates qpainter.save() if self.isSelected(): qpainter.setBrush(QBrush(QColor(255, 255, 255))) else: qpainter.setBrush(QBrush(QColor(0,0,0))) if self.isSelected(): # self.mouseIsPressed: qpainter.setPen(QPen(Qt.white, 1, Qt.DotLine, Qt.RoundCap)) for child in self.childItems(): qpainter.drawLine(QPointF(), child.pos()) qpainter.restore()
def mouseReleaseEvent(self, e): """ Adds a control point to the curve @param e: """ # click event if self.clicked: # add point p = e.pos() a = activeSplinePoint(p.x(), p.y(), parentItem=self) self.fixedPoints.append(a) self.fixedPoints.sort(key=lambda z: z.scenePos().x()) t = activeTangent(controlPoint=p + QPointF(0.7, -0.7) * self.halfTgLen, contactPoint=p, parentItem=self) a.tangent = t self.fixedTangents.insert(self.fixedPoints.index(a), t) self.updatePath()
def zoom(self, p_abs, p_mapped, angle): by = 0 velocity = 2 * (1 / self.current_scale) + 0.5 if velocity > 3: velocity = 3 direction = '' if angle > 0: by = 1 + (angle / 360 * 0.1 * velocity) direction = 'in' elif angle < 0: by = 1 - (-angle / 360 * 0.1 * velocity) direction = 'out' else: by = 1 scene_rect_width = self.mapFromScene(self.sceneRect()).boundingRect().width() scene_rect_height = self.mapFromScene(self.sceneRect()).boundingRect().height() if direction == 'in': if self.current_scale * by < 3: self.scale(by, by) self.current_scale *= by elif direction == 'out': if scene_rect_width * by >= self.viewport().size().width() and scene_rect_height * by >= self.viewport().size().height(): self.scale(by, by) self.current_scale *= by w = self.viewport().width() h = self.viewport().height() wf = self.mapToScene(QPoint(w - 1, 0)).x() - self.mapToScene(QPoint(0, 0)).x() hf = self.mapToScene(QPoint(0, h - 1)).y() - self.mapToScene(QPoint(0, 0)).y() lf = p_mapped.x() - p_abs.x() * wf / w tf = p_mapped.y() - p_abs.y() * hf / h self.ensureVisible(lf, tf, wf, hf, 0, 0) target_rect = QRectF(QPointF(lf, tf), QSizeF(wf, hf)) self.total_scale_div = target_rect.width() / self.viewport().width() self.ensureVisible(target_rect, 0, 0)
def createRightSide(self): self.topRightGroupBox = QGroupBox() self.totalLength = 0 self.elems = 0 self.elems_list = [] self.overall_layout = QVBoxLayout() grad = QPalette() gradient = QConicalGradient(QPointF(1100, 150), -190) gradient.setColorAt(0.0, QColor(30, 30, 30)) gradient.setColorAt(0.5, QColor(50, 50, 50)) gradient.setColorAt(0.97, QColor(50, 13, 150)) gradient.setColorAt(1.0, QColor(106, 13, 173)) gradient.setSpread(QGradient.RepeatSpread) grad.setBrush(QPalette.Window, QBrush(gradient)) self.setPalette(grad) self.scrollarea = QScrollArea() self.scrollarea.setWidgetResizable(True) self.widget = QWidget() self.scrollarea.setWidget(self.widget) self.layout = QVBoxLayout(self.widget) self.add_elem = QPushButton("Add Element") if PLATFORM == "darwin": self.add_elem.setToolTip("Shortcut: ⌘E") else: self.add_elem.setToolTip("Shortcut: Ctrl+E") self.add_elem.setStyleSheet( "QToolTip { border: 0px; border-radius: 3px }") self.add_elem.clicked.connect(lambda: ElementPopup()) self.add_elem.setFixedWidth(300) shortcut = QShortcut(QKeySequence("Ctrl+E"), self.add_elem) shortcut.activated.connect(lambda: ElementPopup()) shortcut.setEnabled(True) self.layout.addWidget(self.add_elem) self.layout.setAlignment(self.add_elem, Qt.AlignCenter | Qt.AlignTop) self.overall_layout.addWidget(self.scrollarea) self.topRightGroupBox.setLayout(self.overall_layout)
def __init__(self, starCount=1, maxStarCount=5): self.starCount = starCount self.maxStarCount = maxStarCount # Create the star shape we'll be drawing. self.starPolygon = QPolygonF() self.starPolygon.append(QPointF(1.0, 0.5)) for i in range(1, 5): self.starPolygon.append(QPointF(0.5 + 0.5 * cos(0.8 * i * pi), 0.5 + 0.5 * sin(0.8 * i * pi))) # Create the diamond shape we'll show in the editor self.diamondPolygon = QPolygonF() diamondPoints = [QPointF(0.4, 0.5), QPointF(0.5, 0.4), QPointF(0.6, 0.5), QPointF(0.5, 0.6), QPointF(0.4, 0.5)] for point in diamondPoints: self.diamondPolygon.append(point)
def cameraProfileUpdate(value): self.dngDict = self.cameraProfilesCombo.itemData(value) if self.options['cpToneCurve']: toneCurve = dngProfileToneCurve( self.dngDict.get('ProfileToneCurve', [])) self.toneForm.baseCurve = [ QPointF(x * axeSize, -y * axeSize) for x, y in zip(toneCurve.dataX, toneCurve.dataY) ] self.toneForm.update() # recompute as shot temp and tint using new profile self.asShotTemp, self.asShotTint = multipliers2TemperatureAndTint( *1 / np.array(self.asShotMultipliers[:3]), self.XYZ2CameraMatrix, self.dngDict) # display updated as shot temp item = self.listWidget2.item(1) item.setText(item.text().split(":")[0] + ': %d' % self.asShotTemp) # invalidate cache self.layer.bufCache_HSV_CV32 = None self.dataChanged.emit(2) # 2 = no postprocessing
def replot(): axis = self.axes(Qt.Vertical)[axis_index] d_min = d_max = None for n in cache.columns()[1:]: serie = self.findSerie(n) data = cache[n] if d_min is None: d_min = min(data) d_max = max(data) else: d_min = min(d_min, min(data)) d_max = max(d_max, max(data)) points = [QPointF(*i) for i in zip(cache["timestamp"], data)] serie.replace(points) self.timeAxis.setRange( *(map(QDateTime().fromMSecsSinceEpoch, cache.timeRange()))) axis.setRange(d_min, d_max) self._next_update = time.monotonic() + self.updateInterval
def __init__(self, item, duration=2000, count=5, percentage_size=0.24, x_shift=0): """Initializes animation stuff. Args: item (QGraphicsItem): The item on top of which the animation should play. """ self._item = item self.cubes = [QGraphicsTextItem("\uf1b2", item) for i in range(count)] self.opacity_at_value_path = QPainterPath(QPointF(0.0, 0.0)) self.opacity_at_value_path.lineTo(QPointF(0.01, 1.0)) self.opacity_at_value_path.lineTo(QPointF(0.5, 1.0)) self.opacity_at_value_path.lineTo(QPointF(1.0, 0.0)) self.time_line = QTimeLine() self.time_line.setLoopCount(0) # loop forever self.time_line.setFrameRange(0, 10) self.time_line.setDuration(duration) self.time_line.setCurveShape(QTimeLine.LinearCurve) self.time_line.valueChanged.connect( self._handle_time_line_value_changed) self.time_line.stateChanged.connect( self._handle_time_line_state_changed) font = QFont('Font Awesome 5 Free Solid') item_rect = item.rect() cube_size = percentage_size * 0.875 * item_rect.height() font.setPixelSize(cube_size) rect = item_rect.translated(-0.5 * cube_size + x_shift, -cube_size) end = rect.center() ctrl = end - QPointF(0, 0.6 * rect.height()) lower, upper = 0.2, 0.8 starts = [lower + i * (upper - lower) / count for i in range(count)] starts = [ rect.topLeft() + QPointF(start * rect.width(), 0) for start in starts ] self.paths = [QPainterPath(start) for start in starts] for path in self.paths: path.quadTo(ctrl, end) self.offsets = [i / count for i in range(count)] for cube in self.cubes: cube.setFont(font) cube.setDefaultTextColor("#003333") cube.setTransformOriginPoint(cube.boundingRect().center()) cube.hide() cube.setOpacity(0)
def get_point_along_walls(room, margin): r_aux = copy.deepcopy(room.room_qrect) r_aux = r_aux.adjusted(+margin, -margin, -margin, +margin) # left,top,right,bottom lines = { 'top': QLineF(r_aux.topLeft(), r_aux.topRight()), 'right': QLineF(r_aux.topRight(), r_aux.bottomRight()), 'bottom': QLineF(r_aux.bottomLeft(), r_aux.bottomRight()), 'left': QLineF(r_aux.topLeft(), r_aux.bottomLeft()) } del lines[room.door_position] side = random.choice(list(lines.keys())) p = random.uniform(0.25, 0.75) return QPointF(lines[side].pointAt(p).x(), lines[side].pointAt(p).y()), side
def append_data_and_plot(self, d): """Append and update the plot""" num, m = d ax1 = self.chart.axisX(self.series) xmin = xmax = num step = 100 for p in self.series.pointsVector()[-step:]: xmin = min(p.x(), xmin) xmax = max(p.x(), xmax) xmin = max(0, xmax - step) ax1.setMin(xmin) ax1.setMax(xmax) self.series.append(QPointF(num, m))
def add_corridor(self, side, corridor_width, corridor_height): if len(self.dict_rooms_and_corridors_per_side[side]) == 0: if side == 'bottom': initial_point = self.initial_corridor.bottomLeft() else: initial_point = self.initial_corridor.topLeft() + QPointF( 0, self.fixed_height) else: initial_point = self.dict_rooms_and_corridors_per_side[side][ -1].room_qrect.topRight() corridor = Room(type='corridor', p=initial_point, w=corridor_width, h=-corridor_height) self.dict_rooms_and_corridors_per_side[side].append(corridor)
def mouseMoveEvent(self, event): """ When the mouse is moved, update the destination and color of the indicator. :param event: The event that carries the location of the mouse move :type event: QGraphicsSceneMouseEvent :return: None :rtype: NoneType """ if self.stagingConnection is None: return destP = event.scenePos() pg = self.getPortGraphicsAtPos(event.scenePos().x(), event.scenePos().y()) if pg is not self.stagingConnection and pg is not None: # if it's a valid connection, color the indicator and snap to middle of port. src = self.stagingConnection.getPort() dst = pg.getPort() if self._action.connectionIsValid(src, dst): x = pg.scenePos().x() y = pg.scenePos().y() - PortGraphics.TOTAL_HEIGHT / 2 destP = QPointF(x, y) self.connectionIndicator.setColor( ConnectionIndicator.GOOD_COLOR) else: self.connectionIndicator.setColor( ConnectionIndicator.BAD_COLOR) # If the src port is the dest port, color it bad. elif pg is self.stagingConnection: self.connectionIndicator.setColor(ConnectionIndicator.BAD_COLOR) # If we're not over a port, just use the base color. else: self.connectionIndicator.setColor(ConnectionIndicator.BASE_COLOR) self.connectionIndicator.setDest(destP) self.connectionIndicator.prepareGeometryChange() event.accept()
def groupFromList(cls, items, grid=None, position=QPointF(), parent=None): """ Inits a new group and adds all activeNode objects from list to the group. @param items: @type items: list @param grid: @type grid: activeGrid @param position: group position @type position: QPointF @param parent: @return: group @rtype: nodeGroup """ if not items: return newGroup = nodeGroup(grid=grid, position=position, parent=parent) for item in items: if type(item) is activeNode: newGroup.addToGroup(item) newGroup.setSelected(True) return newGroup
def mousePressEvent(self, event: QGraphicsSceneMouseEvent): mousePos = QPointF( event.buttonDownScenePos(Qt.LeftButton).x(), event.buttonDownScenePos(Qt.LeftButton).y()) itemList = list(self.items(mousePos)) super(GraphicsScene, self).mousePressEvent(event) if event.button() == Qt.LeftButton: if len(self.nodeList) <= 2: if self.focusItem(): self.nodeList.append((self.focusItem(), time())) if not self.focusItem(): self.nodeList.clear() if len(itemList) > 0: self.m_Item = itemList[0] self.itemLock.emit(self.m_Item) if self.m_Item is not None and event.button() == Qt.LeftButton: self.m_oldPos = self.m_Item.pos()
def keyPressEvent(self, event): if event.key() == Qt.Key_Left: self.centreCoordinate = QPointF( self.mapLayer.centreCoordinate.x(), self.mapLayer.centreCoordinate.y() - self.mapLayer.tileZoomIndex) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_Right: self.centreCoordinate = QPointF( self.mapLayer.centreCoordinate.x(), self.mapLayer.centreCoordinate.y() + self.mapLayer.tileZoomIndex) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_Up: self.centreCoordinate = QPointF( self.mapLayer.centreCoordinate.x() + self.mapLayer.tileZoomIndex, self.mapLayer.centreCoordinate.y()) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_Down: self.centreCoordinate = QPointF( self.mapLayer.centreCoordinate.x() - self.mapLayer.tileZoomIndex, self.mapLayer.centreCoordinate.y()) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_Z: self.zoom *= 1.3 self.mapLayer.updateZoom(self.zoom) if event.key() == Qt.Key_X: self.zoom /= 1.3 self.mapLayer.updateZoom(self.zoom) if event.key() == Qt.Key_P: self.centreCoordinate = QPointF(-32.2138204, 115.0387413) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_A: self.centreCoordinate = QPointF(-35.09138204, 138.07387413) self.mapLayer.updateCentre(self.centreCoordinate) if event.key() == Qt.Key_M: self.centreCoordinate = QPointF(0, 0) self.mapLayer.updateCentre(self.centreCoordinate) self.mapLayer.updateCanvasSize(self.canvasSize)
def mouseMoveEvent(self, e): self.clicked = False item = self.parentItem() if item is None: return p = e.pos() + self.pos() x, y = p.x(), p.y( ) # e.scenePos().x(), e.scenePos().y() # TODO modified 20/02/20 validate if self.rect is not None: x = min(max(x, self.xmin), self.xmax) y = min(max(y, self.ymin), self.ymax) self.setPos(x, y) if self.tangent is not None: controlPoint, contactPoint = self.tangent.controlPoint, self.tangent.contactPoint v = controlPoint - contactPoint contactPoint = QPointF(x, y) self.tangent.contactPoint = contactPoint self.tangent.controlPoint = contactPoint + v self.tangent.setPos(contactPoint) item.fixedPoints.sort(key=lambda p: p.scenePos().x()) item.updatePath()
def updateSource(self): """ sets the pointing window, using self.sourceImage """ # scale img while keeping its aspect ratio # into a QPixmap having the same size than self.layer sourcePixmap = QPixmap.fromImage(self.sourceImage).scaled( self.layer.size(), Qt.KeepAspectRatio) self.sourceSize = sourcePixmap.size() self.sourcePixmap = QPixmap(self.layer.size()) self.sourcePixmap.fill(Qt.black) qp = QPainter(self.sourcePixmap) qp.drawPixmap( QPointF(), sourcePixmap ) # (QRect(0, 0, sourcePixmap.width(), sourcePixmap.height()), sourcePixmap) qp.end() self.sourcePixmapThumb = self.sourcePixmap.scaled( self.pwSize, self.pwSize, aspectMode=Qt.KeepAspectRatio) self.widgetImg.setPixmap(self.sourcePixmapThumb) self.widgetImg.setFixedSize(self.sourcePixmapThumb.size()) self.layer.sourceFromFile = True
def eventFilter(self, source, event): if (event.type() == QEvent.MouseButtonPress or (event.type() == QEvent.MouseMove and event.buttons() == Qt.LeftButton)): self.pos = pos = event.pos() t = atan2(self.cen.y() - pos.y(), pos.x() - self.cen.x()) if self.colWhlPath.contains(pos): # in the color wheel self.chPt = pos #if not self._startedTimer: # self.timer = QTimer() # self.timer.timeout.connect(self.timerSpinner) # self.timer.start(30.303) # self._startedTimer = True # hue -> mouse angle (same as t here) h = (int(degrees(t)) - self.o_ang) * -self.rot_d self.hue = (h if h > 0 else h + 360) % 360 # saturation -> mouse radius (clipped to wheel radius) m_rad = sqrt((self.pos.x() - self.cen.x())**2 + (self.pos.y() - self.cen.y())**2) self.sat = int(255 * min(m_rad / self.cW_rad, 1)) if self.vInArcPath.contains(pos): # in the value selection arc self.vIdAng = t if t > 0 else t + 2 * pi r2 = self.vAoBox.width() / 2.0 x, y = r2 * cos(t) + self.cen.x(), r2 * -sin(t) + self.cen.y() self.vIdCen = QPointF(x, y) self.vIdBox.moveCenter(self.vIdCen) self.value = int(255 * (t - radians(self.e_ang)) / self.ang_w) % 256 self.update() col = QColor() col.setHsv(self.hue, self.sat, self.value) self.currentColorChanged.emit(col) return QWidget.eventFilter(self, source, event)
def __init__(self,scene): QGraphicsView.__init__(self) #Graphics self.scene=scene self.alignment = Qt.Alignment(Qt.AlignVCenter, Qt.AlignHCenter) self.setAlignment(self.alignment) self.itemSelected=False self.mousePressedForRect=False self.mousePressedForPainting=False self.rectItemPressed=False self.ellipseItemPressed=False self.mouseMovedForDrawing=False self.mousePressedForCreatingTemplate=False self.paintEventEnabled=False self.createTemplateEventEnabled=False self.drawRect=False self.advancedMode=False self.rectMoved=False self.rectResized=False self.listOfItems=[] self.pos1 = [0,0] self.pos2 = [0,0] self.viewWidth=0 self.viewHeight=0 self.widthMargin=0 self.heightMargin=0 self.zoomOutFactor=1 self.zoomInFactor=1 self.netZoomFactor=1 self.netDeltaX=0 self.totalDelta=QPointF(0,0) self.delta=0 self.ellipseRadius=10 self.paintingEnabled=False self.createTemplateEnabled=False self.paintingColor=QColor() self.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.TextAntialiasing)
def max_arrow(right_facing): """ Creates a polygon that matches Max's ui Arrow :param right_facing: Bool: True for right facing arrow, false for down facing arrow :return: a QPolygonF """ polygon = QtG.QPolygonF() if right_facing: polygon.append(QPointF(0.0, 0.0)) polygon.append(QPointF(0.0, 12.0)) polygon.append(QPointF(8.0, 6.0)) else: polygon.append(QPointF(0.0, 0.0)) polygon.append(QPointF(12.0, 0.0)) polygon.append(QPointF(6.0, 8.0)) return polygon
def add_from_geojson(self, geojson, color='red'): new_items = [] if not (geojson['type'] == 'FeatureCollection'): return features = geojson['features'] for feature in features: if feature['type'] != 'Feature': continue geometry = feature['geometry'] if geometry['type'] != 'Point': continue coordinate = geometry['coordinates'] new_marker = MarkerItem(QPointF(coordinate[1], coordinate[0]), color=QColor(color), properties=feature['properties']) new_items.append(new_marker) self.beginInsertRows(QModelIndex(), self.rowCount(), self.rowCount() + len(new_items) - 1) self._items.extend(new_items) self.endInsertRows()
def populateScene(self): self.scene = QGraphicsScene(self) image = QImage(":/qt4logo.png") xx: int = 0 nitems: int = 0 for i in range(-11000, 11000, 110): xx += 1 yy: int = 0 for j in range(-7000, 7000, 70): yy += 1 x = (i + 11000) / 22000.0 y = (j + 7000) / 14000.0 color = QColor( image.pixel(int(image.width() * x), int(image.height() * y))) item = Chip(color, xx, yy) item.setPos(QPointF(i, j)) self.scene.addItem(item) nitems += 1
def __init__(self, size, cModel, parent=None): """ @param size: node count in each dim. @param parent: """ super().__init__() self.setParentItem(parent) self.size = size # parent should be the color wheel. step is the unitary coordinate increment # between consecutive nodes in each direction self.step = parent.size / float((self.size - 1)) # set pos relative to parent self.setPos(0, 0) # np.fromiter does not handle dtype object, so we cannot use a generator self.gridNodes = [[activeNode(QPointF(i*self.step, j * self.step), cModel, gridRow=j, gridCol=i, parent=self, grid=self) for i in range(self.size)] for j in range(self.size)] self.drawTrace = False self.drawGrid() self.selectedGroup = None self.setFlag(QGraphicsItem.ItemIsSelectable, True)
def __init__(self, sourceNode=None, destNode=None): super(BezierEdge, self).__init__(QPointF(0, 0)) self.centerCp = BezierPointItem(self, self._m_centerPos, PointType.Center, ItemType.NoneType) self.edge1Cp = BezierPointItem(self, self._edge1, PointType.Edge, ItemType.SourceType) self.edge2Cp = BezierPointItem(self, self._edge2, PointType.Edge, ItemType.DestType) self.beginCp = BezierPointItem(self, self.__sourcePoint, PointType.Special, ItemType.SourceType) self.endCp = BezierPointItem(self, self.__destPoint, PointType.Special, ItemType.DestType) self.textCp = BezierTextItem(self, self._m_textPos, PointType.Text, ItemType.PathType) self.weightCp = BezierTextItem(self, self.weightPos, PointType.Text, ItemType.PathType) self.weightCp.setPlainText("0") self.weightCp.setVisible(False) if sourceNode: self.__source: BezierNode = sourceNode self.__source.addBezierEdge(self, self.beginCp.itemType()) self.__source.setPos(self.specialControlPoints()[0]) if destNode: self.__dest: BezierNode = destNode self.__dest.addBezierEdge(self, self.endCp.itemType()) self.__dest.setPos(self.specialControlPoints()[1]) self._m_pointList.append(self.centerCp) self._m_pointList.append(self.beginCp) self._m_pointList.append(self.edge1Cp) self._m_pointList.append(self.edge2Cp) self._m_pointList.append(self.endCp) self._m_pointList.setRandColor() self._m_pointList.setParentItem(self)
def createFit(self, xy_series, fit_xy_series): #Remove previous data del self.__pts[:] num_pts = xy_series.count() x_data = np.zeros(num_pts) y_data = np.zeros(num_pts) def test_func(x, a, b): return a * np.sin(b * x) for n in range(num_pts): x_data[n] = xy_series.at(n).x() y_data[n] = xy_series.at(n).y() params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[1, 1]) for n in range(num_pts): y_data[n] = test_func(x_data[n], params[0], params[1]) point = QPointF(x_data[n], y_data[n]) self.__pts.append(point) fit_xy_series.replace(self.__pts)
def paint(self, painter, option, widget): #pylint: disable=unused-argument self.update_document() painter.setRenderHints(QPainter.Antialiasing | QPainter.SmoothPixmapTransform | QPainter.HighQualityAntialiasing) painter.setFont(self._config.disasm_font) if self.infodock.is_instruction_selected( self.addr) or self.obj.should_highlight_line: highlight_color = Conf.disasm_view_node_instruction_selected_background_color painter.setBrush(highlight_color) painter.setPen(highlight_color) painter.drawRect(0, 0, self.width, self.height) x = 0 if self._disasm_view.show_address: x += self._addr_item.boundingRect().width( ) + self.GRAPH_ADDR_SPACING painter.translate(QPointF(x, 0)) self._qtextdoc.drawContents(painter)
def setAnchor(self, point): self._anchor = QPointF(point)
class Callout(QGraphicsItem): def __init__(self, chart): QGraphicsItem.__init__(self, chart) self._chart = chart self._text = "" self._textRect = QRectF() self._anchor = QPointF() self._font = QFont() self._rect = QRectF() def boundingRect(self): anchor = self.mapFromParent(self._chart.mapToPosition(self._anchor)) rect = QRectF() rect.setLeft(min(self._rect.left(), anchor.x())) rect.setRight(max(self._rect.right(), anchor.x())) rect.setTop(min(self._rect.top(), anchor.y())) rect.setBottom(max(self._rect.bottom(), anchor.y())) return rect def paint(self, painter, option, widget): path = QPainterPath() path.addRoundedRect(self._rect, 5, 5) anchor = self.mapFromParent(self._chart.mapToPosition(self._anchor)) if not self._rect.contains(anchor) and not self._anchor.isNull(): point1 = QPointF() point2 = QPointF() # establish the position of the anchor point in relation to _rect above = anchor.y() <= self._rect.top() aboveCenter = (anchor.y() > self._rect.top() and anchor.y() <= self._rect.center().y()) belowCenter = (anchor.y() > self._rect.center().y() and anchor.y() <= self._rect.bottom()) below = anchor.y() > self._rect.bottom() onLeft = anchor.x() <= self._rect.left() leftOfCenter = (anchor.x() > self._rect.left() and anchor.x() <= self._rect.center().x()) rightOfCenter = (anchor.x() > self._rect.center().x() and anchor.x() <= self._rect.right()) onRight = anchor.x() > self._rect.right() # get the nearest _rect corner. x = (onRight + rightOfCenter) * self._rect.width() y = (below + belowCenter) * self._rect.height() cornerCase = ((above and onLeft) or (above and onRight) or (below and onLeft) or (below and onRight)) vertical = abs(anchor.x() - x) > abs(anchor.y() - y) x1 = (x + leftOfCenter * 10 - rightOfCenter * 20 + cornerCase * int(not vertical) * (onLeft * 10 - onRight * 20)) y1 = (y + aboveCenter * 10 - belowCenter * 20 + cornerCase * vertical * (above * 10 - below * 20)) point1.setX(x1) point1.setY(y1) x2 = (x + leftOfCenter * 20 - rightOfCenter * 10 + cornerCase * int(not vertical) * (onLeft * 20 - onRight * 10)) y2 = (y + aboveCenter * 20 - belowCenter * 10 + cornerCase * vertical * (above * 20 - below * 10)) point2.setX(x2) point2.setY(y2) path.moveTo(point1) path.lineTo(anchor) path.lineTo(point2) path = path.simplified() painter.setBrush(QColor(255, 255, 255)) painter.drawPath(path) painter.drawText(self._textRect, self._text) def mousePressEvent(self, event): event.setAccepted(True) def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: self.setPos(mapToParent( event.pos() - event.buttonDownPos(Qt.LeftButton))) event.setAccepted(True) else: event.setAccepted(False) def setText(self, text): self._text = text metrics = QFontMetrics(self._font) self._textRect = QRectF(metrics.boundingRect( QRect(0.0, 0.0, 150.0, 150.0),Qt.AlignLeft, self._text)) self._textRect.translate(5, 5) self.prepareGeometryChange() self._rect = self._textRect.adjusted(-5, -5, 5, 5) def setAnchor(self, point): self._anchor = QPointF(point) def updateGeometry(self): self.prepareGeometryChange() self.setPos(self._chart.mapToPosition( self._anchor) + QPointF(10, -50))
def testQPointFToTuple(self): p = QPointF(1, 2) self.assertEqual((1, 2), p.toTuple())