def renderItem(self, painter, widget, rect, fillBackground): """ Render a legend entry into a given rectangle. :param QPainter painter: Painter :param QWidget widget: Widget representing a legend entry :param QRectF rect: Bounding rectangle :param bool fillBackground: When true, fill rect with the widget background """ if fillBackground: if widget.autoFillBackground() or\ widget.testAttribute(Qt.WA_StyledBackground): QwtPainter.drawBackground(painter, rect, widget) label = widget #TODO: cast to QwtLegendLabel if label is not None: icon = label.data().icon() sz = icon.defaultSize() iconRect = QRectF(rect.x()+label.margin(), rect.center().y()-.5*sz.height(), sz.width(), sz.height()) icon.render(painter, iconRect, Qt.KeepAspectRatio) titleRect = QRectF(rect) titleRect.setX(iconRect.right()+2*label.spacing()) painter.setFont(label.font()) painter.setPen(label.palette().color(QPalette.Text)) label.drawText(painter, titleRect) #TODO: cast label to QwtLegendLabel
def drawLines(self, painter, xMap, yMap, canvasRect, from_, to): """ Draw lines :param QPainter painter: Painter :param qwt.scale_map.QwtScaleMap xMap: Maps x-values into pixel coordinates. :param qwt.scale_map.QwtScaleMap yMap: Maps y-values into pixel coordinates. :param QRectF canvasRect: Contents rectangle of the canvas :param int from_: Index of the first point to be painted :param int to: Index of the last point to be painted. If to < 0 the curve will be painted to its last point. .. seealso:: :py:meth:`draw()`, :py:meth:`drawDots()`, :py:meth:`drawSteps()`, :py:meth:`drawSticks()` """ if from_ > to: return doAlign = QwtPainter.roundingAlignment(painter) doFill = self.__data.brush.style() != Qt.NoBrush\ and self.__data.brush.color().alpha() > 0 clipRect = QRectF() if self.__data.paintAttributes & self.ClipPolygons: pw = max([1., painter.pen().widthF()]) clipRect = canvasRect.adjusted(-pw, -pw, pw, pw) doIntegers = False if QT_VERSION < 0x040800: if painter.paintEngine().type() == QPaintEngine.Raster: if not doFill: doIntegers = True noDuplicates = self.__data.paintAttributes & self.FilterPoints mapper = QwtPointMapper() mapper.setFlag(QwtPointMapper.RoundPoints, doAlign) mapper.setFlag(QwtPointMapper.WeedOutPoints, noDuplicates) mapper.setBoundingRect(canvasRect) if doIntegers: polyline = mapper.toPolygon(xMap, yMap, self.data(), from_, to) if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygon(clipRect.toAlignedRect(), polyline, False) QwtPainter.drawPolyline(painter, polyline) else: polyline = mapper.toPolygonF(xMap, yMap, self.data(), from_, to) if doFill: if painter.pen().style() != Qt.NoPen: filled = QPolygonF(polyline) self.fillCurve(painter, xMap, yMap, canvasRect, filled) filled.clear() if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygonF(clipRect, polyline, False) QwtPainter.drawPolyline(painter, polyline) else: self.fillCurve(painter, xMap, yMap, canvasRect, polyline) else: if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygonF(clipRect, polyline, False) QwtPainter.drawPolyline(painter, polyline)
def minLabelDist(self, font): if not self.hasComponent(QwtAbstractScaleDraw.Labels): return 0 ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick) if not ticks: return 0 fm = QFontMetrics(font) vertical = self.orientation() == Qt.Vertical bRect1 = QRectF() bRect2 = self.labelRect(font, ticks[0]) if vertical: bRect2.setRect(-bRect2.bottom(), 0., bRect2.height(), bRect2.width()) maxDist = 0. for tick in ticks: bRect1 = bRect2 bRect2 = self.labelRect(font, tick) if vertical: bRect2.setRect(-bRect2.bottom(), 0., bRect2.height(), bRect2.width()) dist = fm.leading() if bRect1.right() > 0: dist += bRect1.right() if bRect2.left() < 0: dist += -bRect2.left() if dist > maxDist: maxDist = dist angle = qwtRadians(self.labelRotation()) if vertical: angle += np.pi/2 sinA = np.sin(angle) if qFuzzyCompare(sinA+1., 1.): return np.ceil(maxDist) fmHeight = fm.ascent()-2 labelDist = fmHeight/np.sin(angle)*np.cos(angle) if labelDist < 0: labelDist = -labelDist if labelDist > maxDist: labelDist = maxDist if labelDist < fmHeight: labelDist = fmHeight return np.ceil(labelDist)
def drawPath(self, path): rect = QRectF(QPointF(0., 0.), self.__size) if path.controlPointRect().contains(rect.center()): self.setCornerRects(path) self.alignCornerRects(rect) self.background.path = path self.background.brush = self.__brush self.background.origin = self.__origin else: self.border.pathlist += [path]
def renderDocument(self, plot, filename, sizeMM=(300, 200), resolution=85, format_=None): if isinstance(sizeMM, tuple): sizeMM = QSizeF(*sizeMM) if format_ is None: ext = osp.splitext(filename)[1] if not ext: raise TypeError("Unable to determine target format from filename") format_ = ext[1:] if plot is None or sizeMM.isEmpty() or resolution <= 0: return title = plot.title().text() if not title: title = "Plot Document" mmToInch = 1./25.4 size = sizeMM * mmToInch * resolution documentRect = QRectF(0.0, 0.0, size.width(), size.height()) fmt = format_.lower() if fmt in ("pdf", "ps"): printer = QPrinter() if fmt == "pdf": printer.setOutputFormat(QPrinter.PdfFormat) else: printer.setOutputFormat(QPrinter.PostScriptFormat) printer.setColorMode(QPrinter.Color) printer.setFullPage(True) printer.setPaperSize(sizeMM, QPrinter.Millimeter) printer.setDocName(title) printer.setOutputFileName(filename) printer.setResolution(resolution) painter = QPainter(printer) self.render(plot, painter, documentRect) painter.end() elif fmt == "svg": generator = QSvgGenerator() generator.setTitle(title) generator.setFileName(filename) generator.setResolution(resolution) generator.setViewBox(documentRect) painter = QPainter(generator) self.render(plot, painter, documentRect) painter.end() elif fmt in QImageWriter.supportedImageFormats(): imageRect = documentRect.toRect() dotsPerMeter = int(round(resolution*mmToInch*1000.)) image = QImage(imageRect.size(), QImage.Format_ARGB32) image.setDotsPerMeterX(dotsPerMeter) image.setDotsPerMeterY(dotsPerMeter) image.fill(QColor(Qt.white).rgb()) painter = QPainter(image) self.render(plot, painter, imageRect) painter.end() image.save(filename, fmt) else: raise TypeError("Unsupported file format '%s'" % fmt)
def drawSymbol(self, painter, point_or_rect): """ Draw the symbol into a rectangle The symbol is painted centered and scaled into the target rectangle. It is always painted uncached and the pin point is ignored. This method is primarily intended for drawing a symbol to the legend. :param QPainter painter: Painter :param point_or_rect: Position or target rectangle of the symbol in screen coordinates :type point_or_rect: QPointF or QPoint or QRectF """ if isinstance(point_or_rect, (QPointF, QPoint)): # drawSymbol( QPainter *, const QPointF & ) self.drawSymbols(painter, [point_or_rect]) return # drawSymbol( QPainter *, const QRectF & ) rect = point_or_rect assert isinstance(rect, QRectF) if self.__data.style == QwtSymbol.NoSymbol: return if self.__data.style == QwtSymbol.Graphic: self.__data.graphic.graphic.render(painter, rect, Qt.KeepAspectRatio) elif self.__data.style == QwtSymbol.Path: if self.__data.path.graphic.isNull(): self.__data.path.graphic = qwtPathGraphic( self.__data.path.path, self.__data.pen, self.__data.brush) self.__data.path.graphic.render(painter, rect, Qt.KeepAspectRatio) return elif self.__data.style == QwtSymbol.SvgDocument: if self.__data.svg.renderer is not None: scaledRect = QRectF() sz = QSizeF(self.__data.svg.renderer.viewBoxF().size()) if not sz.isEmpty(): sz.scale(rect.size(), Qt.KeepAspectRatio) scaledRect.setSize(sz) scaledRect.moveCenter(rect.center()) else: scaledRect = rect self.__data.svg.renderer.render(painter, scaledRect) else: br = QRect(self.boundingRect()) ratio = min([rect.width()/br.width(), rect.height()/br.height()]) painter.save() painter.translate(rect.center()) painter.scale(ratio, ratio) isPinPointEnabled = self.__data.isPinPointEnabled self.__data.isPinPointEnabled = False pos = QPointF() self.renderSymbols(painter, pos, 1) self.__data.isPinPointEnabled = isPinPointEnabled painter.restore()
def draw(self, painter, xMap, yMap, canvasRect): pos = QPointF(xMap.transform(self.__data.xValue), yMap.transform(self.__data.yValue)) self.drawLines(painter, canvasRect, pos) if self.__data.symbol and\ self.__data.symbol.style() != QwtSymbol.NoSymbol: sz = self.__data.symbol.size() clipRect = QRectF(canvasRect.adjusted(-sz.width(), -sz.height(), sz.width(), sz.height())) if clipRect.contains(pos): self.__data.symbol.drawSymbols(painter, [pos]) self.drawLabel(painter, canvasRect, pos)
def toRect(self): r = QRectF(self.hInterval.minValue(), self.vInterval.minValue(), self.hInterval.maxValue()-self.hInterval.minValue(), self.vInterval.maxValue()-self.vInterval.minValue()) r = r.normalized() if self.hInterval.borderFlags() & QwtInterval.ExcludeMinimum: r.adjust(1, 0, 0, 0) if self.hInterval.borderFlags() & QwtInterval.ExcludeMaximum: r.adjust(0, 0, -1, 0) if self.vInterval.borderFlags() & QwtInterval.ExcludeMinimum: r.adjust(0, 1, 0, 0) if self.vInterval.borderFlags() & QwtInterval.ExcludeMaximum: r.adjust(0, 0, 0, -1) return r
def drawLines(self, painter, xMap, yMap, canvasRect, from_, to): if from_ > to: return doAlign = QwtPainter.roundingAlignment(painter) doFit = (self.__data.attributes & self.Fitted)\ and self.__data.curveFitter doFill = self.__data.brush.style() != Qt.NoBrush\ and self.__data.brush.color().alpha() > 0 clipRect = QRectF() if self.__data.paintAttributes & self.ClipPolygons: pw = max([1., painter.pen().widthF()]) clipRect = canvasRect.adjusted(-pw, -pw, pw, pw) doIntegers = False if QT_VERSION < 0x040800: if painter.paintEngine().type() == QPaintEngine.Raster: if not doFit and not doFill: doIntegers = True noDuplicates = self.__data.paintAttributes & self.FilterPoints mapper = QwtPointMapper() mapper.setFlag(QwtPointMapper.RoundPoints, doAlign) mapper.setFlag(QwtPointMapper.WeedOutPoints, noDuplicates) mapper.setBoundingRect(canvasRect) if doIntegers: polyline = mapper.toPolygon(xMap, yMap, self.data(), from_, to) if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygon(clipRect.toAlignedRect(), polyline, False) QwtPainter.drawPolyline(painter, polyline) else: polyline = mapper.toPolygonF(xMap, yMap, self.data(), from_, to) if doFit: polyline = self.__data.curveFitter.fitCurve(polyline) if doFill: if painter.pen().style() != Qt.NoPen: filled = QPolygonF(polyline) self.fillCurve(painter, xMap, yMap, canvasRect, filled) filled.clear() if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygonF(clipRect, polyline, False) QwtPainter.drawPolyline(painter, polyline) else: self.fillCurve(painter, xMap, yMap, canvasRect, polyline) else: if self.__data.paintAttributes & self.ClipPolygons: polyline = QwtClipper().clipPolygonF(clipRect, polyline, False) QwtPainter.drawPolyline(painter, polyline)
def renderItem(self, painter, widget, rect, fillBackground): if fillBackground: if widget.autoFillBackground() or\ widget.testAttribute(Qt.WA_StyledBackground): QwtPainter.drawBackground(painter, rect, widget) label = widget #TODO: cast to QwtLegendLabel if label is not None: icon = label.data().icon() sz = icon.defaultSize() iconRect = QRectF(rect.x()+label.margin(), rect.center().y()-.5*sz.height(), sz.width(), sz.height()) icon.render(painter, iconRect, Qt.KeepAspectRatio) titleRect = QRectF(rect) titleRect.setX(iconRect.right()+2*label.spacing()) painter.setFont(label.font()) painter.setPen(label.palette().color(QPalette.Text)) label.drawText(painter, titleRect) #TODO: cast label to QwtLegendLabel
def drawSymbol(self, painter, point_or_rect): if isinstance(point_or_rect, (QPointF, QPoint)): # drawSymbol( QPainter *, const QPointF & ) self.drawSymbols(painter, [point_or_rect], 1) return # drawSymbol( QPainter *, const QRectF & ) rect = point_or_rect assert isinstance(rect, QRectF) if self.__data.style == QwtSymbol.NoSymbol: return if self.__data.style == QwtSymbol.Graphic: self.__data.graphic.graphic.render(painter, rect, Qt.KeepAspectRatio) elif self.__data.style == QwtSymbol.Path: if self.__data.path.graphic.isNull(): self.__data.path.graphic = qwtPathGraphic( self.__data.path.path, self.__data.pen, self.__data.brush) self.__data.path.graphic.render(painter, rect, Qt.KeepAspectRatio) return elif self.__data.style == QwtSymbol.SvgDocument: if self.__data.svg.renderer is not None: scaledRect = QRectF() sz = QSizeF(self.__data.svg.renderer.viewBoxF().size()) if not sz.isEmpty(): sz.scale(rect.size(), Qt.KeepAspectRatio) scaledRect.setSize(sz) scaledRect.moveCenter(rect.center()) else: scaledRect = rect self.__data.svg.renderer.render(painter, scaledRect) else: br = QRect(self.boundingRect()) ratio = min([rect.width()/br.width(), rect.height()/br.height()]) painter.save() painter.translate(rect.center()) painter.scale(ratio, ratio) isPinPointEnabled = self.__data.isPinPointEnabled self.__data.isPinPointEnabled = False pos = QPointF() self.renderSymbols(painter, pos, 1) self.__data.isPinPointEnabled = isPinPointEnabled painter.restore()
def clipPolygonF(self, clipRect, polygon, closePolygon): raise NotImplementedError( "Nearly impossible to implement in pure Python") #XXX: the only viable option would be to use Qt's intersected method # but unfortunately it's closing systematically the output polygon # (how to test it: polygon.intersected(QPolygonF(clipRect))) if isinstance(clipRect, QRect): clipRect = QRectF(clipRect) clipper = QwtPolygonClipper(clipRect) return clipper.clipPolygon(polygon, closePolygon)
def setCornerRects(self, path): pos = QPointF(0., 0.) for i in range(path.elementCount()): el = path.elementAt(i) if el.type in (QPainterPath.MoveToElement, QPainterPath.LineToElement): pos.setX(el.x) pos.setY(el.y) elif el.type == QPainterPath.CurveToElement: r = QRectF(pos, QPointF(el.x, el.y)) self.clipRects += [r.normalized()] pos.setX(el.x) pos.setY(el.y) elif el.type == QPainterPath.CurveToDataElement: if self.clipRects: r = self.clipRects[-1] r.setCoords(min([r.left(), el.x]), min([r.top(), el.y]), max([r.right(), el.x]), max([r.bottom(), el.y])) self.clipRects[-1] = r.normalized()
def qwtIsClippingNeeded(painter): doClipping = False clipRect = QRectF() #TODO: remove next line when QwtClipper will be implemented return doClipping, clipRect pe = painter.paintEngine() if pe and pe.type() == QPaintEngine.SVG: if painter.hasClipping(): doClipping = True clipRect = painter.clipRegion().boundingRect() return doClipping, clipRect
def qwtDrawSvgSymbols(painter, points, numPoints, renderer, symbol): if renderer is None or not renderer.isValid(): return viewBox = QRectF(renderer.viewBoxF()) if viewBox.isEmpty(): return sz = QSizeF(symbol.size()) if not sz.isValid(): sz = viewBox.size() sx = sz.width() / viewBox.width() sy = sz.height() / viewBox.height() pinPoint = QPointF(viewBox.center()) if symbol.isPinPointEnabled(): pinPoint = symbol.pinPoint() dx = sx * (pinPoint.x() - viewBox.left()) dy = sy * (pinPoint.y() - viewBox.top()) for pos in points: x = pos.x() - dx y = pos.y() - dy renderer.render(painter, QRectF(x, y, sz.width(), sz.height()))
def dataRect(self): """ :return: Bounding rectangle of the series or an invalid rectangle, when no series is stored .. seealso:: :py:meth:`qwt.plot_series.QwtSeriesData.boundingRect()` """ if self.__series is None or self.dataSize() == 0: return QRectF(1.0, 1.0, -2.0, -2.0) return self.__series.boundingRect()
def draw(self, painter, xMap, yMap, canvasRect): """ Draw the marker :param QPainter painter: Painter :param qwt.scale_map.QwtScaleMap xMap: x Scale Map :param qwt.scale_map.QwtScaleMap yMap: y Scale Map :param QRectF canvasRect: Contents rectangle of the canvas in painter coordinates """ pos = QPointF(xMap.transform(self.__data.xValue), yMap.transform(self.__data.yValue)) self.drawLines(painter, canvasRect, pos) if self.__data.symbol and\ self.__data.symbol.style() != QwtSymbol.NoSymbol: sz = self.__data.symbol.size() clipRect = QRectF(canvasRect.adjusted(-sz.width(), -sz.height(), sz.width(), sz.height())) if clipRect.contains(pos): self.__data.symbol.drawSymbols(painter, [pos]) self.drawLabel(painter, canvasRect, pos)
def updateBoundingRect(self, rect): br = QRectF(rect) painter = self.paintEngine().painter() if painter and painter.hasClipping(): #XXX: there's something fishy about the following lines... cr = painter.clipRegion().boundingRect() cr = painter.transform().mapRect(br) br &= cr if self.__data.boundingRect.width() < 0: self.__data.boundingRect = br else: self.__data.boundingRect |= br
def draw(self, painter, xMap, yMap, canvasRect): """ Draw the marker :param QPainter painter: Painter :param qwt.scale_map.QwtScaleMap xMap: x Scale Map :param qwt.scale_map.QwtScaleMap yMap: y Scale Map :param QRectF canvasRect: Contents rectangle of the canvas in painter coordinates """ pos = QPointF(xMap.transform(self.__data.xValue), yMap.transform(self.__data.yValue)) self.drawLines(painter, canvasRect, pos) if self.__data.symbol and\ self.__data.symbol.style() != QwtSymbol.NoSymbol: sz = self.__data.symbol.size() clipRect = QRectF( canvasRect.adjusted(-sz.width(), -sz.height(), sz.width(), sz.height())) if clipRect.contains(pos): self.__data.symbol.drawSymbols(painter, [pos]) self.drawLabel(painter, canvasRect, pos)
def scaleRect(self, axis): """ :param int axisId: Axis index :return: Geometry for the scale .. seealso:: :py:meth:`invalidate()`, :py:meth:`activate()` """ if axis not in QwtPlot.validAxes: return QRectF() return self.__data.scaleRect[axis]
def drawSimpleRichText(self, painter, rect, flags, text): txt = text.clone() painter.save() unscaledRect = QRectF(rect) if painter.font().pixelSize() < 0: res = qwtScreenResolution() pd = painter.device() if pd.logicalDpiX() != res.width()\ or pd.logicalDpiY() != res.height(): transform = QTransform() transform.scale(res.width()/float(pd.logicalDpiX()), res.height()/float(pd.logicalDpiY())) painter.setWorldTransform(transform, True) invtrans, _ok = transform.inverted() unscaledRect = invtrans.mapRect(rect) txt.setDefaultFont(painter.font()) txt.setPageSize(QSizeF(unscaledRect.width(), QWIDGETSIZE_MAX)) layout = txt.documentLayout() height = layout.documentSize().height() y = unscaledRect.y() if flags & Qt.AlignBottom: y += unscaledRect.height()-height elif flags & Qt.AlignVCenter: y += (unscaledRect.height()-height)/2 context = QAbstractTextDocumentLayout.PaintContext() context.palette.setColor(QPalette.Text, painter.pen().color()) painter.translate(unscaledRect.x(), y) layout.draw(painter, context) painter.restore()
def qwtDrawEllipseSymbols(painter, points, numPoints, symbol): painter.setBrush(symbol.brush()) painter.setPen(symbol.pen()) size = symbol.size() sw = size.width() sh = size.height() sw2 = .5 * size.width() sh2 = .5 * size.height() for pos in points: x = pos.x() y = pos.y() r = QRectF(x - sw2, y - sh2, sw, sh) painter.drawEllipse(r)
def invTransform(self, *args): """Transform from paint to scale coordinates Scalar: scalemap.invTransform(scalar) Point (QPointF): scalemap.invTransform(xMap, yMap, pos) Rectangle (QRectF): scalemap.invTransform(xMap, yMap, rect) """ if len(args) == 1: # Scalar transform return self.invTransform_scalar(args[0]) elif isinstance(args[2], QPointF): xMap, yMap, pos = args return QPointF(xMap.invTransform(pos.x()), yMap.invTransform(pos.y())) elif isinstance(args[2], QRectF): xMap, yMap, rect = args x1 = xMap.invTransform(rect.left()) x2 = xMap.invTransform(rect.right() - 1) y1 = yMap.invTransform(rect.top()) y2 = yMap.invTransform(rect.bottom() - 1) r = QRectF(x1, y1, x2 - x1, y2 - y1) return r.normalized()
def qwtDrawGraphicSymbols(painter, points, numPoint, graphic, symbol): pointRect = QRectF(graphic.controlPointRect()) if pointRect.isEmpty(): return sx = 1. sy = 1. sz = symbol.size() if sz.isValid(): sx = sz.width()/pointRect.width() sy = sz.height()/pointRect.height() pinPoint = QPointF(pointRect.center()) if symbol.isPinPointEnabled(): pinPoint = symbol.pinPoint() transform = QTransform(painter.transform()) for pos in points: tr = QTransform(transform) tr.translate(pos.x(), pos.y()) tr.scale(sx, sy) tr.translate(-pinPoint.x(), -pinPoint.y()) painter.setTransform(tr) graphic.render(painter) painter.setTransform(transform)
def invTransform(self, *args): """Transform from paint to scale coordinates Scalar: scalemap.invTransform(scalar) Point (QPointF): scalemap.invTransform(xMap, yMap, pos) Rectangle (QRectF): scalemap.invTransform(xMap, yMap, rect) """ if len(args) == 1: # Scalar transform return self.invTransform_scalar(args[0]) elif isinstance(args[2], QPointF): xMap, yMap, pos = args return QPointF(xMap.invTransform(pos.x()), yMap.invTransform(pos.y())) elif isinstance(args[2], QRectF): xMap, yMap, rect = args x1 = xMap.invTransform(rect.left()) x2 = xMap.invTransform(rect.right()-1) y1 = yMap.invTransform(rect.top()) y2 = yMap.invTransform(rect.bottom()-1) r = QRectF(x1, y1, x2-x1, y2-y1) return r.normalized()
def boundingRect(self): """ Calculate the bounding rectangle The bounding rectangle is calculated once by iterating over all points and is stored for all following requests. :return: Bounding rectangle """ xmin = self.__x.min() xmax = self.__x.max() ymin = self.__y.min() ymax = self.__y.max() return QRectF(xmin, ymin, xmax-xmin, ymax-ymin)
def heightForWidth(self, font, flags, text, width): """ Find the height for a given width :param QFont font: Font of the text :param int flags: Bitwise OR of the flags used like in QPainter::drawText :param str text: Text to be rendered :param float width: Width :return: Calculated height """ fm = self.fontmetrics_f(font) rect = fm.boundingRect(QRectF(0, 0, width, QWIDGETSIZE_MAX), flags, text) return rect.height()
def drawTitle(self, painter, align, rect): """ Rotate and paint a title according to its position into a given rectangle. :param QPainter painter: Painter :param int align: Alignment :param QRectF rect: Bounding rectangle """ r = rect flags = self.__data.title.renderFlags()\ &(~ int(Qt.AlignTop|Qt.AlignBottom|Qt.AlignVCenter)) if align == QwtScaleDraw.LeftScale: angle = -90. flags |= Qt.AlignTop r.setRect(r.left(), r.bottom(), r.height(), r.width() - self.__data.titleOffset) elif align == QwtScaleDraw.RightScale: angle = -90. flags |= Qt.AlignTop r.setRect(r.left() + self.__data.titleOffset, r.bottom(), r.height(), r.width() - self.__data.titleOffset) elif align == QwtScaleDraw.BottomScale: angle = 0. flags |= Qt.AlignBottom r.setTop(r.top() + self.__data.titleOffset) else: angle = 0. flags |= Qt.AlignTop r.setBottom(r.bottom() - self.__data.titleOffset) if self.__data.layoutFlags & self.TitleInverted: if align in (QwtScaleDraw.LeftScale, QwtScaleDraw.RightScale): angle = -angle r.setRect(r.x() + r.height(), r.y() - r.width(), r.width(), r.height()) painter.save() painter.setFont(self.font()) painter.setPen(self.palette().color(QPalette.Text)) painter.translate(r.x(), r.y()) if angle != 0.: painter.rotate(angle) title = self.__data.title title.setRenderFlags(flags) title.draw(painter, QRectF(0., 0., r.width(), r.height())) painter.restore()
def qwtBoundingRect(*args): if args: sample = args[0] if len(args) == 1 and isinstance(sample, (QPointF, QwtPoint3d)): return QRectF(sample.x(), sample.y(), 0.0, 0.0) elif len(args) == 1 and isinstance(sample, QwtPointPolar): return QRectF(sample.x(), sample.y(), 0.0, 0.0) elif len(args) == 1 and isinstance(sample, QwtIntervalSample): return QRectF(sample.interval.minValue(), sample.value, sample.interval.maxValue() - sample.interval.minValue(), 0.) elif len(args) == 1 and isinstance(sample, QwtSetSample): minY = sample.set[0] maxY = sample.set[0] for val in sample.set: if val < minY: minY = val if val > maxY: maxY = val minX = sample.value maxX = sample.value return QRectF(minX, minY, maxX - minX, maxY - minY) elif len(args) == 1 and isinstance(sample, QwtOHLCSample): interval = sample.boundingInterval() return QRectF(interval.minValue(), sample.time, interval.width(), 0.) elif len(args) in (1, 2, 3): series = args[0] from_ = 0 to = -1 if len(args) > 1: from_ = args[1] if len(args) > 2: to = args[2] return qwtBoundingRectT(series, from_, to) else: raise TypeError("%s() takes 1 or 3 argument(s) (%s given)"\ % ("qwtBoundingRect", len(args)))
def drawSymbol(self, painter, point_or_rect): """ Draw the symbol into a rectangle The symbol is painted centered and scaled into the target rectangle. It is always painted uncached and the pin point is ignored. This method is primarily intended for drawing a symbol to the legend. :param QPainter painter: Painter :param point_or_rect: Position or target rectangle of the symbol in screen coordinates :type point_or_rect: QPointF or QPoint or QRectF """ if isinstance(point_or_rect, (QPointF, QPoint)): # drawSymbol( QPainter *, const QPointF & ) self.drawSymbols(painter, [point_or_rect]) return # drawSymbol( QPainter *, const QRectF & ) rect = point_or_rect assert isinstance(rect, QRectF) if self.__data.style == QwtSymbol.NoSymbol: return if self.__data.style == QwtSymbol.Graphic: self.__data.graphic.graphic.render(painter, rect, Qt.KeepAspectRatio) elif self.__data.style == QwtSymbol.Path: if self.__data.path.graphic.isNull(): self.__data.path.graphic = qwtPathGraphic( self.__data.path.path, self.__data.pen, self.__data.brush) self.__data.path.graphic.render(painter, rect, Qt.KeepAspectRatio) return elif self.__data.style == QwtSymbol.SvgDocument: if self.__data.svg.renderer is not None: scaledRect = QRectF() sz = QSizeF(self.__data.svg.renderer.viewBoxF().size()) if not sz.isEmpty(): sz.scale(rect.size(), Qt.KeepAspectRatio) scaledRect.setSize(sz) scaledRect.moveCenter(rect.center()) else: scaledRect = rect self.__data.svg.renderer.render(painter, scaledRect) else: br = QRect(self.boundingRect()) ratio = min( [rect.width() / br.width(), rect.height() / br.height()]) painter.save() painter.translate(rect.center()) painter.scale(ratio, ratio) isPinPointEnabled = self.__data.isPinPointEnabled self.__data.isPinPointEnabled = False pos = QPointF() self.renderSymbols(painter, pos, 1) self.__data.isPinPointEnabled = isPinPointEnabled painter.restore()
def qwtStrokedPathRect(painter, path): stroker = QPainterPathStroker() stroker.setWidth(painter.pen().widthF()) stroker.setCapStyle(painter.pen().capStyle()) stroker.setJoinStyle(painter.pen().joinStyle()) stroker.setMiterLimit(painter.pen().miterLimit()) rect = QRectF() if qwtHasScalablePen(painter): stroke = stroker.createStroke(path) rect = painter.transform().map(stroke).boundingRect() else: mappedPath = painter.transform().map(path) mappedPath = stroker.createStroke(mappedPath) rect = mappedPath.boundingRect() return rect
def boundingRect(self): """ The bounding rectangle is the :py:meth:`controlPointRect` extended by the areas needed for rendering the outlines with unscaled pens. :return: Bounding rectangle of the graphic .. seealso:: :py:meth:`controlPointRect`, :py:meth:`scaledBoundingRect` """ if self.__data.boundingRect.width() < 0: return QRectF() return self.__data.boundingRect
def qwtDrawEllipseSymbols(painter, points, numPoints, symbol): painter.setBrush(symbol.brush()) painter.setPen(symbol.pen()) size = symbol.size() if QwtPainter.roundingAlignment(painter): sw = size.width() sh = size.height() sw2 = size.width() // 2 sh2 = size.height() // 2 for pos in points: x = round(pos.x()) y = round(pos.y()) r = QRectF(x - sw2, y - sh2, sw, sh) QwtPainter.drawEllipse(painter, r) else: sw = size.width() sh = size.height() sw2 = .5 * size.width() sh2 = .5 * size.height() for pos in points: x = pos.x() y = pos.y() r = QRectF(x - sw2, y - sh2, sw, sh) QwtPainter.drawEllipse(painter, r)
def controlPointRect(self): """ The control point rectangle is the bounding rectangle of all control points of the paths and the target rectangles of the images/pixmaps. :return: Control point rectangle .. seealso:: :py:meth:`boundingRect()`, :py:meth:`scaledBoundingRect()` """ if self.__data.pointRect.width() < 0: return QRectF() return self.__data.pointRect
def drawContents(self, painter): """ Redraw the text and focus indicator :param QPainter painter: Painter """ r = self.textRect() if r.isEmpty(): return painter.setFont(self.font()) painter.setPen(self.palette().color(QPalette.Active, QPalette.Text)) self.drawText(painter, QRectF(r)) if self.hasFocus(): m = 2 focusRect = self.contentsRect().adjusted(m, m, -m + 1, -m + 1) QwtPainter.drawFocusRect(painter, self, focusRect)
def drawPath(self, path): painter = self.paintEngine().painter() if painter is None: return self.__data.commands += [QwtPainterCommand(path)] if not path.isEmpty(): scaledPath = painter.transform().map(path) pointRect = scaledPath.boundingRect() boundingRect = QRectF(pointRect) if painter.pen().style() != Qt.NoPen\ and painter.pen().brush().style() != Qt.NoBrush: boundingRect = qwtStrokedPathRect(painter, path) self.updateControlPointRect(pointRect) self.updateBoundingRect(boundingRect) self.__data.pathInfos += [PathInfo(pointRect, boundingRect, qwtHasScalablePen(painter))]
def qwtDrawRectSymbols(painter, points, numPoints, symbol): size = symbol.size() pen = QPen(symbol.pen()) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) painter.setBrush(symbol.brush()) painter.setRenderHint(QPainter.Antialiasing, False) sw = size.width() sh = size.height() sw2 = .5 * size.width() sh2 = .5 * size.height() for pos in points: x = pos.x() y = pos.y() r = QRectF(x - sw2, y - sh2, sw, sh) painter.drawRect(r)
def qwtDrawSvgSymbols(painter, points, numPoints, renderer, symbol): if renderer is None or not renderer.isValid(): return viewBox = QRectF(renderer.viewBoxF()) if viewBox.isEmpty(): return sz = QSizeF(symbol.size()) if not sz.isValid(): sz = viewBox.size() sx = sz.width()/viewBox.width() sy = sz.height()/viewBox.height() pinPoint = QPointF(viewBox.center()) if symbol.isPinPointEnabled(): pinPoint = symbol.pinPoint() dx = sx*(pinPoint.x()-viewBox.left()) dy = sy*(pinPoint.y()-viewBox.top()) for pos in points: x = pos.x()-dx y = pos.y()-dy renderer.render(painter, QRectF(x, y, sz.width(), sz.height()))
def drawBorder(self, painter): """ Draw the border of the plot canvas :param QPainter painter: Painter .. seealso:: :py:meth:`setBorderRadius()` """ if self.__data.borderRadius > 0: if self.frameWidth() > 0: QwtPainter.drawRoundedFrame(painter, QRectF(self.frameRect()), self.__data.borderRadius, self.__data.borderRadius, self.palette(), self.frameWidth(), self.frameStyle()) else: if QT_VERSION >= 0x040500: if PYQT5: from qwt.qt.QtGui import QStyleOptionFrame else: from qwt.qt.QtGui import QStyleOptionFrameV3 as\ QStyleOptionFrame opt = QStyleOptionFrame() opt.initFrom(self) frameShape = self.frameStyle() & QFrame.Shape_Mask frameShadow = self.frameStyle() & QFrame.Shadow_Mask opt.frameShape = QFrame.Shape(int(opt.frameShape) | frameShape) if frameShape in (QFrame.Box, QFrame.HLine, QFrame.VLine, QFrame.StyledPanel, QFrame.Panel): opt.lineWidth = self.lineWidth() opt.midLineWidth = self.midLineWidth() else: opt.lineWidth = self.frameWidth() if frameShadow == self.Sunken: opt.state |= QStyle.State_Sunken elif frameShadow == self.Raised: opt.state |= QStyle.State_Raised self.style().drawControl(QStyle.CE_ShapedFrame, opt, painter, self) else: self.drawFrame(painter)
def toPixmap(self, *args): """ Convert the graphic to a `QPixmap` All pixels of the pixmap get initialized by `Qt.transparent` before the graphic is scaled and rendered on it. The size of the pixmap is the default size ( ceiled to integers ) of the graphic. :return: The graphic as pixmap in default size .. seealso:: :py:meth:`defaultSize()`, :py:meth:`toImage()`, :py:meth:`render()` """ if len(args) == 0: if self.isNull(): return QPixmap() sz = self.defaultSize() w = np.ceil(sz.width()) h = np.ceil(sz.height()) pixmap = QPixmap(w, h) pixmap.fill(Qt.transparent) r = QRectF(0., 0., sz.width(), sz.height()) painter = QPainter(pixmap) self.render(painter, r, Qt.KeepAspectRatio) painter.end() return pixmap elif len(args) in (1, 2): size = args[0] aspectRatioMode = Qt.IgnoreAspectRatio if len(args) == 2: aspectRatioMode = args[-1] pixmap = QPixmap(size) pixmap.fill(Qt.transparent) r = QRect(0, 0, size.width(), size.height()) painter = QPainter(pixmap) self.render(painter, r, aspectRatioMode) painter.end() return pixmap
def borderPath(self, rect): if self.testAttribute(Qt.WA_StyledBackground): recorder = QwtStyleSheetRecorder(rect.size()) painter = QPainter(recorder) opt = QStyleOption() opt.initFrom(self) opt.rect = rect self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self) painter.end() if not recorder.background.path.isEmpty(): return recorder.background.path if not recorder.border.rectList.isEmpty(): return qwtCombinePathList(rect, recorder.border.pathlist) elif self.__data.borderRadius > 0.: fw2 = self.frameWidth() * .5 r = QRectF(rect).adjusted(fw2, fw2, -fw2, -fw2) path = QPainterPath() path.addRoundedRect(r, self.__data.borderRadius, self.__data.borderRadius) return path return QPainterPath()
def renderItem(self, painter, widget, rect, fillBackground): if fillBackground: if widget.autoFillBackground() or\ widget.testAttribute(Qt.WA_StyledBackground): QwtPainter.drawBackground(painter, rect, widget) label = widget #TODO: cast to QwtLegendLabel if label is not None: icon = label.data().icon() sz = icon.defaultSize() iconRect = QRectF(rect.x() + label.margin(), rect.center().y() - .5 * sz.height(), sz.width(), sz.height()) icon.render(painter, iconRect, Qt.KeepAspectRatio) titleRect = QRectF(rect) titleRect.setX(iconRect.right() + 2 * label.spacing()) painter.setFont(label.font()) painter.setPen(label.palette().color(QPalette.Text)) label.drawText(painter, titleRect) #TODO: cast label to QwtLegendLabel
def drawRect(self, *args): if len(args) == 5: painter, x, y, w, h = args self.drawRect(painter, QRectF(x, y, w, h)) elif len(args) == 2: painter, rect = args r = rect deviceClipping, clipRect = qwtIsClippingNeeded(painter) if deviceClipping: if not clipRect.intersects(r): return if not clipRect.contains(r): self.fillRect(painter, r & clipRect, painter.brush()) painter.save() painter.setBrush(Qt.NoBrush) self.drawPolyline(painter, QPolygonF(r)) painter.restore() return painter.drawRect(r) else: raise TypeError("QwtPainter.drawRect() takes 2 or 5 argument(s) "\ "(%s given)" % len(args))
def qwtDrawStar1Symbols(painter, points, numPoints, symbol): size = symbol.size() painter.setPen(symbol.pen()) sqrt1_2 = np.sqrt(.5) if QwtPainter.roundingAlignment(painter): r = QRect(0, 0, size.width(), size.height()) for pos in points: r.moveCenter(pos.toPoint()) d1 = r.width() / 2. * (1. - sqrt1_2) QwtPainter.drawLine(painter, round(r.left() + d1), round(r.top() + d1), round(r.right() - d1), round(r.bottom() - d1)) QwtPainter.drawLine(painter, round(r.left() + d1), round(r.bottom() - d1), round(r.right() - d1), round(r.top() + d1)) c = QPoint(r.center()) QwtPainter.drawLine(painter, c.x(), r.top(), c.x(), r.bottom()) QwtPainter.drawLine(painter, r.left(), c.y(), r.right(), c.y()) else: r = QRectF(0, 0, size.width(), size.height()) for pos in points: r.moveCenter(pos.toPoint()) c = QPointF(r.center()) d1 = r.width() / 2. * (1. - sqrt1_2) QwtPainter.drawLine(painter, r.left() + d1, r.top() + d1, r.right() - d1, r.bottom() - d1) QwtPainter.drawLine(painter, r.left() + d1, r.bottom() - d1, r.right() - d1, r.top() + d1) QwtPainter.drawLine(painter, c.x(), r.top(), c.x(), r.bottom()) QwtPainter.drawLine(painter, r.left(), c.y(), r.right(), c.y())
def boundingRect(self): """Return the bounding rectangle of the data, error bars included. """ if self.__dx is None: xmin = min(self.__x) xmax = max(self.__x) elif len(self.__dx.shape) in [0, 1]: xmin = min(self.__x - self.__dx) xmax = max(self.__x + self.__dx) else: xmin = min(self.__x - self.__dx[0]) xmax = max(self.__x + self.__dx[1]) if self.__dy is None: ymin = min(self.__y) ymax = max(self.__y) elif len(self.__dy.shape) in [0, 1]: ymin = min(self.__y - self.__dy) ymax = max(self.__y + self.__dy) else: ymin = min(self.__y - self.__dy[0]) ymax = max(self.__y + self.__dy[1]) return QRectF(xmin, ymin, xmax - xmin, ymax - ymin)
def draw(self, painter, rect, flags, text): """ Draw the text in a clipping rectangle :param QPainter painter: Painter :param QRectF rect: Clipping rectangle :param int flags: Bitwise OR of the flags like in for QPainter::drawText() :param str text: Text to be rendered """ txt = QwtRichTextDocument(text, flags, painter.font()) painter.save() unscaledRect = QRectF(rect) if painter.font().pixelSize() < 0: res = qwtScreenResolution() pd = painter.device() if pd.logicalDpiX() != res.width()\ or pd.logicalDpiY() != res.height(): transform = QTransform() transform.scale(res.width() / float(pd.logicalDpiX()), res.height() / float(pd.logicalDpiY())) painter.setWorldTransform(transform, True) invtrans, _ok = transform.inverted() unscaledRect = invtrans.mapRect(rect) txt.setDefaultFont(painter.font()) txt.setPageSize(QSizeF(unscaledRect.width(), QWIDGETSIZE_MAX)) layout = txt.documentLayout() height = layout.documentSize().height() y = unscaledRect.y() if flags & Qt.AlignBottom: y += unscaledRect.height() - height elif flags & Qt.AlignVCenter: y += (unscaledRect.height() - height) / 2 context = QAbstractTextDocumentLayout.PaintContext() context.palette.setColor(QPalette.Text, painter.pen().color()) painter.translate(unscaledRect.x(), y) layout.draw(painter, context) painter.restore()
def renderTo(self, plot, dest): """ Render a plot to a file Supported formats are: - pdf: Portable Document Format PDF - ps: Postcript - svg: Scalable Vector Graphics SVG - all image formats supported by Qt, see QImageWriter.supportedImageFormats() Scalable vector graphic formats like PDF or SVG are superior to raster graphics formats. :param qwt.plot.QwtPlot plot: Plot widget :param str fileName: Path of the file, where the document will be stored :param str format: Format for the document :param QSizeF sizeMM: Size for the document in millimeters. :param int resolution: Resolution in dots per Inch (dpi) .. seealso:: :py:meth:`renderTo()`, :py:meth:`render()`, :py:meth:`qwt.painter.QwtPainter.setRoundingAlignment()` """ if isinstance(dest, QPaintDevice): w = dest.width() h = dest.height() rect = QRectF(0, 0, w, h) elif isinstance(dest, QPrinter): w = dest.width() h = dest.height() rect = QRectF(0, 0, w, h) aspect = rect.width()/rect.height() if aspect < 1.: rect.setHeight(aspect*rect.width()) elif isinstance(dest, QSvgGenerator): rect = dest.viewBoxF() if rect.isEmpty(): rect.setRect(0, 0, dest.width(), dest.height()) if rect.isEmpty(): rect.setRect(0, 0, 800, 600) p = QPainter(dest) self.render(plot, p, rect)
def activate(self, plot, plotRect, options=0x00): self.invalidate() rect = QRectF(plotRect) self.__data.layoutData.init(plot, rect) if not (options & self.IgnoreLegend) and plot.legend() and\ not plot.legend().isEmpty(): self.__data.legendRect = self.layoutLegend(options, rect) region = QRegion(rect.toRect()) rect = region.subtracted(QRegion(self.__data.legendRect.toRect()) ).boundingRect() if self.__data.legendPos == QwtPlot.LeftLegend: rect.setLeft(rect.left()+self.__data.spacing) elif self.__data.legendPos == QwtPlot.RightLegend: rect.setRight(rect.right()-self.__data.spacing) elif self.__data.legendPos == QwtPlot.TopLegend: rect.setTop(rect.top()+self.__data.spacing) elif self.__data.legendPos == QwtPlot.BottomLegend: rect.setBottom(rect.bottom()-self.__data.spacing) # +---+-----------+---+ # | Title | # +---+-----------+---+ # | | Axis | | # +---+-----------+---+ # | A | | A | # | x | Canvas | x | # | i | | i | # | s | | s | # +---+-----------+---+ # | | Axis | | # +---+-----------+---+ # | Footer | # +---+-----------+---+ dimTitle, dimFooter, dimAxes = self.expandLineBreaks(options, rect) if dimTitle > 0: self.__data.titleRect.setRect(rect.left(), rect.top(), rect.width(), dimTitle) rect.setTop(self.__data.titleRect.bottom()+self.__data.spacing) if self.__data.layoutData.scale[QwtPlot.yLeft].isEnabled !=\ self.__data.layoutData.scale[QwtPlot.yRight].isEnabled: self.__data.titleRect.setX(rect.left()+dimAxes[QwtPlot.yLeft]) self.__data.titleRect.setWidth(rect.width()\ -dimAxes[QwtPlot.yLeft]-dimAxes[QwtPlot.yRight]) if dimFooter > 0: self.__data.footerRect.setRect(rect.left(), rect.bottom()-dimFooter, rect.width(), dimFooter) rect.setBottom(self.__data.footerRect.top()-self.__data.spacing) if self.__data.layoutData.scale[QwtPlot.yLeft].isEnabled !=\ self.__data.layoutData.scale[QwtPlot.yRight].isEnabled: self.__data.footerRect.setX(rect.left()+dimAxes[QwtPlot.yLeft]) self.__data.footerRect.setWidth(rect.width()\ -dimAxes[QwtPlot.yLeft]-dimAxes[QwtPlot.yRight]) self.__data.canvasRect.setRect( rect.x()+dimAxes[QwtPlot.yLeft], rect.y()+dimAxes[QwtPlot.xTop], rect.width()-dimAxes[QwtPlot.yRight]-dimAxes[QwtPlot.yLeft], rect.height()-dimAxes[QwtPlot.xBottom]-dimAxes[QwtPlot.xTop]) for axis in range(QwtPlot.axisCnt): if dimAxes[axis]: dim = dimAxes[axis] scaleRect = self.__data.scaleRect[axis] scaleRect.setRect(*self.__data.canvasRect.getRect()) if axis == QwtPlot.yLeft: scaleRect.setX(self.__data.canvasRect.left()-dim) scaleRect.setWidth(dim) elif axis == QwtPlot.yRight: scaleRect.setX(self.__data.canvasRect.right()) scaleRect.setWidth(dim) elif axis == QwtPlot.xBottom: scaleRect.setY(self.__data.canvasRect.bottom()) scaleRect.setHeight(dim) elif axis == QwtPlot.xTop: scaleRect.setY(self.__data.canvasRect.top()-dim) scaleRect.setHeight(dim) scaleRect = scaleRect.normalized() # +---+-----------+---+ # | <- Axis -> | # +-^-+-----------+-^-+ # | | | | | | # | | | | # | A | | A | # | x | Canvas | x | # | i | | i | # | s | | s | # | | | | # | | | | | | # +-V-+-----------+-V-+ # | <- Axis -> | # +---+-----------+---+ self.alignScales(options, self.__data.canvasRect, self.__data.scaleRect) if not self.__data.legendRect.isEmpty(): self.__data.legendRect = self.alignLegend(self.__data.canvasRect, self.__data.legendRect)
def renderTo(self, plot, dest): if isinstance(dest, QPaintDevice): w = dest.width() h = dest.height() rect = QRectF(0, 0, w, h) elif isinstance(dest, QPrinter): w = dest.width() h = dest.height() rect = QRectF(0, 0, w, h) aspect = rect.width()/rect.height() if aspect < 1.: rect.setHeight(aspect*rect.width()) elif isinstance(dest, QSvgGenerator): rect = dest.viewBoxF() if rect.isEmpty(): rect.setRect(0, 0, dest.width(), dest.height()) if rect.isEmpty(): rect.setRect(0, 0, 800, 600) p = QPainter(dest) self.render(plot, p, rect)
def layoutLegend(self, options, rect): """ Find the geometry for the legend :param options: Options how to layout the legend :param QRectF rect: Rectangle where to place the legend :return: Geometry for the legend """ hint = self.__data.layoutData.legend.hint if self.__data.legendPos in (QwtPlot.LeftLegend, QwtPlot.RightLegend): dim = min([hint.width(), int(rect.width()*self.__data.legendRatio)]) if not (options & self.IgnoreScrollbars): if hint.height() > rect.height(): dim += self.__data.layoutData.legend.hScrollExtent else: dim = min([hint.height(), int(rect.height()*self.__data.legendRatio)]) dim = max([dim, self.__data.layoutData.legend.vScrollExtent]) legendRect = QRectF(rect) if self.__data.legendPos == QwtPlot.LeftLegend: legendRect.setWidth(dim) elif self.__data.legendPos == QwtPlot.RightLegend: legendRect.setX(rect.right()-dim) legendRect.setWidth(dim) elif self.__data.legendPos == QwtPlot.TopLegend: legendRect.setHeight(dim) elif self.__data.legendPos == QwtPlot.BottomLegend: legendRect.setY(rect.bottom()-dim) legendRect.setHeight(dim) return legendRect
def qwtDrawStar1Symbols(painter, points, numPoints, symbol): size =symbol.size() painter.setPen(symbol.pen()) sqrt1_2 = np.sqrt(.5) r = QRectF(0, 0, size.width(), size.height()) for pos in points: r.moveCenter(pos.toPoint()) c = QPointF(r.center()) d1 = r.width()/2.*(1.-sqrt1_2) painter.drawLine(r.left()+d1, r.top()+d1, r.right()-d1, r.bottom()-d1) painter.drawLine(r.left()+d1, r.bottom()-d1, r.right()-d1, r.top()+d1) painter.drawLine(c.x(), r.top(), c.x(), r.bottom()) painter.drawLine(r.left(), c.y(), r.right(), c.y())
def activate(self, plot, plotRect, options=0x00): """ Recalculate the geometry of all components. :param qwt.plot.QwtPlot plot: Plot to be layout :param QRectF plotRect: Rectangle where to place the components :param options: Layout options """ self.invalidate() rect = QRectF(plotRect) self.__data.layoutData.init(plot, rect) if not (options & self.IgnoreLegend) and plot.legend() and\ not plot.legend().isEmpty(): self.__data.legendRect = self.layoutLegend(options, rect) region = QRegion(rect.toRect()) rect = region.subtracted(QRegion(self.__data.legendRect.toRect()) ).boundingRect() if self.__data.legendPos == QwtPlot.LeftLegend: rect.setLeft(rect.left()+self.__data.spacing) elif self.__data.legendPos == QwtPlot.RightLegend: rect.setRight(rect.right()-self.__data.spacing) elif self.__data.legendPos == QwtPlot.TopLegend: rect.setTop(rect.top()+self.__data.spacing) elif self.__data.legendPos == QwtPlot.BottomLegend: rect.setBottom(rect.bottom()-self.__data.spacing) # +---+-----------+---+ # | Title | # +---+-----------+---+ # | | Axis | | # +---+-----------+---+ # | A | | A | # | x | Canvas | x | # | i | | i | # | s | | s | # +---+-----------+---+ # | | Axis | | # +---+-----------+---+ # | Footer | # +---+-----------+---+ # title, footer and axes include text labels. The height of each # label depends on its line breaks, that depend on the width # for the label. A line break in a horizontal text will reduce # the available width for vertical texts and vice versa. # expandLineBreaks finds the height/width for title, footer and axes # including all line breaks. dimTitle, dimFooter, dimAxes = self.expandLineBreaks(options, rect) if dimTitle > 0: self.__data.titleRect.setRect(rect.left(), rect.top(), rect.width(), dimTitle) rect.setTop(self.__data.titleRect.bottom()+self.__data.spacing) if self.__data.layoutData.scale[QwtPlot.yLeft].isEnabled !=\ self.__data.layoutData.scale[QwtPlot.yRight].isEnabled: self.__data.titleRect.setX(rect.left()+dimAxes[QwtPlot.yLeft]) self.__data.titleRect.setWidth(rect.width()\ -dimAxes[QwtPlot.yLeft]-dimAxes[QwtPlot.yRight]) if dimFooter > 0: self.__data.footerRect.setRect(rect.left(), rect.bottom()-dimFooter, rect.width(), dimFooter) rect.setBottom(self.__data.footerRect.top()-self.__data.spacing) if self.__data.layoutData.scale[QwtPlot.yLeft].isEnabled !=\ self.__data.layoutData.scale[QwtPlot.yRight].isEnabled: self.__data.footerRect.setX(rect.left()+dimAxes[QwtPlot.yLeft]) self.__data.footerRect.setWidth(rect.width()\ -dimAxes[QwtPlot.yLeft]-dimAxes[QwtPlot.yRight]) self.__data.canvasRect.setRect( rect.x()+dimAxes[QwtPlot.yLeft], rect.y()+dimAxes[QwtPlot.xTop], rect.width()-dimAxes[QwtPlot.yRight]-dimAxes[QwtPlot.yLeft], rect.height()-dimAxes[QwtPlot.xBottom]-dimAxes[QwtPlot.xTop]) for axis in QwtPlot.validAxes: if dimAxes[axis]: dim = dimAxes[axis] scaleRect = self.__data.scaleRect[axis] scaleRect.setRect(*self.__data.canvasRect.getRect()) if axis == QwtPlot.yLeft: scaleRect.setX(self.__data.canvasRect.left()-dim) scaleRect.setWidth(dim) elif axis == QwtPlot.yRight: scaleRect.setX(self.__data.canvasRect.right()) scaleRect.setWidth(dim) elif axis == QwtPlot.xBottom: scaleRect.setY(self.__data.canvasRect.bottom()) scaleRect.setHeight(dim) elif axis == QwtPlot.xTop: scaleRect.setY(self.__data.canvasRect.top()-dim) scaleRect.setHeight(dim) scaleRect = scaleRect.normalized() # +---+-----------+---+ # | <- Axis -> | # +-^-+-----------+-^-+ # | | | | | | # | | | | # | A | | A | # | x | Canvas | x | # | i | | i | # | s | | s | # | | | | # | | | | | | # +-V-+-----------+-V-+ # | <- Axis -> | # +---+-----------+---+ # The ticks of the axes - not the labels above - should # be aligned to the canvas. So we try to use the empty # corners to extend the axes, so that the label texts # left/right of the min/max ticks are moved into them. self.alignScales(options, self.__data.canvasRect, self.__data.scaleRect) if not self.__data.legendRect.isEmpty(): self.__data.legendRect = self.alignLegend(self.__data.canvasRect, self.__data.legendRect)
def qwtBoundingRectT(series, from_, to): boundingRect = QRectF(1.0, 1.0, -2.0, -2.0) if from_ < 0: from_ = 0 if to < 0: to = series.size() - 1 if to < from_: return boundingRect first_stage = True for i in range(from_, to + 1): rect = qwtBoundingRect(series.sample(i)) if rect.width() >= 0.0 and rect.height() >= 0.0: if first_stage: boundingRect = rect first_stage = False continue else: boundingRect.setLeft(min([boundingRect.left(), rect.left()])) boundingRect.setRight(max([boundingRect.right(), rect.right()])) boundingRect.setTop(min([boundingRect.top(), rect.top()])) boundingRect.setBottom(max([boundingRect.bottom(), rect.bottom()])) return boundingRect
def colorBarRect(self, rect): """ Calculate the the rectangle for the color bar :param QRectF rect: Bounding rectangle for all components of the scale :return: Rectangle for the color bar """ cr = QRectF(rect) if self.__data.scaleDraw.orientation() == Qt.Horizontal: cr.setLeft(cr.left() + self.__data.borderDist[0]) cr.setWidth(cr.width() - self.__data.borderDist[1] + 1) else: cr.setTop(cr.top() + self.__data.borderDist[0]) cr.setHeight(cr.height() - self.__data.borderDist[1] + 1) sda = self.__data.scaleDraw.alignment() if sda == QwtScaleDraw.LeftScale: cr.setLeft(cr.right()-self.__data.margin-self.__data.colorBar.width) cr.setWidth(self.__data.colorBar.width) elif sda == QwtScaleDraw.RightScale: cr.setLeft(cr.left()+self.__data.margin) cr.setWidth(self.__data.colorBar.width) elif sda == QwtScaleDraw.BottomScale: cr.setTop(cr.top()+self.__data.margin) cr.setHeight(self.__data.colorBar.width) elif sda == QwtScaleDraw.TopScale: cr.setTop(cr.bottom()-self.__data.margin-self.__data.colorBar.width) cr.setHeight(self.__data.colorBar.width) return cr
def colorBarRect(self, rect): cr = QRectF(rect) if self.__data.scaleDraw.orientation() == Qt.Horizontal: cr.setLeft(cr.left() + self.__data.borderDist[0]) cr.setWidth(cr.width() - self.__data.borderDist[1] + 1) else: cr.setTop(cr.top() + self.__data.borderDist[0]) cr.setHeight(cr.height() - self.__data.borderDist[1] + 1) sda = self.__data.scaleDraw.alignment() if sda == QwtScaleDraw.LeftScale: cr.setLeft(cr.right()-self.__data.margin-self.__data.colorBar.width) cr.setWidth(self.__data.colorBar.width) elif sda == QwtScaleDraw.RightScale: cr.setLeft(cr.left()+self.__data.margin) cr.setWidth(self.__data.colorBar.width) elif sda == QwtScaleDraw.BottomScale: cr.setTop(cr.top()+self.__data.margin) cr.setHeight(self.__data.colorBar.width) elif sda == QwtScaleDraw.TopScale: cr.setTop(cr.bottom()-self.__data.margin-self.__data.colorBar.width) cr.setHeight(self.__data.colorBar.width) return cr
def layoutLegend(self, options, rect): hint = self.__data.layoutData.legend.hint if self.__data.legendPos in (QwtPlot.LeftLegend, QwtPlot.RightLegend): dim = min([hint.width(), int(rect.width()*self.__data.legendRatio)]) if not (options & self.IgnoreScrollbars): if hint.height() > rect.height(): dim += self.__data.layoutData.legend.hScrollExtent else: dim = min([hint.height(), int(rect.height()*self.__data.legendRatio)]) dim = max([dim, self.__data.layoutData.legend.vScrollExtent]) legendRect = QRectF(rect) if self.__data.legendPos == QwtPlot.LeftLegend: legendRect.setWidth(dim) elif self.__data.legendPos == QwtPlot.RightLegend: legendRect.setX(rect.right()-dim) legendRect.setWidth(dim) elif self.__data.legendPos == QwtPlot.TopLegend: legendRect.setHeight(dim) elif self.__data.legendPos == QwtPlot.BottomLegend: legendRect.setY(rect.bottom()-dim) legendRect.setHeight(dim) return legendRect
def render(self, *args): """ .. py:method:: render(painter) Replay all recorded painter commands :param QPainter painter: Qt painter .. py:method:: render(painter, size, aspectRatioMode) Replay all recorded painter commands The graphic is scaled to fit into the rectangle of the given size starting at ( 0, 0 ). :param QPainter painter: Qt painter :param QSizeF size: Size for the scaled graphic :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale .. py:method:: render(painter, rect, aspectRatioMode) Replay all recorded painter commands The graphic is scaled to fit into the given rectangle :param QPainter painter: Qt painter :param QRectF rect: Rectangle for the scaled graphic :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale .. py:method:: render(painter, pos, aspectRatioMode) Replay all recorded painter commands The graphic is scaled to the :py:meth:`defaultSize()` and aligned to a position. :param QPainter painter: Qt painter :param QPointF pos: Reference point, where to render :param Qt.AspectRatioMode aspectRatioMode: Mode how to scale """ if len(args) == 1: painter, = args if self.isNull(): return transform = painter.transform() painter.save() for command in self.__data.commands: qwtExecCommand(painter, command, self.__data.renderHints, transform, self.__data.initialTransform) painter.restore() elif len(args) in (2, 3) and isinstance(args[1], QSizeF): painter, size = args[:2] aspectRatioMode = Qt.IgnoreAspectRatio if len(args) == 3: aspectRatioMode = args[-1] r = QRectF(0., 0., size.width(), size.height()) self.render(painter, r, aspectRatioMode) elif len(args) in (2, 3) and isinstance(args[1], QRectF): painter, rect = args[:2] aspectRatioMode = Qt.IgnoreAspectRatio if len(args) == 3: aspectRatioMode = args[-1] if self.isEmpty() or rect.isEmpty(): return sx = 1. sy = 1. if self.__data.pointRect.width() > 0.: sx = rect.width()/self.__data.pointRect.width() if self.__data.pointRect.height() > 0.: sy = rect.height()/self.__data.pointRect.height() scalePens = not bool(self.__data.renderHints & self.RenderPensUnscaled) for info in self.__data.pathInfos: ssx = info.scaleFactorX(self.__data.pointRect, rect, scalePens) if ssx > 0.: sx = min([sx, ssx]) ssy = info.scaleFactorY(self.__data.pointRect, rect, scalePens) if ssy > 0.: sy = min([sy, ssy]) if aspectRatioMode == Qt.KeepAspectRatio: s = min([sx, sy]) sx = s sy = s elif aspectRatioMode == Qt.KeepAspectRatioByExpanding: s = max([sx, sy]) sx = s sy = s tr = QTransform() tr.translate(rect.center().x()-.5*sx*self.__data.pointRect.width(), rect.center().y()-.5*sy*self.__data.pointRect.height()) tr.scale(sx, sy) tr.translate(-self.__data.pointRect.x(), -self.__data.pointRect.y()) transform = painter.transform() if not scalePens and transform.isScaling(): # we don't want to scale pens according to sx/sy, # but we want to apply the scaling from the # painter transformation later self.__data.initialTransform = QTransform() self.__data.initialTransform.scale(transform.m11(), transform.m22()) painter.setTransform(tr, True) self.render(painter) painter.setTransform(transform) self.__data.initialTransform = None elif len(args) in (2, 3) and isinstance(args[1], QPointF): painter, pos = args[:2] alignment = Qt.AlignTop|Qt.AlignLeft if len(args) == 3: alignment = args[-1] r = QRectF(pos, self.defaultSize()) if alignment & Qt.AlignLeft: r.moveLeft(pos.x()) elif alignment & Qt.AlignHCenter: r.moveCenter(QPointF(pos.x(), r.center().y())) elif alignment & Qt.AlignRight: r.moveRight(pos.x()) if alignment & Qt.AlignTop: r.moveTop(pos.y()) elif alignment & Qt.AlignVCenter: r.moveCenter(QPointF(r.center().x(), pos.y())) elif alignment & Qt.AlignBottom: r.moveBottom(pos.y()) self.render(painter, r) else: raise TypeError("%s().render() takes 1, 2 or 3 argument(s) (%s "\ "given)" % (self.__class__.__name__, len(args)))
def boundingRect(self): """ Calculate the bounding rectangle for a symbol at position (0,0). :return: Bounding rectangle """ rect = QRectF() pinPointTranslation = False if self.__data.style in (QwtSymbol.Ellipse, QwtSymbol.Rect, QwtSymbol.Hexagon): pw = 0. if self.__data.pen.style() != Qt.NoPen: pw = max([self.__data.pen.widthF(), 1.]) rect.setSize(self.__data.size+QSizeF(pw, pw)) rect.moveCenter(QPointF(0., 0.)) elif self.__data.style in (QwtSymbol.XCross, QwtSymbol.Diamond, QwtSymbol.Triangle, QwtSymbol.UTriangle, QwtSymbol.DTriangle, QwtSymbol.RTriangle, QwtSymbol.LTriangle, QwtSymbol.Star1, QwtSymbol.Star2): pw = 0. if self.__data.pen.style() != Qt.NoPen: pw = max([self.__data.pen.widthF(), 1.]) rect.setSize(QSizeF(self.__data.size)+QSizeF(2*pw, 2*pw)) rect.moveCenter(QPointF(0., 0.)) elif self.__data.style == QwtSymbol.Path: if self.__data.path.graphic.isNull(): self.__data.path.graphic = qwtPathGraphic( self.__data.path.path, self.__data.pen, self.__data.brush) rect = qwtScaleBoundingRect(self.__data.path.graphic, self.__data.size) pinPointTranslation = True elif self.__data.style == QwtSymbol.Pixmap: if self.__data.size.isEmpty(): rect.setSize(self.__data.pixmap.pixmap.size()) else: rect.setSize(self.__data.size) pinPointTranslation = True elif self.__data.style == QwtSymbol.Graphic: rect = qwtScaleBoundingRect(self.__data.graphic.graphic, self.__data.size) pinPointTranslation = True elif self.__data.style == QwtSymbol.SvgDocument: if self.__data.svg.renderer is not None: rect = self.__data.svg.renderer.viewBoxF() if self.__data.size.isValid() and not rect.isEmpty(): sz = QSizeF(rect.size()) sx = self.__data.size.width()/sz.width() sy = self.__data.size.height()/sz.height() transform = QTransform() transform.scale(sx, sy) rect = transform.mapRect(rect) pinPointTranslation = True else: rect.setSize(self.__data.size) rect.moveCenter(QPointF(0., 0.)) if pinPointTranslation: pinPoint = QPointF(0., 0.) if self.__data.isPinPointEnabled: pinPoint = rect.center()-self.__data.pinPoint rect.moveCenter(pinPoint) r = QRect() r.setLeft(np.floor(rect.left())) r.setTop(np.floor(rect.top())) r.setRight(np.floor(rect.right())) r.setBottom(np.floor(rect.bottom())) if self.__data.style != QwtSymbol.Pixmap: r.adjust(-1, -1, 1, 1) return r
def minLabelDist(self, font): """ Determine the minimum distance between two labels, that is necessary that the texts don't overlap. :param QFont font: Font :return: The maximum width of a label .. seealso:: :py:meth:`getBorderDistHint()` """ if not self.hasComponent(QwtAbstractScaleDraw.Labels): return 0 ticks = self.scaleDiv().ticks(QwtScaleDiv.MajorTick) if not ticks: return 0 fm = QFontMetrics(font) vertical = self.orientation() == Qt.Vertical bRect1 = QRectF() bRect2 = self.labelRect(font, ticks[0]) if vertical: bRect2.setRect(-bRect2.bottom(), 0., bRect2.height(), bRect2.width()) maxDist = 0. for tick in ticks: bRect1 = bRect2 bRect2 = self.labelRect(font, tick) if vertical: bRect2.setRect(-bRect2.bottom(), 0., bRect2.height(), bRect2.width()) dist = fm.leading() if bRect1.right() > 0: dist += bRect1.right() if bRect2.left() < 0: dist += -bRect2.left() if dist > maxDist: maxDist = dist angle = qwtRadians(self.labelRotation()) if vertical: angle += np.pi/2 sinA = np.sin(angle) if qFuzzyCompare(sinA+1., 1.): return np.ceil(maxDist) fmHeight = fm.ascent()-2 labelDist = fmHeight/np.sin(angle)*np.cos(angle) if labelDist < 0: labelDist = -labelDist if labelDist > maxDist: labelDist = maxDist if labelDist < fmHeight: labelDist = fmHeight return np.ceil(labelDist)