def draw(self, qpainter, zoom=1): """Draw this figure Parameters ---------- qpainter: PySide.QtGui.QPainter """ size_x = self.size_x * zoom size_y = self.size_y * zoom pensize = 3 qpainter.setPen( QtGui.QPen(PipelineDrawer.blue_cta, pensize, QtCore.Qt.SolidLine)) text_pos = QPointF(self.center) text_pos.setX(text_pos.x() - size_x / 2 + 2) text_pos.setY(text_pos.y() + pensize) qpainter.drawText(text_pos, str(self.nb_job_done)) pt = QPointF(self.center) pt.setX(5) pos = self.name.find("$$thread_number$$") if pos != -1: name = self.name[0:pos] else: name = self.name qpainter.drawText(pt, name) if self.running == True: qpainter.setPen( QtGui.QPen(PipelineDrawer.mygreen, 3, QtCore.Qt.SolidLine)) else: qpainter.setPen( QtGui.QPen(PipelineDrawer.blue_cta, 3, QtCore.Qt.SolidLine)) x1 = self.center.x() - (size_x / 2) y1 = self.center.y() - (size_y / 2) qpainter.drawRoundedRect(x1, y1, size_x, size_y, 12.0, 12.0)
def pointAt(self, axes, axis_values): """ Returns the point that best represents this graph information. :param axes | [<XChartAxis>, ..] axis_values | {<str> axisName, <variant> value :return <QPointF> """ point = QPointF() rect = self._buildData.get('axis_rect') if not rect: return point x_range = rect.right() - rect.left() y_range = rect.bottom() - rect.top() for axis in axes: if not axis.name() in axis_values: continue perc = axis.percentAt(axis_values[axis.name()]) if axis.orientation() == Qt.Vertical: point.setY(rect.bottom() - perc * y_range) else: point.setX(rect.left() + perc * x_range) return point
def __init__(self, rect=None): super(TaskGraphicsItem, self).__init__() if rect is not None: self.setRect(rect) self.setPen(QPen(Qt.NoPen)) # Setup the text item self.textItem = QGraphicsTextItem() self.textItem.setParentItem(self) self.textItem.rotate(-90) self.textItem.setDefaultTextColor(QColor(255, 255, 255)) # The dimensions to reach via a LERP. self.startPos = QPointF(0, 0) self.endPos = QPointF(0, 0) self.startDiameter = 1 self.endDiameter = 1 self.centerMark = QGraphicsEllipseItem() self.centerMark.setBrush(QBrush(Qt.white)) self.centerMark.setPen(QPen(Qt.NoPen)) self.centerMark.setParentItem(self) self.pid = -1 # To determine if it is associated with an active process. self.used = False
def __init__(self, head, tail, uuid): QGraphicsObject.__init__(self) if not issubclass(head.__class__, dict) and not isinstance(tail.__class__, dict): raise AttributeError self.setZValue(0.0) self.__kId = uuid self.__head = head self.__tail = tail if head[ENode.kGuiAttributeType].match(EAttribute.kTypeInput): self.__head = tail self.__tail = head self.__head[ENode.kGuiAttributeParent].onMove.connect(self.update) self.__tail[ENode.kGuiAttributeParent].onMove.connect(self.update) self.__headPoint = QPointF(0.0, 0.0) self.__tailPoint = QPointF(0.0, 0.0) self.__pen = QPen(QColor(43, 43, 43), 2, Qt.SolidLine) self.update()
def showMoveHelper(self, visible=True): """show help text In empty HandBoards""" if visible: if not self.__moveHelper: splitter = QGraphicsRectItem(self) hbCenter = self.rect().center() splitter.setRect(hbCenter.x() * 0.5, hbCenter.y(), hbCenter.x() * 1, 1) helpItems = [splitter] for name, yFactor in [(m18n('Move Exposed Tiles Here'), 0.5), (m18n('Move Concealed Tiles Here'), 1.5)]: helper = QGraphicsSimpleTextItem(name, self) helper.setScale(3) nameRect = QRectF() nameRect.setSize(helper.mapToParent(helper.boundingRect()).boundingRect().size()) center = QPointF(hbCenter) center.setY(center.y() * yFactor) helper.setPos(center - nameRect.center()) if self.sceneRotation() == 180: rotateCenter(helper, 180) helpItems.append(helper) self.__moveHelper = self.scene().createItemGroup(helpItems) self.__moveHelper.setVisible(True) else: if self.__moveHelper: self.__moveHelper.setVisible(False)
def foldInput(self, folded): self.element.paramsFolded = folded self.prepareGeometryChange() if self.element.algorithm.outputs: pt = self.getLinkPointForOutput(-1) pt = QPointF(0, pt.y()) self.outButton.position = pt self.update()
def paint(self, painter, option, widget=None): pt = QPointF(-self.WIDTH / 2, -self.HEIGHT / 2) + self.position rect = QRectF(pt.x(), pt.y(), self.WIDTH, self.HEIGHT) if self.isIn: painter.setPen(QPen(Qt.transparent, 1)) painter.setBrush(QBrush(Qt.lightGray, Qt.SolidPattern)) else: painter.setPen(QPen(Qt.transparent, 1)) painter.setBrush(QBrush(Qt.transparent, Qt.SolidPattern)) painter.drawRect(rect) painter.drawPixmap(pt.x(), pt.y(), self.pixmap)
def __getAttributePosition(self, attrType): attr_x_pos = 0 if attrType.match(EAttribute.kTypeOutput): attr_x_pos = self.__titleRect.width() - self.__attrRect.width() rect = self.__attrRect.translated( QPointF(attr_x_pos, self.__out_attr_step)) point = QPointF((rect.topRight() + rect.bottomRight()) / 2) point.setX(point.x() + self.pen().width() * 2) self.__out_attr_step += self.__attrRect.width() + self.pen().width( ) return [rect, point] rect = self.__attrRect.translated( QPointF(attr_x_pos, self.__in_attr_step)) point = QPointF((rect.topLeft() + rect.bottomLeft()) / 2) point.setX(point.x() - self.pen().width() * 2) self.__in_attr_step += self.__attrRect.width() + self.pen().width() return [rect, point]
def movePoints(self, image_name, pt_ids): if image_name == self.image_name: data = self.current_data dm = self.data_manager points = self.points cells = self.cells for pt_id in pt_ids: pos = data[pt_id] pos = QPointF(pos.x() / self.min_scale, pos.y() / self.min_scale) points[pt_id].setPos(pos) for cid in dm.cell_points[pt_id]: cell = cells.get(cid, None) if cell is not None and cell.isVisible(): cell.setGeometry()
def beginDrawing(self, pos, sliceRect): self.sliceRect = sliceRect self.scene.clear() self.bb = QRect() self.pos = QPointF(pos.x()+0.0001, pos.y()+0.0001) line = self.moveTo(pos) return line
def mousePressEvent(self, event): if event.button() == Qt.MidButton: self.setCursor(QCursor(Qt.SizeAllCursor)) self._lastPanPoint = event.pos() self._crossHairCursor.setVisible(False) self._dragMode = True if self._ticker.isActive(): self._deltaPan = QPointF(0, 0) if event.buttons() == Qt.RightButton: #make sure that we have the cursor at the correct position #before we call the context menu self.mouseMoveEvent(event) self.customContextMenuRequested.emit(event.pos()) return if not self.drawingEnabled: print "ImageView2D.mousePressEvent: drawing is not enabled" return if event.buttons() == Qt.LeftButton: #don't draw if flicker the view if self._ticker.isActive(): return if QApplication.keyboardModifiers() == Qt.ShiftModifier: self.erasingToggled.emit(True) self._tempErase = True mousePos = self.mapToScene(event.pos()) self.beginDrawing(mousePos)
def __init__(self, parent): QDial.__init__(self, parent) self.m_pixmap = QPixmap(":/bitmaps/dial_01d.png") self.m_pixmap_n_str = "01" self.m_custom_paint = 0 self.m_hovered = False self.m_hover_step = self.HOVER_MIN if self.m_pixmap.width() > self.m_pixmap.height(): self.m_orientation = self.HORIZONTAL else: self.m_orientation = self.VERTICAL self.m_label = "" self.m_label_pos = QPointF(0.0, 0.0) self.m_label_width = 0 self.m_label_height = 0 self.m_label_gradient = QLinearGradient(0, 0, 0, 1) if self.palette().window().color().lightness() > 100: # Light background self.m_color1 = QColor(100, 100, 100, 255) self.m_color2 = QColor(0, 0, 0, 0) self.m_colorT = [self.palette().text().color(), self.palette().mid().color()] else: # Dark background self.m_color1 = QColor(0, 0, 0, 255) self.m_color2 = QColor(0, 0, 0, 0) self.m_colorT = [Qt.white, Qt.darkGray] self.updateSizes()
def path_link_disabled(basepath): """ Return a QPainterPath 'styled' to indicate a 'disabled' link. A disabled link is displayed with a single disconnection symbol in the middle (--||--) Parameters ---------- basepath : QPainterPath The base path (a simple curve spine). Returns ------- path : QPainterPath A 'styled' link path """ segmentlen = basepath.length() px = 5 if segmentlen < 10: return QPainterPath(basepath) t = (px / 2) / segmentlen p1, _ = qpainterpath_simple_split(basepath, 0.50 - t) _, p2 = qpainterpath_simple_split(basepath, 0.50 + t) angle = -basepath.angleAtPercent(0.5) + 90 angler = math.radians(angle) normal = QPointF(math.cos(angler), math.sin(angler)) end1 = p1.currentPosition() start2 = QPointF(p2.elementAt(0).x, p2.elementAt(0).y) p1.moveTo(start2.x(), start2.y()) p1.addPath(p2) def QPainterPath_addLine(path, line): path.moveTo(line.p1()) path.lineTo(line.p2()) QPainterPath_addLine(p1, QLineF(end1 - normal * 3, end1 + normal * 3)) QPainterPath_addLine(p1, QLineF(start2 - normal * 3, start2 + normal * 3)) return p1
def __init__( self, scene ): self._visible = True super(XNodeConnection, self).__init__() # define custom properties self._textItem = None self._polygons = [] self._style = XConnectionStyle.Linear self._padding = 20 self._squashThreshold = 2 * scene.cellWidth() self._showDirectionArrow = False self._highlightPen = QPen(QColor('yellow')) self._disabledPen = QPen(QColor(100, 100, 100)) self._disableWithLayer = False self._enabled = True self._dirty = True self._customData = {} self._layer = None self._font = QApplication.instance().font() self._text = '' self._inputNode = None self._inputFixedY = None self._inputFixedX = None self._inputPoint = QPointF() self._inputLocation = XConnectionLocation.Left self._autoCalculateInputLocation = False self._showInputArrow = False self._outputNode = None self._outputFixedX = None self._outputFixedY = None self._outputPoint = QPointF() self._outputLocation = XConnectionLocation.Right self._autoCalculateOutputLocation = False self._showOutputArrow = False # set standard properties self.setFlags( self.ItemIsSelectable ) self.setZValue(-1) self.setPen( QColor('white') ) self.setLayer( scene.currentLayer() )
def __init__(self, raw=None, map=None, enabled=True): self._raw = QPointF() self._map = QgsPoint() self._local = QPointF() self._enabled = True self.setRaw(raw) self.setMap(map) self.setEnabled(enabled)
def beginDrawing(self, pos, sliceRect): ''' pos -- QPointF-like ''' self.sliceRect = sliceRect self.scene.clear() self.bb = QRect() self.pos = QPointF(pos.x(), pos.y()) self._hasMoved = False
def paint(self, painter, option, widget=None): myPen = self.pen() myPen.setColor(self.myColor) painter.setPen(myPen) painter.setBrush(self.myColor) controlPoints = [] endPt = self.endItem.getLinkPointForParameter(self.endIndex) startPt = self.startItem.getLinkPointForOutput(self.startIndex) if isinstance(self.startItem.element, Algorithm): if self.startIndex != -1: controlPoints.append(self.startItem.pos() + startPt) controlPoints.append(self.startItem.pos() + startPt + QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt) pt = QPointF(self.startItem.pos() + startPt + QPointF(-3, -3)) painter.drawEllipse(pt.x(), pt.y(), 6, 6) pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3)) painter.drawEllipse(pt.x(), pt.y(), 6, 6) else: # Case where there is a dependency on an algorithm not # on an output controlPoints.append(self.startItem.pos() + startPt) controlPoints.append(self.startItem.pos() + startPt + QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt) else: controlPoints.append(self.startItem.pos()) controlPoints.append(self.startItem.pos() + QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt - QPointF(ModelerGraphicItem.BOX_WIDTH / 2, 0)) controlPoints.append(self.endItem.pos() + endPt) pt = QPointF(self.endItem.pos() + endPt + QPointF(-3, -3)) painter.drawEllipse(pt.x(), pt.y(), 6, 6) path = QPainterPath() path.moveTo(controlPoints[0]) path.cubicTo(*controlPoints[1:]) painter.strokePath(path, painter.pen()) self.setPath(path)
def beginDrawing(self, pos, shape): self.shape = shape self.bb = QRectF(0, 0, self.shape[0], self.shape[1]) self.scene.clear() if self.erasing: self.penVis.setColor(self.erasingColor) else: self.penVis.setColor(self.drawColor) self.pos = QPointF(pos.x()+0.0001, pos.y()+0.0001) line = self.moveTo(pos) return line
def beginDrawing(self, pos, shape): print "BrushingModel.beginDrawing(pos=%r, shape=%r)" % (pos, shape) self.shape = shape self.scene.clear() self.bb = QRect() if self.erasing: self.penVis.setColor(self.erasingColor) else: self.penVis.setColor(self.drawColor) self.pos = QPointF(pos.x()+0.0001, pos.y()+0.0001) line = self.moveTo(pos) return line
def drawArrow(self, paint, x1, y1, x2, y2): m = paint.worldMatrix() paint.translate(x1,y1) pi = 3.1415926 if abs(x2 - x1) > 0: alpha = math.atan(abs(y2-y1)/abs(x2-x1)) * 180 / pi else: alpha = 90 if y2 > y1: if x2 > x1: paint.rotate(alpha) else: paint.rotate(180-alpha) else: if x2 > x1: paint.rotate(-alpha) else: paint.rotate(alpha-180) endcoord = math.sqrt((x2-x1)**2 + (y2-y1)**2) p1 = QPointF(endcoord , 0) paint.drawLine(0, 0, p1.x(), 0) paint.setWorldMatrix(m)
def updateSmooth(self): if self.m_smooth: if self.m_cursor.x() != self.m_smooth_x or self.m_cursor.y() != self.m_smooth_y: if abs(self.m_cursor.x() - self.m_smooth_x) <= 0.001: self.m_smooth_x = self.m_cursor.x() return elif abs(self.m_cursor.y() - self.m_smooth_y) <= 0.001: self.m_smooth_y = self.m_cursor.y() return new_x = (self.m_smooth_x + self.m_cursor.x() * 3) / 4 new_y = (self.m_smooth_y + self.m_cursor.y() * 3) / 4 pos = QPointF(new_x, new_y) self.m_cursor.setPos(pos) self.m_lineH.setY(pos.y()) self.m_lineV.setX(pos.x()) xp = pos.x() / (self.p_size.x() + self.p_size.width()) yp = pos.y() / (self.p_size.y() + self.p_size.height()) self.sendMIDI(xp, yp) self.emit(SIGNAL("cursorMoved(double, double)"), xp, yp)
def __init__(self, head, tail, uuid, arrowed=False): QGraphicsObject.__init__(self) self.__arrowed = arrowed if not issubclass(head.__class__, dict) and not isinstance(tail.__class__, dict): raise AttributeError self.setZValue(0.0) self.__kId = uuid self.__head = head self.__tail = tail self.__path = QPainterPath() self.__headPoint = QPointF(0.0, 0.0) self.__tailPoint = QPointF(0.0, 0.0) self.__head[ENode.kGuiAttributeParent].onMove.connect(self.update) self.__tail[ENode.kGuiAttributeParent].onMove.connect(self.update) self.__pen = QPen(QColor(43, 43, 43), 2, Qt.SolidLine) self.update()
def eventFilter(self, _, event): if event.type() == QEvent.MouseButtonRelease: x = self.invTransform(Qwt.QwtPlot.xBottom, event.pos().x()) y = self.invTransform(Qwt.QwtPlot.yLeft, event.pos().y()) self.lastClickCoordinates = QPointF(x, y) elif event.type() == QEvent.MouseMove: x = self.invTransform(Qwt.QwtPlot.xBottom, event.pos().x()) y = self.invTransform(Qwt.QwtPlot.yLeft, event.pos().y()) coords = QPointF(x, y) if self.picker.isActive() and self.lastClickCoordinates is not None: toolTip = 'origin x: %.5f, y: %.5f' % (self.lastClickCoordinates.x(), self.lastClickCoordinates.y()) delta = coords - self.lastClickCoordinates toolTip += '\ndelta x: %.5f, y: %.5f\nlength: %.5f' % (delta.x(), delta.y(), math.sqrt(delta.x() ** 2 + delta.y() ** 2)) else: toolTip = 'buttons\nleft: measure\nmiddle: move\nright: zoom x/y\nwheel: zoom y' self.setToolTip(toolTip) self.mouseCoordinatesChanged.emit(coords) return False
def __init__(self, element, model): super(ModelerGraphicItem, self).__init__(None, None) self.model = model self.element = element if isinstance(element, ModelerParameter): icon = QIcon(os.path.join(pluginPath, 'images', 'input.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.param.description elif isinstance(element, ModelerOutput): # Output name icon = QIcon(os.path.join(pluginPath, 'images', 'output.png')) self.pixmap = icon.pixmap(20, 20, state=QIcon.On) self.text = element.description else: self.text = element.description self.pixmap = element.algorithm.getIcon().pixmap(15, 15) self.arrows = [] self.setFlag(QGraphicsItem.ItemIsMovable, True) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setZValue(1000) if not isinstance(element, ModelerOutput): icon = QIcon(os.path.join(pluginPath, 'images', 'edit.png')) pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, ModelerGraphicItem.BOX_HEIGHT / 2 - FlatButtonGraphicItem.HEIGHT / 2 + 1) self.editButton = FlatButtonGraphicItem(icon, pt, self.editElement) self.editButton.setParentItem(self) icon = QIcon(os.path.join(pluginPath, 'images', 'delete.png')) pt = QPointF(ModelerGraphicItem.BOX_WIDTH / 2 - FlatButtonGraphicItem.WIDTH / 2, - ModelerGraphicItem.BOX_HEIGHT / 2 + FlatButtonGraphicItem.HEIGHT / 2 + 1) self.deleteButton = FlatButtonGraphicItem(icon, pt, self.removeElement) self.deleteButton.setParentItem(self) if isinstance(element, Algorithm): alg = element.algorithm if alg.parameters: pt = self.getLinkPointForParameter(-1) pt = QPointF(0, pt.y() + 2) self.inButton = FoldButtonGraphicItem(pt, self.foldInput, self.element.paramsFolded) self.inButton.setParentItem(self) if alg.outputs: pt = self.getLinkPointForOutput(-1) pt = QPointF(0, pt.y() + 2) self.outButton = FoldButtonGraphicItem(pt, self.foldOutput, self.element.outputsFolded) self.outButton.setParentItem(self)
def draw(self, qpainter, zoom=1): """Draw this figure Parameters ---------- qpainter: PySide.QtGui.QPainter """ size_x = self.size_x * zoom size_y = self.size_y * zoom pensize = 3 qpainter.setPen( QtGui.QPen(QtCore.Qt.black, pensize, QtCore.Qt.SolidLine)) qpainter.drawEllipse(self.center, size_x / 2, size_y / 2) text_pos = QPointF(self.center) text_pos.setX(text_pos.x() - size_x / 2 + 10) text_pos.setY(text_pos.y() + pensize) qpainter.drawText(text_pos, str(self.queue_size)) qpainter.setPen( QtGui.QPen(PipelineDrawer.blue_cta, 3, QtCore.Qt.SolidLine))
def __init__(self, type_, values, duration): '''CTOR @param type_: string, must be in supported types @param values: list of values of variable @param duration: integer, holds stepwidth of wave ''' QtGui.QGraphicsScene.__init__(self) self.supportedTypes = ["bool", "int", "float", "double"] self.vSpace = 10 self.values = [] self.curPos = QPointF(0, 2) self.type = type_ self.width = duration self.valFont = QtGui.QFont("Arial", 7) self.valFontColor = QtGui.QColor() self.valFontColor.setGreen(100) self.setSceneRect(0, 0, self.width, 15) for v in values: self.appendValue(v, duration)
def mouseMoveEvent(self,event): if self._dragMode == True: #the mouse was moved because the user wants to change #the viewport self._deltaPan = QPointF(event.pos() - self._lastPanPoint) self._panning() self._lastPanPoint = event.pos() return if self._ticker.isActive(): #the view is still scrolling #do nothing until it comes to a complete stop return self.mousePos = mousePos = self.mapToScene(event.pos()) x = self.x = mousePos.x() y = self.y = mousePos.y() self.mouseMoved.emit(x,y) if self._isDrawing: self.drawing.emit(mousePos)
def drawData(self, painter, size, angle, dataname, color): """ Draw data @param painter: @type painter: @param size: @type size: @param angle: @type angle: @param dataname: @type dataname: @param color: @type color: """ col1 = QColor(color) col2 = QColor(color) col3 = QColor(color) col1 = col1.lighter(105) col2 = col1.darker(140) col3 = col3.darker() gradient = QRadialGradient( QPointF(size.width() / 2, size.height() / 2), size.width() / 2 - 20) gradient.setColorAt(0.0, col1) gradient.setColorAt(0.6, col2) gradient.setColorAt(1.0, col3) painter.setPen(Qt.NoPen) painter.setBrush(gradient) painter.drawPie(QRect(20, 20, size.width() - 40, size.height() - 40), self.__startAngle, angle) self.__startAngle = self.__startAngle + angle
def __init__(self, parent=None): GraphicsPathObject.__init__(self, parent) assert (isinstance(parent, NodeItem)) self.__processingState = 0 self.__progress = -1 self.__animationEnabled = False self.__isSelected = False self.__hasFocus = False self.__hover = False self.__shapeRect = QRectF(-10, -10, 20, 20) self.setAcceptHoverEvents(True) self.setFlag(QGraphicsItem.ItemSendsScenePositionChanges, True) self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True) self.setPen(QPen(Qt.NoPen)) self.setPalette(default_palette()) self.shadow = QGraphicsDropShadowEffect( blurRadius=3, color=QColor(SHADOW_COLOR), offset=QPointF(0, 0), ) self.setGraphicsEffect(self.shadow) self.shadow.setEnabled(True) self.__blurAnimation = QPropertyAnimation(self.shadow, "blurRadius", self) self.__blurAnimation.setDuration(100) self.__blurAnimation.finished.connect(self.__on_finished) self.__pingAnimation = QPropertyAnimation(self, "scale", self) self.__pingAnimation.setDuration(250) self.__pingAnimation.setKeyValues([(0.0, 1.0), (0.5, 1.1), (1.0, 1.0)])
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25*10, 25*10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25*10-30) path = QPainterPath() path.addText(QPointF(50, 25*10-50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20,20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = DelayedSpinBox(750) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def boundingRect(self): parent = self._parent x, y = parent.x, parent.y width, height = parent._width, parent._height pen_width_in_view = parent.thick_width # This is a little tricky. The line is always drawn with the same # absolute thickness, REGARDLESS of the view's transform. # That is, the line does not appear to be part of the data, # so it doesn't get thinner as we zoom out. # To compensate for this when determining the line's bounding box within the scene, # we need to know the transform used by the view that is showing this scene. # If we didn't do this, our bounding rect would be off by a few pixels. # That probably wouldn't be a big deal. view = self.scene().views()[0] inverted_transform, has_inverse = view.transform().inverted() transformed_pen_thickness = inverted_transform.map( QPointF(pen_width_in_view, pen_width_in_view) ) pen_width_in_scene = transformed_pen_thickness.x() if self._direction == 'horizontal': return self.scene().data2scene.mapRect( QRectF( 0, y - pen_width_in_scene/2.0, width, pen_width_in_scene ) ) else: return self.scene().data2scene.mapRect( QRectF( x - pen_width_in_scene/2.0, 0, pen_width_in_scene, height ) )
def lonLatFromPos(self, x, y): """Position in WGS84 coordinate of the scene coordinates. Convert from scene reference system to WGS84 reference system. Args: x(float, int or numpy.ndarray): X value or values. y(float, int or numpy.ndarray): Y value or values. Returns: If input data is float, QPointF with the coordinate of the input position. If input data is array, tuple of numpy.ndarray (x, y) with the coordinates of the input positions. """ tdim = float(self._tileSource.tileSize()) tx = x / tdim ty = y / tdim zn = 1 << self._zoom lon = tx / zn * 360.0 - 180.0 n = PI - PI2 * ty / zn lat = PI_div_180_inv * arctan(0.5 * (exp(n) - exp(-n))) if isinstance(lon, float): return QPointF(lon, lat) return (lon, lat)
def __init__(self, parent): QGraphicsPathItem.__init__(self, parent) if not isinstance(parent, LinkItem): raise TypeError("'LinkItem' expected") self.setAcceptedMouseButtons(Qt.NoButton) self.__canvasLink = parent self.setAcceptHoverEvents(True) self.shadow = QGraphicsDropShadowEffect( blurRadius=10, color=QColor(SHADOW_COLOR), offset=QPointF(0, 0) ) self.normalPen = QPen(QBrush(QColor("#9CACB4")), 2.0) self.hoverPen = QPen(QBrush(QColor("#7D7D7D")), 2.1) self.setPen(self.normalPen) self.setGraphicsEffect(self.shadow) self.shadow.setEnabled(False) self.__hover = False self.__enabled = True self.__shape = None
def anchor_rect(rect, anchor_pos, anchor_h=Qt.AnchorHorizontalCenter, anchor_v=Qt.AnchorVerticalCenter): if anchor_h == Qt.AnchorLeft: x = anchor_pos.x() elif anchor_h == Qt.AnchorHorizontalCenter: x = anchor_pos.x() - rect.width() / 2 elif anchor_h == Qt.AnchorRight: x = anchor_pos.x() - rect.width() else: raise ValueError(anchor_h) if anchor_v == Qt.AnchorTop: y = anchor_pos.y() elif anchor_v == Qt.AnchorVerticalCenter: y = anchor_pos.y() - rect.height() / 2 elif anchor_v == Qt.AnchorBottom: y = anchor_pos.y() - rect.height() else: raise ValueError(anchor_v) return QPointF(x, y)
def __init__(self, screen, num_particles, pos, pos_irange, vel, vel_irange, duration, duration_irange, color_seq, quad_sz, img_path): self.screen = screen self.num_particles = num_particles self.setup_texture(img_path) #self.setup_display_list(quad_sz) self.particles = set() rect = QRectF(0.,0.,quad_sz,quad_sz) rect.moveCenter(QPointF(0.,0.)) for i in xrange(self.num_particles): pos = apply_irange(pos, pos_irange) vel = apply_irange(vel, vel_irange) duration = duration + uniform(*duration_irange) #p = Particle(pos, vel, color_seq, self.display_list, duration) p = Particle(pos, vel, color_seq, (self.texture, rect, self.screen.qpainter), duration) self.particles.add(p)
def xsectLineRect1(l, r): """Find the first intersection point of a line segment and a rectangle. l -- QLineF r -- QRectF This algo assumes one line end point is INSIDE the rectangle. Return a QPointF() """ rt = l.BoundedIntersection rp = QPointF() # left if l.intersect(QLineF(r.topLeft(), r.bottomLeft()), rp) == rt: return rp # top elif l.intersect(QLineF(r.topLeft(), r.topRight()), rp) == rt: return rp # right elif l.intersect(QLineF(r.topRight(), r.bottomRight()), rp) == rt: return rp # bottom elif l.intersect(QLineF(r.bottomRight(), r.bottomLeft()), rp) == rt: return rp
def distToLine(pt, p1, p2): """ Compute the distance from the point `pt` to the line segment [p1,p2] """ u = p2-p1 lu = u.x()*u.x() + u.y()*u.y() pmax = QPointF(max(abs(p1.x()), abs(p2.x())), max(abs(p1.y()), abs(p2.y()))) if lu / (pmax.x()*pmax.x() + pmax.y()*pmax.y()) < 1e-10: diff = u - p1 return sqrt(diff.x()*diff.x() + diff.y()*diff.y()) dp = pt-p1 proj = (u.x()*dp.x() + u.y()*dp.y()) if proj >= 0 and proj <= lu: return abs(dp.x()*u.y() - u.x()*dp.y())/sqrt(lu) elif proj < 0: return dp.x()*dp.x() + dp.y()*dp.y() else: return dist(pt, p2)
def paint(self, painter, option, widget): painter.save() dirtyColor = QColor(255, 0, 0) painter.setOpacity(0.5) painter.setBrush(QBrush(dirtyColor, Qt.SolidPattern)) painter.setPen(dirtyColor) intersected = self._tiling.intersected(option.exposedRect) #print "pies are painting at ", option.exposedRect progress = 0.0 for i in intersected: progress += self._indicate[i] if not (self._indicate[i] < 1.0): # only paint for less than 100% progress continue # Don't show unless a delay time has passed since the tile progress was reset. delta = datetime.datetime.now() - self._zeroProgressTimestamp[i] if delta < self.delay: t = QTimer.singleShot(int(delta.total_seconds() * 1000.0), self.update) continue p = self._tiling.tileRectFs[i] w, h = p.width(), p.height() r = min(w, h) rectangle = QRectF(p.center() - QPointF(r / 4, r / 4), QSizeF(r / 2, r / 2)) startAngle = 0 * 16 spanAngle = min(360 * 16, int((1.0 - self._indicate[i]) * 360.0) * 16) painter.drawPie(rectangle, startAngle, spanAngle) painter.restore()
def __drawLine(self, value, duration, printvalue=True): ''' Draws a line depending on the type of the waveform. @param value: value to add to wave @param duration: integer, defines duration(length) of value in wave @param printvalue: bool, add values to waveform (for value-type waveforms only) ''' self.width = self.width + duration tmp = self.curPos self.curPos = QPointF(self.curPos.x() + duration, self.curPos.y()) if self.type == "bool": if value: self.addItem(QtGui.QGraphicsLineItem(QLineF(tmp, self.curPos))) else: self.addItem(QtGui.QGraphicsLineItem(tmp.x(), tmp.y() + self.vSpace, self.curPos.x(), self.curPos.y() + self.vSpace)) elif self.type in self.supportedTypes: if printvalue: text = QtGui.QGraphicsTextItem(str(value)) text.setFont(self.valFont) text.setDefaultTextColor(self.valFontColor) text.setPos(QPointF(tmp.x() + 4, tmp.y() - 5)) self.addItem(text) self.addItem(QtGui.QGraphicsLineItem(QLineF(tmp, self.curPos))) self.addItem(QtGui.QGraphicsLineItem(tmp.x(), tmp.y() + self.vSpace, self.curPos.x(), self.curPos.y() + self.vSpace))
def calcLineRectIntersection(rect, centerLine): ''' checking which side of rectangle intersect with centerLine \ Here the 1. a. intersect point between center and 4 sides of src and \ b. intersect point between center and 4 sides of des and \ to draw a line connecting for src & des 2. angle for src for the arrow head calculation is returned ''' x = rect.x() y = rect.y() w = rect.width() h = rect.height() borders = [(x,y,x+w,y), (x+w,y,x+w,y+h), (x+w,y+h,x,y+h), (x,y+h,x,y)] intersectionPoint = QPointF() intersects = False for lineEnds in borders: line = QLineF(*lineEnds) intersectType = centerLine.intersect(line, intersectionPoint) if intersectType == centerLine.BoundedIntersection: intersects = True break return (intersects, intersectionPoint)
def loadGcpFile(path): inFile = QFile(path) if (not inFile.open(QIODevice.ReadOnly | QIODevice.Text)): return 'ERROR: Unable to open GCP file for reading' inStream = QTextStream(inFile) line = inStream.readLine() # Skip the header line if found if (line == 'mapX,mapY,pixelX,pixelY,enable'): line = inStream.readLine() lines = 0 gc = Transform() while (line): lines += 1 vals = line.split(',') if (len(vals) != 5): return None map = QgsPoint(float(vals[0]), float(vals[1])) raw = QPointF(float(vals[2]), float(vals[3])) enabled = bool(vals[4]) point = GroundControlPoint(raw, map, enabled) gc.setPoint(lines, point) line = inStream.readLine() inFile.close() return gc
def __init__(self, graph, scene): QGraphicsObject.__init__(self) if scene: scene.addItem(self) self.graph = graph self.curves = [] self.items = {} self.attributes = [] self.point_attrs = {} self.point_vals = {} self.default_values = { PointColor: Qt.black, PointSize: 8, PointSymbol: OWPoint.Ellipse } self.box_rect = QRectF() self.setFiltersChildEvents(True) self.setFlag(self.ItemHasNoContents, True) self.mouse_down = False self._orientation = Qt.Vertical self.max_size = QSizeF() self._floating = True self._floating_animation = None self._mouse_down_pos = QPointF()
def paintEvent(self, _): painter = QStylePainter(self) options = QStyleOptionToolBar() # init style options options.initFrom(self.dock) options.rect = self.rect() textRect = self.rect().adjusted(3, 3, 0, 0) msh = self.minimumSizeHint() # need to rotate if vertical state if self.dock.features() & QDockWidget.DockWidgetVerticalTitleBar: painter.rotate(-90) painter.translate(QPointF(-self.rect().height(), 0)) self.transposeSize(options.rect) self.transposeSize(textRect) msh.transpose() # draw toolbar painter.drawControl(QStyle.CE_ToolBar, options) # restore rotation if self.dock.features() & QDockWidget.DockWidgetVerticalTitleBar: painter.rotate(90)
def paint(self, painter, option, widget): dirtyColor = QColor(255,0,0) painter.setOpacity(0.5) painter.save() painter.setBrush(QBrush(dirtyColor, Qt.SolidPattern)) painter.setPen(dirtyColor) for i,p in enumerate(self._tiling.tileRectFs): if self._indicate[i] == 1.0: continue # Don't show unless 1000 millisecs have passed since the tile progress was reset. startTime = self._zeroProgressTimestamp[i] if startTime is not None and datetime.datetime.now() - startTime < datetime.timedelta(milliseconds=1000): continue w,h = p.width(), p.height() r = min(w,h) rectangle = QRectF(p.center()-QPointF(r/4,r/4), QSizeF(r/2, r/2)); startAngle = 0 * 16 spanAngle = min(360*16, int((1.0-self._indicate[i])*360.0) * 16) painter.drawPie(rectangle, startAngle, spanAngle) painter.restore()
def _dendrogram_geom_changed(self): pos = self.dendrogram.pos_at_height(self.cutoff_height) geom = self.dendrogram.geometry() crect = self.dendrogram.contentsRect() self._set_slider_value(pos.x(), geom.width()) self.cut_line.setLength(geom.height()) self.top_axis.resize(crect.width(), self.top_axis.height()) self.top_axis.setPos(geom.left() + crect.left(), 0) self.top_axis.line.setPos(self.cut_line.scenePos().x(), 0) self.bottom_axis.resize(crect.width(), self.bottom_axis.height()) self.bottom_axis.setPos(geom.left() + crect.left(), 0) self.bottom_axis.line.setPos(self.cut_line.scenePos().x(), 0) geom = self._main_graphics.geometry() assert geom.topLeft() == QPointF(0, 0) self.scene.setSceneRect(geom) geom.setHeight(self.top_axis.size().height()) self.top_axis.scene().setSceneRect(geom) self.bottom_axis.scene().setSceneRect(geom)
def __init__(self, parent): QDial.__init__(self, parent) self.fPixmap = QPixmap("./bitmaps/dial_01d.png") self.fPixmapNum = "01" self.fCustomPaint = self.CUSTOM_PAINT_NULL self.fHovered = False self.fHoverStep = self.HOVER_MIN if self.fPixmap.width() > self.fPixmap.height(): self.fOrientation = self.HORIZONTAL else: self.fOrientation = self.VERTICAL self.fLabel = "" self.fLabelPos = QPointF(0.0, 0.0) self.fLabelFont = QFont() self.fLabelFont.setPointSize(6) self.fLabelWidth = 0 self.fLabelHeight = 0 self.fLabelGradient = QLinearGradient(0, 0, 0, 1) if self.palette().window().color().lightness() > 100: # Light background c = self.palette().dark().color() self.fColor1 = c self.fColor2 = QColor(c.red(), c.green(), c.blue(), 0) self.fColorT = [self.palette().buttonText().color(), self.palette().mid().color()] else: # Dark background self.fColor1 = QColor(0, 0, 0, 255) self.fColor2 = QColor(0, 0, 0, 0) self.fColorT = [Qt.white, Qt.darkGray] self.updateSizes()
def mapFromChart(self, x, y): """ Maps a chart point to a pixel position within the grid based on the rulers. :param x | <variant> y | <variant> :return <QPointF> """ grid = self.gridRect() hruler = self.horizontalRuler() vruler = self.verticalRuler() xperc = hruler.percentAt(x) yperc = vruler.percentAt(y) xoffset = grid.width() * xperc yoffset = grid.height() * yperc xpos = grid.left() + xoffset ypos = grid.bottom() - yoffset return QPointF(xpos, ypos)
def resetOffset(self, constrainAxis, rect=None): #self._parent=self.parentItem() if rect == None: rect = self._rect if constrainAxis == 0: if rect.bottom() > 0: self._offset = ((rect.left() + rect.right()) / 2.0, rect.bottom()) else: self._offset = ((rect.left() + rect.right()) / 2.0, rect.top()) elif constrainAxis == 1: if rect.right() > 0: self._offset = (rect.right(), (rect.top() + rect.bottom()) / 2.0) else: self._offset = (rect.left(), (rect.top() + rect.bottom()) / 2.0) #self._offset = ( sel, self.shape[0] ) #print "Resetting ",self._offset self.setPos(QPointF(*self._offset)) self._rect = rect
def paintEvent(self, event): # TODO: Use QPainter.drawPixmapFragments on Qt 4.7 opt = QStyleOption() opt.initFrom(self) pixmap = self.__shadowPixmap shadow_rect = QRectF(opt.rect) widget_rect = QRectF(self.widget().geometry()) widget_rect.moveTo(self.radius_, self.radius_) left = top = right = bottom = self.radius_ pixmap_rect = QRectF(QPointF(0, 0), QSizeF(pixmap.size())) # Shadow casting rectangle in the source pixmap. pixmap_shadow_rect = pixmap_rect.adjusted(left, top, -right, -bottom) source_rects = self.__shadowPixmapFragments(pixmap_rect, pixmap_shadow_rect) target_rects = self.__shadowPixmapFragments(shadow_rect, widget_rect) painter = QPainter(self) for source, target in zip(source_rects, target_rects): painter.drawPixmap(target, pixmap, source) painter.end()
def paint(self, painter, option, widget): """Draw the neck. The base class draws the neck geometry. This function draws any marked notes. Return None. """ super(Neck, self).paint(painter, option, widget) for string, fret, root in self.markedNotes: if root: # mark root notes different color painter.setBrush(QBrush(QColor(255, 0, 0))) painter.setPen(QColor(255, 0, 0)) else: painter.setBrush(QBrush(QColor(0, 0, 0))) painter.setPen(QColor(0, 0, 0)) if fret == 0: # special case for open notes x = self.openX else: x = (self.fretXs[fret-1] + self.fretXs[fret]) / 2.0 r = self.markerDia / 2.0 painter.drawEllipse(QPointF(x, self.stringYs[string]), r, r)
def add_node(self, node): """ Add and return a default constructed :class:`.NodeItem` for a :class:`SchemeNode` instance `node`. If the `node` is already in the scene do nothing and just return its item. """ if node in self.__item_for_node: # Already added return self.__item_for_node[node] item = self.new_node_item(node.description) if node.position: pos = QPointF(*node.position) item.setPos(pos) item.setTitle(node.title) item.setProcessingState(node.processing_state) item.setProgress(node.progress) for message in node.state_messages(): item.setStateMessage(message) item.setStatusMessage(node.status_message()) self.__item_for_node[node] = item node.position_changed.connect(self.__on_node_pos_changed) node.title_changed.connect(item.setTitle) node.progress_changed.connect(item.setProgress) node.processing_state_changed.connect(item.setProcessingState) node.state_message_changed.connect(item.setStateMessage) node.status_message_changed.connect(item.setStatusMessage) return self.add_node_item(item)
def add(self): # add ruller to the path of the scene if self.path_item is not None: self.scene.removeItem(self.path_item) self.path = QtGui.QPainterPath(self.p1) #self.path.closeSubpath() self.path.moveTo(self.p1) self.path.lineTo(self.p2) #print 'self.p1', self.p1 #print 'self.p2', self.p2 for v in self.labels: pv = QPointF(v, self.vort) if self.horiz else QPointF(self.vort, v) self.path.moveTo(pv) self.path.lineTo(pv + self.dt1) # add path with ruler lines to scene self.lst_of_items = [] self.path_item = self.scene.addPath(self.path, self.pen, self.brush) self.path_item.setZValue(self.zvalue) self.lst_of_items.append(self.path_item) #print 'path_item is created' r = self.rect w, h = r.width(), r.height() # add labels to scene for v in self.labels: pv = QPointF(v, self.vort) if self.horiz else QPointF(self.vort, v) vstr = self.fmt % v pt = pv + self.dtxt + QPointF(self.hoff*len(vstr),0)\ + QPointF(self.txtoff_hfr*h, self.txtoff_vfr*h) txtitem = self.scene.addText(vstr, self.font) txtitem.setDefaultTextColor(self.color) txtitem.moveBy(pt.x(), pt.y()) txtitem.setFlag(QtGui.QGraphicsItem.ItemIgnoresTransformations, True) txtitem.setZValue(self.zvalue) self.lst_of_items.append(txtitem)
def _test_gridfunc(o, ge, image_width, image_height): id1, id2 = 1, 2 length_base = image_height # define raster points p1 = QPointF(0., 0.) p2 = QPointF(image_width / 2., 0.) p3 = QPointF(image_width, 0.) p4 = QPointF(0., image_height) p5 = QPointF(image_width / 2., image_height) p6 = QPointF(image_width, image_height) # generate edges middle_edge = ge.init_edge(QLineF(p2, p5), length_base) # piece1 p = QPainterPath() p.moveTo(p1) ge.add_plug_to_path( p, ge.init_edge(QLineF(p1, p2), length_base, is_straight=True)) ge.add_plug_to_path(p, middle_edge) ge.add_plug_to_path( p, ge.init_edge(QLineF(p5, p4), length_base, is_straight=True)) ge.add_plug_to_path( p, ge.init_edge(QLineF(p4, p1), length_base, is_straight=True)) ge.make_piece_from_path(id1, p) # piece2 p = QPainterPath() p.moveTo(p2) ge.add_plug_to_path( p, ge.init_edge(QLineF(p2, p3), length_base, is_straight=True)) ge.add_plug_to_path( p, ge.init_edge(QLineF(p3, p6), length_base, is_straight=True)) ge.add_plug_to_path( p, ge.init_edge(QLineF(p6, p5), length_base, is_straight=True)) ge.add_plug_to_path(p, middle_edge, reverse=True) ge.make_piece_from_path(id2, p) ge.add_relation(id1, id2)
def drawInfo(self, renderContext, zoom, xmin, ymin, xmax, ymax): # debug information mapSettings = self.iface.mapCanvas().mapSettings() lines = [] lines.append("TileLayer") lines.append( " zoom: %d, tile matrix extent: (%d, %d) - (%d, %d), tile count: %d * %d" % (zoom, xmin, ymin, xmax, ymax, xmax - xmin, ymax - ymin)) extent = renderContext.extent() lines.append(" map extent (renderContext): %s" % extent.toString()) lines.append(" map center: %lf, %lf" % (extent.center().x(), extent.center().y())) lines.append(" map size: %f, %f" % (extent.width(), extent.height())) lines.append(" map extent (map canvas): %s" % self.iface.mapCanvas().extent().toString()) m2p = renderContext.mapToPixel() painter = renderContext.painter() viewport = painter.viewport() mapExtent = QgsRectangle( m2p.toMapCoordinatesF(0, 0), m2p.toMapCoordinatesF(viewport.width(), viewport.height())) lines.append(" map extent (calculated): %s" % mapExtent.toString()) lines.append(" viewport size (pixel): %d, %d" % (viewport.width(), viewport.height())) lines.append(" window size (pixel): %d, %d" % (painter.window().width(), painter.window().height())) lines.append(" outputSize (pixel): %d, %d" % (mapSettings.outputSize().width(), mapSettings.outputSize().height())) device = painter.device() lines.append(" deviceSize (pixel): %f, %f" % (device.width(), device.height())) lines.append(" logicalDpi: %f, %f" % (device.logicalDpiX(), device.logicalDpiY())) lines.append(" outputDpi: %f" % mapSettings.outputDpi()) lines.append(" mapToPixel: %s" % m2p.showParameters()) lines.append(" meters per pixel: %f" % (extent.width() / viewport.width())) lines.append(" scaleFactor: %f" % renderContext.scaleFactor()) lines.append(" rendererScale: %f" % renderContext.rendererScale()) scaleX, scaleY = self.getScaleToVisibleExtent(renderContext) lines.append(" scale: %f, %f" % (scaleX, scaleY)) # draw information textRect = painter.boundingRect(QRect(QPoint(0, 0), viewport.size()), Qt.AlignLeft, "Q") for i, line in enumerate(lines): painter.drawText(10, (i + 1) * textRect.height(), line) self.log(line) # diagonal painter.drawLine( QPointF(0, 0), QPointF(painter.viewport().width(), painter.viewport().height())) painter.drawLine(QPointF(painter.viewport().width(), 0), QPointF(0, painter.viewport().height())) # credit label margin, paddingH, paddingV = (3, 4, 3) credit = "This is credit" rect = QRect(0, 0, painter.viewport().width() - margin, painter.viewport().height() - margin) textRect = painter.boundingRect(rect, Qt.AlignBottom | Qt.AlignRight, credit) bgRect = QRect(textRect.left() - paddingH, textRect.top() - paddingV, textRect.width() + 2 * paddingH, textRect.height() + 2 * paddingV) painter.drawRect(bgRect) painter.drawText(rect, Qt.AlignBottom | Qt.AlignRight, credit)
def drawTilesOnTheFly(self, renderContext, tiles, sdx=1.0, sdy=1.0): if not hasGdal: msg = self.tr("Reprojection requires python-gdal") self.showBarMessage(msg, QgsMessageBar.INFO, 2) return transform = renderContext.coordinateTransform() if not transform: return # create an image that has the same resolution as the tiles image = tiles.image() # tile extent extent = tiles.extent() geotransform = [ extent.xMinimum(), extent.width() / image.width(), 0, extent.yMaximum(), 0, -extent.height() / image.height() ] driver = gdal.GetDriverByName("MEM") tile_ds = driver.Create("", image.width(), image.height(), 1, gdal.GDT_UInt32) tile_ds.SetProjection(str(transform.sourceCrs().toWkt())) tile_ds.SetGeoTransform(geotransform) # QImage to raster ba = image.bits().asstring(image.numBytes()) tile_ds.GetRasterBand(1).WriteRaster(0, 0, image.width(), image.height(), ba) # canvas extent m2p = renderContext.mapToPixel() viewport = renderContext.painter().viewport() width = viewport.width() height = viewport.height() extent = QgsRectangle(m2p.toMapCoordinatesF(0, 0), m2p.toMapCoordinatesF(width, height)) geotransform = [ extent.xMinimum(), extent.width() / width, 0, extent.yMaximum(), 0, -extent.height() / height ] canvas_ds = driver.Create("", width, height, 1, gdal.GDT_UInt32) canvas_ds.SetProjection(str(transform.destCRS().toWkt())) canvas_ds.SetGeoTransform(geotransform) # reproject image gdal.ReprojectImage(tile_ds, canvas_ds) # raster to QImage ba = canvas_ds.GetRasterBand(1).ReadRaster(0, 0, width, height) reprojected_image = QImage(ba, width, height, QImage.Format_ARGB32_Premultiplied) # draw the image on the map canvas rect = QRectF(QPointF(0, 0), QPointF(viewport.width() * sdx, viewport.height() * sdy)) renderContext.painter().drawImage(rect, reprojected_image)
def paint(self, painter, option, widget=None): if self.isVisible: painter.save() t = painter.transform() painter.setTransform(self.scene().data2scene * t) painter.setPen(self.thin_penY) painter.drawLine(QPointF(0.0, self.y), QPointF(self._width, self.y)) painter.setPen(self.thin_penX) painter.drawLine(QPointF(self.x, 0), QPointF(self.x, self._height)) radius = self.diameter / 2 + 1 painter.setPen(self.thick_penY) painter.drawLine(QPointF(0.0, self.y), QPointF(self.x - radius, self.y)) painter.drawLine(QPointF(self.x + radius, self.y), QPointF(self._width, self.y)) painter.setPen(self.thick_penX) painter.drawLine(QPointF(self.x, 0), QPointF(self.x, self.y - radius)) painter.drawLine(QPointF(self.x, self.y + radius), QPointF(self.x, self._height)) painter.restore()
def paint(self, painter, option, widget): arc_rect = 10 connector_length = 5 painter.setPen(self.pen) path = QtGui.QPainterPath() if self.source.x() == self.dest.x(): path.moveTo(self.source.x(), self.source.y()) path.lineTo(self.dest.x(), self.dest.y()) painter.drawPath(path) else: #Define points starting from source point1 = QPointF(self.source.x(), self.source.y()) point2 = QPointF(point1.x(), point1.y() - connector_length) point3 = QPointF(point2.x() + arc_rect, point2.y() - arc_rect) #Define points starting from dest point4 = QPointF(self.dest.x(), self.dest.y()) point5 = QPointF(point4.x(), point3.y() - arc_rect) point6 = QPointF(point5.x() - arc_rect, point5.y() + arc_rect) start_angle_arc1 = 180 span_angle_arc1 = 90 start_angle_arc2 = 90 span_angle_arc2 = -90 # If the dest is at the left of the source, then we # need to reverse some values if self.source.x() > self.dest.x(): point5 = QPointF(point4.x(), point4.y() + connector_length) point6 = QPointF(point5.x() + arc_rect, point5.y() + arc_rect) point3 = QPointF(self.source.x() - arc_rect, point6.y()) point2 = QPointF(self.source.x(), point3.y() + arc_rect) span_angle_arc1 = 90 path.moveTo(point1) path.lineTo(point2) path.arcTo(QRectF(point2, point3), start_angle_arc1, span_angle_arc1) path.lineTo(point6) path.arcTo(QRectF(point6, point5), start_angle_arc2, span_angle_arc2) path.lineTo(point4) painter.drawPath(path)
def shape(self): if self.__shape is None: path = self.getPath() d = self.pixelLength(QPointF(0, self.opts["mouseWidth"])) self.__shape = shape_from_path(path, width=d) return self.__shape