Beispiel #1
0
    def scaledBoundingRect(self, sx, sy):
        """
        Calculate the target rectangle for scaling the graphic
        
        :param float sx: Horizontal scaling factor 
        :param float sy: Vertical scaling factor 
        :return: Scaled bounding rectangle
            
        .. note::
        
            In case of paths that are painted with a cosmetic pen 
            (see :py:meth:`QPen.isCosmetic()`) the target rectangle is 
            different to multiplying the bounding rectangle.

        .. seealso::
        
            :py:meth:`boundingRect()`, :py:meth:`controlPointRect()`
        """
        if sx == 1.0 and sy == 1.0:
            return self.__data.boundingRect
        transform = QTransform()
        transform.scale(sx, sy)
        rect = transform.mapRect(self.__data.pointRect)
        for pathInfo in self.__data.pathInfos:
            rect |= pathInfo.scaledBoundingRect(
                sx, sy,
                not bool(self.__data.renderHints & self.RenderPensUnscaled))
        return rect
Beispiel #2
0
 def __init__(self,
              image,
              name="",
              invertY=False,
              xlabel: str = None,
              ylabel: str = None,
              transform=None,
              z: int = None,
              **kwargs):
     self._name = name
     super(ImageHint, self).__init__()
     self.count = next(self.ref_count)
     self.image = image
     self.invertY = invertY
     self.xlabel = xlabel
     self.ylabel = ylabel
     self.transform = transform
     if transform is None:
         transform = QTransform()
         transform.translate(0, -1)
         transform.scale(0, -1)
         self.transform = transform
     self.z = z
     self.kwargs = kwargs
     self.enabled = False
     self.canvas = None
Beispiel #3
0
 def setZoom(self, x, y):
     self.zx = x
     self.zy = y
     trans = QTransform()
     trans.scale(self.zx, self.zy)
     self.setTransform(trans)
     for vert in self.vertItems:
         vert.updateZoom(self.zx, self.zy)
Beispiel #4
0
 def updateZoom(self, zx, zy):
     trans = QTransform()
     trans.scale(1.0 / zx, 1.0 / zy)
     # self.setTransform( trans )
     self.VP.setTransform(trans)
     self.preBP.setTransform(trans)
     self.postBP.setTransform(trans)
     self.updateTPPos()
Beispiel #5
0
 def scaledBoundingRect(self, sx, sy, scalePens):
     if sx == 1.0 and sy == 1.0:
         return self.__boundingRect
     transform = QTransform()
     transform.scale(sx, sy)
     if scalePens and self.__scalablePen:
         rect = transform.mapRect(self.__boundingRect)
     else:
         rect = transform.mapRect(self.__pointRect)
         l = abs(self.__pointRect.left() - self.__boundingRect.left())
         r = abs(self.__pointRect.right() - self.__boundingRect.right())
         t = abs(self.__pointRect.top() - self.__boundingRect.top())
         b = abs(self.__pointRect.bottom() - self.__boundingRect.bottom())
         rect.adjust(-l, -t, r, b)
     return rect
Beispiel #6
0
    def monitor_images(self):
        while self.active:
            if self.last_frame:
                image_array = self.style.stylize(self.last_frame)
                image = QImage(image_array.data, image_array.shape[1],
                               image_array.shape[0], image_array.strides[0],
                               QImage.Format_RGB888)

                rotating = QTransform()
                rotating.scale(-1, 1)  # mirror
                rotating.rotate(settings.ROTATE_IMAGE)
                image = image.transformed(rotating)

                self.image_signal.emit(StyledCapture(image, self.style.name))

            # check for stop/changes
            QApplication.processEvents()
Beispiel #7
0
def qwtDrawGraphicSymbols(painter, points, numPoint, graphic, symbol):
    pointRect = QRectF(graphic.controlPointRect())
    if pointRect.isEmpty():
        return
    sx = 1.0
    sy = 1.0
    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)
Beispiel #8
0
    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()
Beispiel #9
0
    def _paint_icon(self, iconic, painter, rect, mode, state, options):
        """Paint a single icon."""
        painter.save()
        color = options['color']
        char = options['char']

        color_options = {
            QIcon.On: {
                QIcon.Normal: (options['color_on'], options['on']),
                QIcon.Disabled:
                (options['color_on_disabled'], options['on_disabled']),
                QIcon.Active:
                (options['color_on_active'], options['on_active']),
                QIcon.Selected:
                (options['color_on_selected'], options['on_selected'])
            },
            QIcon.Off: {
                QIcon.Normal: (options['color_off'], options['off']),
                QIcon.Disabled:
                (options['color_off_disabled'], options['off_disabled']),
                QIcon.Active:
                (options['color_off_active'], options['off_active']),
                QIcon.Selected:
                (options['color_off_selected'], options['off_selected'])
            }
        }

        color, char = color_options[state][mode]

        painter.setPen(QColor(color))

        # A 16 pixel-high icon yields a font size of 14, which is pixel perfect
        # for font-awesome. 16 * 0.875 = 14
        # The reason why the glyph size is smaller than the icon size is to
        # account for font bearing.

        draw_size = round(0.875 * rect.height() * options['scale_factor'])
        prefix = options['prefix']

        # Animation setup hook
        animation = options.get('animation')
        if animation is not None:
            animation.setup(self, painter, rect)

        painter.setFont(iconic.font(prefix, draw_size))
        if 'offset' in options:
            rect = QRect(rect)
            rect.translate(round(options['offset'][0] * rect.width()),
                           round(options['offset'][1] * rect.height()))

        if 'vflip' in options and options['vflip'] == True:
            x_center = rect.width() * 0.5
            y_center = rect.height() * 0.5
            painter.translate(x_center, y_center)
            transfrom = QTransform()
            transfrom.scale(1, -1)
            painter.setTransform(transfrom, True)
            painter.translate(-x_center, -y_center)

        if 'hflip' in options and options['hflip'] == True:
            x_center = rect.width() * 0.5
            y_center = rect.height() * 0.5
            painter.translate(x_center, y_center)
            transfrom = QTransform()
            transfrom.scale(-1, 1)
            painter.setTransform(transfrom, True)
            painter.translate(-x_center, -y_center)

        if 'rotated' in options:
            x_center = rect.width() * 0.5
            y_center = rect.height() * 0.5
            painter.translate(x_center, y_center)
            painter.rotate(options['rotated'])
            painter.translate(-x_center, -y_center)

        painter.setOpacity(options.get('opacity', 1.0))

        painter.drawText(rect, int(Qt.AlignCenter | Qt.AlignVCenter), char)
        painter.restore()
Beispiel #10
0
    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.0
            if self.__data.pen.style() != Qt.NoPen:
                pw = max([self.__data.pen.widthF(), 1.0])
            rect.setSize(self.__data.size + QSizeF(pw, pw))
            rect.moveCenter(QPointF(0.0, 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.0
            if self.__data.pen.style() != Qt.NoPen:
                pw = max([self.__data.pen.widthF(), 1.0])
            rect.setSize(QSizeF(self.__data.size) + QSizeF(2 * pw, 2 * pw))
            rect.moveCenter(QPointF(0.0, 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, 0.0))
        if pinPointTranslation:
            pinPoint = QPointF(0.0, 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
Beispiel #11
0
 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, 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.0
         sy = 1.0
         if self.__data.pointRect.width() > 0.0:
             sx = rect.width() / self.__data.pointRect.width()
         if self.__data.pointRect.height() > 0.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.0:
                 sx = min([sx, ssx])
             ssy = info.scaleFactorY(self.__data.pointRect, rect, scalePens)
             if ssy > 0.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() - 0.5 * sx * self.__data.pointRect.width(),
             rect.center().y() - 0.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)))
Beispiel #12
0
    def render(self, plot, painter, plotRect):
        """
        Paint the contents of a QwtPlot instance into a given rectangle.

        :param qwt.plot.QwtPlot plot: Plot to be rendered
        :param QPainter painter: Painter
        :param str format: Format for the document
        :param QRectF plotRect: Bounding rectangle

        .. seealso::

            :py:meth:`renderDocument()`, :py:meth:`renderTo()`,
            :py:meth:`qwt.painter.QwtPainter.setRoundingAlignment()`
        """
        if (painter == 0 or not painter.isActive() or not plotRect.isValid()
                or plot.size().isNull()):
            return
        if not self.__data.discardFlags & self.DiscardBackground:
            QwtPainter.drawBackground(painter, plotRect, plot)

        #  The layout engine uses the same methods as they are used
        #  by the Qt layout system. Therefore we need to calculate the
        #  layout in screen coordinates and paint with a scaled painter.
        transform = QTransform()
        transform.scale(
            float(painter.device().logicalDpiX()) / plot.logicalDpiX(),
            float(painter.device().logicalDpiY()) / plot.logicalDpiY(),
        )

        invtrans, _ok = transform.inverted()
        layoutRect = invtrans.mapRect(plotRect)
        if not (self.__data.discardFlags & self.DiscardBackground):
            left, top, right, bottom = plot.layout().getContentsMargins()
            layoutRect.adjust(left, top, -right, -bottom)

        layout = plot.plotLayout()
        baseLineDists = canvasMargins = [None] * len(QwtPlot.AXES)

        for axisId in QwtPlot.AXES:
            canvasMargins[axisId] = layout.canvasMargin(axisId)
            if self.__data.layoutFlags & self.FrameWithScales:
                scaleWidget = plot.axisWidget(axisId)
                if scaleWidget:
                    baseLineDists[axisId] = max(
                        scaleWidget.getContentsMargins())
                    scaleWidget.setMargin(0)
                if not plot.axisEnabled(axisId):
                    #  When we have a scale the frame is painted on
                    #  the position of the backbone - otherwise we
                    #  need to introduce a margin around the canvas
                    if axisId == QwtPlot.yLeft:
                        layoutRect.adjust(1, 0, 0, 0)
                    elif axisId == QwtPlot.yRight:
                        layoutRect.adjust(0, 0, -1, 0)
                    elif axisId == QwtPlot.xTop:
                        layoutRect.adjust(0, 1, 0, 0)
                    elif axisId == QwtPlot.xBottom:
                        layoutRect.adjust(0, 0, 0, -1)

        #  Calculate the layout for the document.
        layoutOptions = QwtPlotLayout.IgnoreScrollbars

        if (self.__data.layoutFlags & self.FrameWithScales
                or self.__data.discardFlags & self.DiscardCanvasFrame):
            layoutOptions |= QwtPlotLayout.IgnoreFrames

        if self.__data.discardFlags & self.DiscardLegend:
            layoutOptions |= QwtPlotLayout.IgnoreLegend
        if self.__data.discardFlags & self.DiscardTitle:
            layoutOptions |= QwtPlotLayout.IgnoreTitle
        if self.__data.discardFlags & self.DiscardFooter:
            layoutOptions |= QwtPlotLayout.IgnoreFooter

        layout.activate(plot, layoutRect, layoutOptions)

        maps = self.buildCanvasMaps(plot, layout.canvasRect())
        if self.updateCanvasMargins(plot, layout.canvasRect(), maps):
            #  recalculate maps and layout, when the margins
            #  have been changed
            layout.activate(plot, layoutRect, layoutOptions)
            maps = self.buildCanvasMaps(plot, layout.canvasRect())

        painter.save()
        painter.setWorldTransform(transform, True)

        self.renderCanvas(plot, painter, layout.canvasRect(), maps)

        if (not self.__data.discardFlags
                & self.DiscardTitle) and plot.titleLabel().text():
            self.renderTitle(plot, painter, layout.titleRect())

        if (not self.__data.discardFlags
                & self.DiscardFooter) and plot.titleLabel().text():
            self.renderFooter(plot, painter, layout.footerRect())

        if (not self.__data.discardFlags
                & self.DiscardLegend) and plot.titleLabel().text():
            self.renderLegend(plot, painter, layout.legendRect())

        for axisId in QwtPlot.AXES:
            scaleWidget = plot.axisWidget(axisId)
            if scaleWidget:
                baseDist = max(scaleWidget.getContentsMargins())
                startDist, endDist = scaleWidget.getBorderDistHint()
                self.renderScale(
                    plot,
                    painter,
                    axisId,
                    startDist,
                    endDist,
                    baseDist,
                    layout.scaleRect(axisId),
                )

        painter.restore()

        for axisId in QwtPlot.AXES:
            if self.__data.layoutFlags & self.FrameWithScales:
                scaleWidget = plot.axisWidget(axisId)
                if scaleWidget:
                    scaleWidget.setMargin(baseLineDists[axisId])
            layout.setCanvasMargin(canvasMargins[axisId])

        layout.invalidate()