Пример #1
0
    def _print(self):
        """Do the printing, hide the print preview dialog,
        set :attr:`_toBeCleared` flag to True to trigger clearing the
        next time the dialog is shown.

        If the printer is not setup, do it first."""
        printer = self.printer

        painter = qt.QPainter()
        if not painter.begin(printer) or printer is None:
            _logger.error("Cannot initialize printer")
            return
        try:
            self.scene.render(
                painter, qt.QRectF(0, 0, printer.width(), printer.height()),
                qt.QRectF(self.page.rect().x(),
                          self.page.rect().y(),
                          self.page.rect().width(),
                          self.page.rect().height()), qt.Qt.KeepAspectRatio)
            painter.end()
            self.hide()
            self.accept()
            self._toBeCleared = True
        except:  # FIXME
            painter.end()
            qt.QMessageBox.critical(
                self, "ERROR", 'Printing problem:\n %s' % sys.exc_info()[1])
            _logger.error('printing problem:\n %s' % sys.exc_info()[1])
            return
Пример #2
0
    def __createCompoundIcon(self, backgroundIcon, foregroundIcon):
        icon = qt.QIcon()

        sizes = backgroundIcon.availableSizes()
        sizes = sorted(sizes, key=lambda s: s.height())
        sizes = filter(lambda s: s.height() < 100, sizes)
        sizes = list(sizes)
        if len(sizes) > 0:
            baseSize = sizes[-1]
        else:
            baseSize = qt.QSize(32, 32)

        modes = [qt.QIcon.Normal, qt.QIcon.Disabled]
        for mode in modes:
            pixmap = qt.QPixmap(baseSize)
            pixmap.fill(qt.Qt.transparent)
            painter = qt.QPainter(pixmap)
            painter.drawPixmap(0, 0, backgroundIcon.pixmap(baseSize,
                                                           mode=mode))
            painter.drawPixmap(0, 0, foregroundIcon.pixmap(baseSize,
                                                           mode=mode))
            painter.end()
            icon.addPixmap(pixmap, mode=mode)

        return icon
Пример #3
0
    def printPlot(self):
        """Open the print dialog and print the plot.

        Use :meth:`Plot.saveGraph` to print the plot.

        :return: True if successful
        """
        # Init printer and start printer dialog
        dialog = qt.QPrintDialog(self.getPrinter(), self.plot)
        dialog.setWindowTitle('Print Plot')
        if not dialog.exec_():
            return False

        # Save Plot as PNG and make a pixmap from it with default dpi
        pngData = _plotAsPNG(self.plot)

        pixmap = qt.QPixmap()
        pixmap.loadFromData(pngData, 'png')

        xScale = self.getPrinter().pageRect().width() / pixmap.width()
        yScale = self.getPrinter().pageRect().height() / pixmap.height()
        scale = min(xScale, yScale)

        # Draw pixmap with painter
        painter = qt.QPainter()
        if not painter.begin(self.getPrinter()):
            return False

        painter.drawPixmap(0, 0,
                           pixmap.width() * scale,
                           pixmap.height() * scale,
                           pixmap)
        painter.end()

        return True
Пример #4
0
    def _triggered(self, checked=False):
        plot3d = self.getPlot3DWidget()
        if plot3d is None:
            _logger.error('Cannot print widget, no associated Plot3DWidget')
        else:
            printer = self.getPrinter()
            dialog = qt.QPrintDialog(printer, plot3d)
            dialog.setWindowTitle('Print Plot3D snapshot')
            if not dialog.exec_():
                return

            image = plot3d.grabGL()

            # Draw pixmap with painter
            painter = qt.QPainter()
            if not painter.begin(printer):
                return

            if (printer.pageRect().width() < image.width()
                    or printer.pageRect().height() < image.height()):
                # Downscale to page
                xScale = printer.pageRect().width() / image.width()
                yScale = printer.pageRect().height() / image.height()
                scale = min(xScale, yScale)
            else:
                scale = 1.

            rect = qt.QRectF(0, 0, scale * image.width(),
                             scale * image.height())
            painter.drawImage(rect, image)
            painter.end()
Пример #5
0
    def printPlotAsWidget(self):
        """Open the print dialog and print the plot.

        Use :meth:`QWidget.render` to print the plot

        :return: True if successful
        """
        dialog = qt.QPrintDialog(self.getPrinter(), self.plot)
        dialog.setWindowTitle('Print Plot')
        if not dialog.exec_():
            return False

        # Print a snapshot of the plot widget at the top of the page
        widget = self.plot.centralWidget()

        painter = qt.QPainter()
        if not painter.begin(self.getPrinter()):
            return False

        pageRect = self.getPrinter().pageRect()
        xScale = pageRect.width() / widget.width()
        yScale = pageRect.height() / widget.height()
        scale = min(xScale, yScale)

        painter.translate(pageRect.width() / 2., 0.)
        painter.scale(scale, scale)
        painter.translate(-widget.width() / 2., 0.)
        widget.render(painter)
        painter.end()

        return True
Пример #6
0
 def paintEvent(self, e):
     txt = self.currentText()
     if txt.startswith('no'):
         super(LineStyleComboBox, self).paintEvent(e)
         return
     lineStyle = lineStyles[lineStylesText[txt]]
     p = qt.QStylePainter(self)
     p.setPen(self.palette().color(qt.QPalette.Text))
     opt = qt.QStyleOptionComboBox()
     self.initStyleOption(opt)
     p.drawComplexControl(qt.QStyle.CC_ComboBox, opt)
     painter = qt.QPainter(self)
     painter.save()
     painter.setRenderHint(qt.QPainter.Antialiasing, False)
     rect = p.style().subElementRect(qt.QStyle.SE_ComboBoxFocusRect, opt,
                                     self)
     rect.adjust(+5, 0, -5, 0)
     pen = qt.QPen()
     pen.setColor(qt.QColor(self.parent().color))
     pen.setWidth(self.parent().widthSpinBox.value() * 1.5)
     pen.setStyle(lineStyle)
     painter.setPen(pen)
     middle = (rect.bottom() + rect.top()) / 2
     painter.drawLine(rect.left(), middle, rect.right(), middle)
     painter.restore()
Пример #7
0
    def paintEvent(self, event):

        border = self._histoBorder
        pixmap = self.__pixmap

        painter = Qt.QPainter(self)

        rect = self.frameRect().adjusted(border, border, -border, -border)

        if not pixmap:
            painter.save()
            painter.setPen(Qt.QColor(Qt.Qt.gray))
            painter.setBrush(Qt.QColor(Qt.Qt.white))
            painter.drawRect(rect)
            painter.restore()
        else:
            painter.drawPixmap(rect, pixmap, pixmap.rect())

            painter.save()
            painter.setBrush(Qt.QColor(Qt.Qt.black))
            lineMin = self.__lineMin
            if lineMin:
                xLine = lineMin * (rect.width() - 1.) / (pixmap.width() - 1)
                painter.drawRect(xLine - 2, 0, 2, rect.height())
            lineMax = self.__lineMax
            if lineMax:
                xLine = lineMax * (rect.width() - 1.) / (pixmap.width() - 1)
                painter.drawRect(xLine + 2, 0, 2, rect.height())
            painter.restore()
Пример #8
0
    def setProfile(self, x, y, colormap):
        """

        :param profile: a 1D numpy array
        :param colormap: an XsocsPlot2DColormap instance
        :param nColors: number of colors
        :return:
        """
        assert x.ndim == 1
        assert y.ndim == 1

        self.__colormap = colormap
        self.__pixmap = pixmap = Qt.QPixmap(Qt.QSize(x.size,
                                                     self._pimapHeight))
        pixmap.fill()

        xMin = x.min()
        xMax = x.max()

        colors = _applyColormap(colormap, x)
        profileValues = (y * (1.0 * self._pimapHeight / y.max()))
        points = [Qt.QPointF(0, 0)]
        points.extend(
            [Qt.QPointF(idx, val) for idx, val in enumerate(profileValues)])
        points.extend([Qt.QPointF(colormap.nColors - 1, 0)])
        poly = Qt.QPolygonF(points)

        if colormap.minVal is not None:
            lineMin = ((colormap.minVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMin = None

        if colormap.maxVal is not None:
            lineMax = ((colormap.maxVal - xMin) * (pixmap.width() - 1) /
                       (xMax - xMin))
        else:
            lineMax = None

        self.__lineMin = lineMin
        self.__lineMax = lineMax

        gradient = Qt.QLinearGradient(Qt.QPoint(0, 0),
                                      Qt.QPoint(colormap.nColors - 1, 0))
        for idx, color in enumerate(colors):
            qColor = Qt.QColor.fromRgbF(*color)
            gradient.setColorAt(idx / (1.0 * (colormap.nColors - 1)), qColor)

        painter = Qt.QPainter(pixmap)
        painter.save()
        painter.scale(1, -1.)
        painter.translate(Qt.QPointF(0., -1.0 * self._pimapHeight))
        brush = Qt.QBrush(gradient)
        painter.setBrush(brush)
        painter.setPen(Qt.QPen(Qt.Qt.NoPen))
        painter.drawPolygon(poly)
        painter.restore()
        painter.end()
        self.update()
Пример #9
0
def rasterText(text, font, size=-1, weight=-1, italic=False):
    """Raster text using Qt.

    It supports multiple lines.

    :param str text: The text to raster
    :param font: Font name or QFont to use
    :type font: str or :class:`QFont`
    :param int size:
        Font size in points
        Used only if font is given as name.
    :param int weight:
        Font weight in [0, 99], see QFont.Weight.
        Used only if font is given as name.
    :param bool italic:
        True for italic font (default: False).
        Used only if font is given as name.
    :return: Corresponding image in gray scale and baseline offset from top
    :rtype: (HxW numpy.ndarray of uint8, int)
    """
    if not text:
        _logger.info("Trying to raster empty text, replaced by white space")
        text = ' '  # Replace empty text by white space to produce an image

    if not isinstance(font, qt.QFont):
        font = qt.QFont(font, size, weight, italic)

    metrics = qt.QFontMetrics(font)
    size = metrics.size(qt.Qt.TextExpandTabs, text)
    bounds = metrics.boundingRect(qt.QRect(0, 0, size.width(), size.height()),
                                  qt.Qt.TextExpandTabs, text)

    width = bounds.width() + 2  # Add extra border
    # align line size to 32 bits to ease conversion to numpy array
    width = 4 * ((width + 3) // 4)
    image = qt.QImage(width, bounds.height(), qt.QImage.Format_RGB888)
    # TODO if Qt5 use Format_Grayscale8 instead
    image.fill(0)

    # Raster text
    painter = qt.QPainter()
    painter.begin(image)
    painter.setPen(qt.Qt.white)
    painter.setFont(font)
    painter.drawText(bounds, qt.Qt.TextExpandTabs, text)
    painter.end()

    array = convertQImageToArray(image)

    # RGB to R
    array = numpy.ascontiguousarray(array[:, :, 0])

    return array, metrics.ascent()
Пример #10
0
 def icon(self):
     pixmap = qt.QPixmap(2, 2)
     painter = qt.QPainter(pixmap)
     painter.setPen(qt.QColor(255, 0, 0))
     painter.drawPoint(qt.QPoint(0, 0))
     painter.setPen(qt.QColor(255, 255, 0))
     painter.drawPoint(qt.QPoint(1, 0))
     painter.setPen(qt.QColor(0, 255, 0))
     painter.drawPoint(qt.QPoint(0, 1))
     painter.setPen(qt.QColor(0, 255, 255))
     painter.drawPoint(qt.QPoint(1, 1))
     painter.end()
     pixmap = pixmap.scaled(32, 32, qt.Qt.IgnoreAspectRatio, qt.Qt.FastTransformation)
     return qt.QIcon(pixmap)
Пример #11
0
 def paintEvent(self, e):
     super(QColorLoop, self).paintEvent(e)
     rect = e.rect()
     painter = qt.QPainter(self)
     painter.setRenderHint(qt.QPainter.Antialiasing, False)
     painter.save()
     pen = qt.QPen()
     pen.setWidth(self.LINE_WIDTH)
     pen.setStyle(qt.Qt.SolidLine)
     for ic, color in enumerate(self.colorCycle):
         pen.setColor(qt.QColor(color))
         painter.setPen(pen)
         pos = (ic + 1.5) * self.LINE_WIDTH
         painter.drawLine(rect.left() + 2 * self.LINE_WIDTH, pos,
                          rect.right() - 2 * self.LINE_WIDTH, pos)
     painter.restore()
    def paintEvent(self, event):
        painter = qt.QPainter(self)

        style = qt.QApplication.style()

        area = self.__drawArea()
        pixmapRect = self.__pixMapRect()

        option = qt.QStyleOptionProgressBar()
        option.initFrom(self)
        option.rect = area
        option.state = ((self.isEnabled() and qt.QStyle.State_Enabled)
                        or qt.QStyle.State_None)
        style.drawControl(qt.QStyle.CE_ProgressBarGroove, option, painter,
                          self)

        painter.save()
        pen = painter.pen()
        pen.setWidth(1)
        pen.setColor(qt.Qt.black if self.isEnabled() else qt.Qt.gray)
        painter.setPen(pen)
        painter.drawRect(pixmapRect.adjusted(-1, -1, 1, 1))
        painter.restore()

        if self.isEnabled() and self.__pixmap is not None:
            painter.drawPixmap(
                area.adjusted(self._SLIDER_WIDTH / 2, self._PIXMAP_VOFFSET,
                              -self._SLIDER_WIDTH / 2 + 1,
                              -self._PIXMAP_VOFFSET + 1), self.__pixmap,
                self.__pixmap.rect())

        for name in ('first', 'second'):
            rect = self.__sliderRect(name)
            option = qt.QStyleOptionButton()
            option.initFrom(self)
            option.icon = self.__icons[name]
            option.iconSize = rect.size() * 0.7
            if option.state & qt.QStyle.State_MouseOver:
                option.state ^= qt.QStyle.State_MouseOver
            if self.__focus == name:
                option.state |= qt.QStyle.State_HasFocus
            elif option.state & qt.QStyle.State_HasFocus:
                option.state ^= qt.QStyle.State_HasFocus
            option.rect = rect
            style.drawControl(qt.QStyle.CE_PushButton, option, painter, self)
Пример #13
0
    def paintEvent(self, pEvent):
        # get button geometry
        widgGeom = self.rect()
        paintGeom = qt.QRect(widgGeom.left() + 1,
                             widgGeom.top() + 1,
                             widgGeom.width() - 2,
                             widgGeom.height() - 2)

        # paint background color
        painter = qt.QPainter(self)
        if self.brush is not None:
            painter.fillRect(paintGeom, self.brush)
        # paint frame
        pen = qt.QPen(qt.Qt.black)
        pen.setWidth(1 if not self.isCurrent() else 5)
        painter.setPen(pen)
        painter.drawRect(paintGeom)
        painter.end()
        qt.QPushButton.paintEvent(self, pEvent)
Пример #14
0
    def paintEvent(self, event):
        painter = qt.QPainter(self)
        style = qt.QApplication.style()

        palette = qt.QPalette(self.palette())
        option = qt.QStyleOptionButton()
        if self.__color is not None:
            palette.setBrush(qt.QPalette.Normal, qt.QPalette.Base,
                             self.__color)
            palette.setBrush(qt.QPalette.Disabled, qt.QPalette.Base,
                             self.__color)
            palette.setBrush(qt.QPalette.Inactive, qt.QPalette.Base,
                             self.__color)
        self.initStyleOption(option)
        option.palette = palette

        painter.save()
        style.drawPrimitive(qt.QStyle.PE_IndicatorCheckBox, option, painter,
                            self)
        painter.restore()
Пример #15
0
    def paintEvent(self, event):
        painter = qt.QPainter(self)

        opt = qt.QStyleOptionHeader()
        opt.orientation = qt.Qt.Horizontal
        opt.text = self.text()
        opt.textAlignment = self.alignment()
        opt.direction = self.layoutDirection()
        opt.fontMetrics = self.fontMetrics()
        opt.palette = self.palette()
        opt.state = qt.QStyle.State_Active
        opt.position = qt.QStyleOptionHeader.Beginning
        style = self.style()

        # Background
        margin = -1
        opt.rect = self.rect().adjusted(margin, margin, -margin, -margin)
        style.drawControl(qt.QStyle.CE_HeaderSection, opt, painter, None)

        # Frame border and text
        super(_HeaderLabel, self).paintEvent(event)
Пример #16
0
    def paintEvent(self, event):
        super(CalibrantPreview, self).paintEvent(event)
        painter = qt.QPainter(self)

        # border
        option = qt.QStyleOptionProgressBar()
        option.initFrom(self)
        option.rect = self.rect()
        option.state = qt.QStyle.State_Enabled if self.isEnabled(
        ) else qt.QStyle.State_None
        style = qt.QApplication.style()
        style.drawControl(qt.QStyle.CE_ProgressBarGroove, option, painter,
                          self)

        # content
        pixmapRect = self.rect().adjusted(self._PIXMAP_OFFSET,
                                          self._PIXMAP_OFFSET,
                                          -self._PIXMAP_OFFSET,
                                          -self._PIXMAP_OFFSET)
        pixmap = self.__getPixmap(size=pixmapRect.width())
        if pixmap is not None:
            painter.drawPixmap(pixmapRect, pixmap, pixmap.rect())
Пример #17
0
    def paintEvent(self, e):
        txt = self.currentText()
        if txt == '':
            return
        if txt.startswith('no'):
            super(SymbolComboBox, self).paintEvent(e)
            return
        lineSymbol = lineSymbols[lineSymbolsText[txt]]
        p = qt.QStylePainter(self)
        p.setPen(self.palette().color(qt.QPalette.Text))
        opt = qt.QStyleOptionComboBox()
        self.initStyleOption(opt)
        p.drawComplexControl(qt.QStyle.CC_ComboBox, opt)
        painter = qt.QPainter(self)
        painter.save()
        painter.setRenderHint(qt.QPainter.Antialiasing, True)
        rect = p.style().subElementRect(qt.QStyle.SE_ComboBoxFocusRect, opt,
                                        self)
        rect.adjust(+5, 0, -5, 0)

        symbolFC = qt.QColor(self.parent().color)
        symbolEC = qt.QColor(self.parent().color)
        symbolSize = self.parent().sizeSpinBox.value() * 2
        symbolPath = qt.QPainterPath(lineSymbol)
        scale = symbolSize
        painter.scale(scale, scale)
        symbolOffset = qt.QPointF(
            (rect.left() + rect.right() - symbolSize) * 0.5 / scale,
            (rect.top() + rect.bottom() - symbolSize) * 0.5 / scale)
        symbolPath.translate(symbolOffset)
        symbolBrush = qt.QBrush(symbolFC, qt.Qt.SolidPattern)
        symbolPen = qt.QPen(symbolEC, 1. / scale, qt.Qt.SolidLine)
        painter.setPen(symbolPen)
        painter.setBrush(symbolBrush)
        painter.drawPath(symbolPath)
        painter.restore()
Пример #18
0
    def paintEvent(self, event):
        painter = qt.QPainter(self)

        style = qt.QApplication.style()

        area = self.__drawArea()
        if self.__pixmap is not None:
            pixmapRect = self.__pixMapRect()

            option = qt.QStyleOptionProgressBar()
            option.initFrom(self)
            option.rect = area
            option.state = (qt.QStyle.State_Enabled
                            if self.isEnabled() else qt.QStyle.State_None)
            style.drawControl(qt.QStyle.CE_ProgressBarGroove, option, painter,
                              self)

            painter.save()
            pen = painter.pen()
            pen.setWidth(1)
            pen.setColor(qt.Qt.black if self.isEnabled() else qt.Qt.gray)
            painter.setPen(pen)
            painter.drawRect(pixmapRect.adjusted(-1, -1, 0, 1))
            painter.restore()

            if self.isEnabled():
                rect = area.adjusted(self._SLIDER_WIDTH // 2,
                                     self._PIXMAP_VOFFSET,
                                     -self._SLIDER_WIDTH // 2,
                                     -self._PIXMAP_VOFFSET + 1)
                painter.drawPixmap(rect, self.__pixmap, self.__pixmap.rect())
        else:
            option = StyleOptionRangeSlider()
            option.initFrom(self)
            option.rect = area
            option.sliderPosition1 = self.__firstValue
            option.sliderPosition2 = self.__secondValue
            option.handlerRect1 = self.__sliderRect("first")
            option.handlerRect2 = self.__sliderRect("second")
            option.minimum = self.__minValue
            option.maximum = self.__maxValue
            option.state = (qt.QStyle.State_Enabled
                            if self.isEnabled() else qt.QStyle.State_None)
            if self.__hoverControl == "groove":
                option.state |= qt.QStyle.State_MouseOver
            elif option.state & qt.QStyle.State_MouseOver:
                option.state ^= qt.QStyle.State_MouseOver
            self.drawRangeSliderBackground(painter, option, self)

        # Avoid glitch when moving handles
        hoverControl = self.__moving or self.__hoverControl

        for name in ('first', 'second'):
            rect = self.__sliderRect(name)
            option = qt.QStyleOptionButton()
            option.initFrom(self)
            option.icon = self.__icons[name]
            option.iconSize = rect.size() * 0.7
            if hoverControl == name:
                option.state |= qt.QStyle.State_MouseOver
            elif option.state & qt.QStyle.State_MouseOver:
                option.state ^= qt.QStyle.State_MouseOver
            if self.__focus == name:
                option.state |= qt.QStyle.State_HasFocus
            elif option.state & qt.QStyle.State_HasFocus:
                option.state ^= qt.QStyle.State_HasFocus
            option.rect = rect
            style.drawControl(qt.QStyle.CE_PushButton, option, painter, self)
Пример #19
0
    def paintEvent(self, event):
        painter = Qt.QPainter(self)

        style = Qt.QApplication.style()

        area = self.__drawArea()
        pixmapRect = self.__pixMapRect()

        sliders = self.__sliders

        option = Qt.QStyleOptionProgressBar()
        option.initFrom(self)
        option.rect = area
        option.state = ((self.isEnabled() and Qt.QStyle.State_Enabled)
                        or Qt.QStyle.State_None)
        style.drawControl(Qt.QStyle.CE_ProgressBarGroove, option, painter,
                          self)

        # showing interval rect only if show is forced or if there is not
        # background and show is True or None
        showRngBckgrnd = (self.__showRangeBackground
                          or (self.__pixmap and self.__showRangeBackground)
                          or (self.__pixmap is None
                              and self.__showRangeBackground is None)
                          or self.__showRangeBackground)

        alpha = (self.isEnabled() and 255) or 100

        if showRngBckgrnd:
            painter.save()
            rect = Qt.QRect(area)
            rect.setLeft(sliders['left'].center().x())
            rect.setRight(sliders['right'].center().x())
            gradient = Qt.QLinearGradient(area.topLeft(), area.bottomLeft())
            color = Qt.QColor(Qt.Qt.cyan)
            color.setAlpha(alpha)
            gradient.setColorAt(0., color)
            color = Qt.QColor(Qt.Qt.blue)
            color.setAlpha(alpha)
            gradient.setColorAt(1., color)
            brush = Qt.QBrush(gradient)
            painter.setBrush(brush)
            painter.drawRect(rect)
            painter.restore()

        if self.__pixmap and alpha == 255:
            painter.save()
            pen = painter.pen()
            pen.setWidth(2)
            pen.setColor(Qt.Qt.black)
            painter.setPen(pen)
            painter.drawRect(pixmapRect.adjusted(-1, -1, 1, 1))
            painter.restore()

            painter.drawPixmap(
                area.adjusted(self._sliderWidth / 2, self._pixmapVOffset,
                              -self._sliderWidth / 2, -self._pixmapVOffset),
                self.__pixmap, self.__pixmap.rect())

        option = Qt.QStyleOptionButton()
        option.initFrom(self)

        for side, slider in sliders.items():
            option.icon = self.__sliderIcons[side]
            option.iconSize = slider.size() * 0.7
            if self.__hover == side:
                option.state |= Qt.QStyle.State_MouseOver
            elif option.state & Qt.QStyle.State_MouseOver:
                option.state ^= Qt.QStyle.State_MouseOver
            if self.__focus == side:
                option.state |= Qt.QStyle.State_HasFocus
            elif option.state & Qt.QStyle.State_HasFocus:
                option.state ^= Qt.QStyle.State_HasFocus
            option.rect = slider
            style.drawControl(Qt.QStyle.CE_PushButton, option, painter, self)