Пример #1
0
 def paintEvent(self, event: QPaintEvent):
     painter = QPainter(self)
     painter.drawImage(self.rect(), self.image)
     if self.show_frame:
         painter.save()
         pen = QPen()
         pen.setWidth(2)
         pen.setColor(QColor("black"))
         painter.setPen(pen)
         rect = QRect(1, 1, self.width() - 2, self.height() - 2)
         painter.drawRect(rect)
         pen.setColor(QColor("white"))
         painter.setPen(pen)
         rect = QRect(3, 3, self.width() - 6, self.height() - 6)
         painter.drawRect(rect)
         painter.restore()
     if self.show_arrow:
         painter.save()
         triangle = QPolygonF()
         dist = 4
         point1 = QPoint(self.width() - self.triangle_width, 0)
         size = QSize(20, self.height() // 2)
         rect = QRect(point1, size)
         painter.fillRect(rect, QColor("white"))
         triangle.append(point1 + QPoint(dist, dist))
         triangle.append(point1 + QPoint(size.width() - dist, dist))
         triangle.append(point1 + QPoint(size.width() // 2,
                                         size.height() - dist))
         painter.setBrush(Qt.black)
         painter.drawPolygon(triangle, Qt.WindingFill)
         painter.restore()
Пример #2
0
    def paintEvent(self, event):
        """
        Qt override.

        Draw lower left border of the main Stacked Widget.
        """
        super(MainWindow, self).paintEvent(event)
        tab = self.stack.tabbar
        tab_pos = self.mapTo(self, tab.pos())
        pane_pos = self.mapTo(self, self.stack.pos())

        stack_height = self.stack.height()
        menu_height = self.menuBar().height()
        header_height = 49  # From css
        padding = 20  # From css
        left = 1  # From css
        extra = 8  # Still wondering where this extra Y delta is
        deltay = menu_height + header_height + tab.height() + padding + extra
        x0 = tab_pos.x() + tab.width() + padding - left
        y0 = tab_pos.y() + deltay
        y1 = pane_pos.y() + stack_height + deltay - tab.height() - padding

        painter = QPainter(self)
        painter.setPen(QPen(QColor('#006f43'), 1, Qt.SolidLine, Qt.RoundCap))
        painter.drawLine(x0, y0, x0, y1)
Пример #3
0
    def paintEvent(self, event):
        """Qt method override to paint a custom image on the Widget."""
        super(FigureCanvas, self).paintEvent(event)
        # Prepare the rect on which the image is going to be painted :
        fw = self.frameWidth()
        rect = QRect(0 + fw, 0 + fw,
                     self.size().width() - 2 * fw,
                     self.size().height() - 2 * fw)

        if self.fig is None or self._blink_flag:
            return

        # Check/update the qpixmap buffer :
        qpix2paint = None
        for qpix in self._qpix_buffer:
            if qpix.size().width() == rect.width():
                qpix2paint = qpix
                break
        else:
            if self.fmt in ['image/png', 'image/jpeg']:
                qpix2paint = self._qpix_orig.scaledToWidth(
                    rect.width(), mode=Qt.SmoothTransformation)
            elif self.fmt == 'image/svg+xml':
                qpix2paint = QPixmap(svg_to_image(self.fig, rect.size()))
            self._qpix_buffer.append(qpix2paint)

        if qpix2paint is not None:
            # Paint the image on the widget :
            qp = QPainter()
            qp.begin(self)
            qp.drawPixmap(rect, qpix2paint)
            qp.end()
Пример #4
0
    def paintEvent(self, event):
        """Qt Override.

        Include a validation icon to the left of the line edit.
        """
        super(IconLineEdit, self).paintEvent(event)
        painter = QPainter(self)

        rect = self.geometry()
        space = int((rect.height()) / 6)
        h = rect.height() - space
        w = rect.width() - h

        if self._icon_visible:
            if self._status and self._status_set:
                pixmap = self._set_icon.pixmap(h, h)
            elif self._status:
                pixmap = self._valid_icon.pixmap(h, h)
            else:
                pixmap = self._invalid_icon.pixmap(h, h)

            painter.drawPixmap(w, space, pixmap)

        application_style = QApplication.style().objectName()
        if self._application_style != application_style:
            self._application_style = application_style
            self._refresh()

        # Small hack to gurantee correct padding on TRex start
        if self._paint_count < 5:
            self._paint_count += 1
            self._refresh()
Пример #5
0
 def eventFilter(self, obj_, event):
     if event.type() == QEvent.Paint:
         self.reset()
         if self.__data.seriesItem:
             pe = event  # XXX: cast to QPaintEvent
             canvas = self.__data.seriesItem.plot().canvas()
             painter = QPainter(canvas)
             painter.setClipRegion(pe.region())
             doCopyCache = self.testAttribute(self.CopyBackingStore)
             if doCopyCache:
                 plotCanvas = canvas  # XXX: cast to QwtPlotCanvas
                 if plotCanvas:
                     doCopyCache = qwtHasBackingStore(plotCanvas)
                     if doCopyCache:
                         painter.drawPixmap(plotCanvas.rect().topLeft(),
                                            plotCanvas.backingStore())
             if not doCopyCache:
                 qwtRenderItem(
                     painter,
                     canvas.contentsRect(),
                     self.__data.seriesItem,
                     self.__data.from_,
                     self.__data.to,
                 )
             return True
     return False
Пример #6
0
    def paintEvent(self, event):
        """Qt method override to paint a custom image on the Widget."""
        super(FigureCanvas, self).paintEvent(event)
        # Prepare the rect on which the image is going to be painted.
        fw = self.frameWidth()
        rect = QRect(0 + fw, 0 + fw,
                     self.size().width() - 2 * fw,
                     self.size().height() - 2 * fw)

        if self.fig is None or self._blink_flag:
            return

        # Prepare the scaled qpixmap to paint on the widget.
        if (self._qpix_scaled is None
                or self._qpix_scaled.size().width() != rect.width()):
            if self.fmt in ['image/png', 'image/jpeg']:
                self._qpix_scaled = self._qpix_orig.scaledToWidth(
                    rect.width(), mode=Qt.SmoothTransformation)
            elif self.fmt == 'image/svg+xml':
                self._qpix_scaled = QPixmap(svg_to_image(
                    self.fig, rect.size()))

        if self._qpix_scaled is not None:
            # Paint the image on the widget.
            qp = QPainter()
            qp.begin(self)
            qp.drawPixmap(rect, self._qpix_scaled)
            qp.end()
Пример #7
0
    def borderPath(self, rect):
        """
        Calculate the painter path for a styled or rounded border

        When the canvas has no styled background or rounded borders
        the painter path is empty.

        :param QRect rect: Bounding rectangle of the canvas
        :return: Painter path, that can be used for clipping
        """
        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 len(recorder.border.rectList) > 0:
                return qwtCombinePathList(rect, recorder.border.pathlist)
        elif self.__data.borderRadius > 0.0:
            fw2 = self.frameWidth() * 0.5
            r = QRectF(rect).adjusted(fw2, fw2, -fw2, -fw2)
            path = QPainterPath()
            path.addRoundedRect(r, self.__data.borderRadius, self.__data.borderRadius)
            return path
        return QPainterPath()
Пример #8
0
    def paintEvent(self, event):
        tic = time.perf_counter()
        painter = QPainter(self)
        rect = event.rect()
        painter.drawImage(rect, self.image, rect)
        painter.setPen(QColor.fromRgb(255, 0, 0))
        #painter.drawPoints(self.clicks)
        if self.drawBoxes:
            self.drawBoxes(painter)
        # Draw the center mark
        painter.setPen(QColor.fromRgb(255, 0, 0))
        painter.drawLine(self.center.x() - 20, self.center.y(),
                         self.center.x() + 20, self.center.y())
        painter.drawLine(self.center.x(),
                         self.center.y() - 20, self.center.x(),
                         self.center.y() + 20)

        # Draw the scale bar
        if self.scaleBar:
            painter.setPen(QColor.fromRgb(40, 40, 40))
            painter.setFont(QFont("Arial", 30))
            scaleRect = QRect(10, 420, 200, 30)
            painter.drawText(scaleRect, Qt.AlignCenter, "10 nm")
            pen = painter.pen()
            pen.setWidth(5)
            painter.setPen(pen)
            painter.drawLine(10, 460, 210, 460)

        toc = time.perf_counter()
Пример #9
0
    def paintEvent(self, event):
        # Paints the fold indicators and the possible fold region background
        # on the folding panel.
        super(FoldingPanel, self).paintEvent(event)
        painter = QPainter(self)
        document = self.editor.document()

        if not self._display_folding and not self._key_pressed:
            if any(self.folding_status.values()):
                for info in self.editor.visible_blocks:
                    top_position, line_number, block = info
                    self._draw_collapsed_indicator(
                        line_number, top_position, block,
                        painter, mouse_hover=True)
            return
        # Draw background over the selected non collapsed fold region
        if self._mouse_over_line is not None:
            block = self.editor.document().findBlockByNumber(
                self._mouse_over_line)
            try:
                self._draw_fold_region_background(block, painter)
            except (ValueError, KeyError):
                # Catching the KeyError above is necessary to avoid
                # issue spyder-ide/spyder#10918.
                # It happens when users have the mouse on top of the
                # folding panel and make some text modifications
                # that trigger a folding recomputation.
                pass
        # Draw fold triggers
        for top_position, line_number, block in self.editor.visible_blocks:
            self._draw_collapsed_indicator(
                line_number, top_position, block, painter, mouse_hover=False)
Пример #10
0
 def paintEvent(self, event: QPaintEvent):
     painter = QPainter(self)
     painter.save()
     painter.setRenderHint(QPainter.Antialiasing)
     size = min(self.width(), self.height())
     rect = QRect(0, 0, size, size)
     painter.setBrush(self.background_color)
     painter.setPen(self.background_color)
     painter.drawEllipse(rect)
     painter.setBrush(self.main_color)
     painter.setPen(self.main_color)
     factor = self.nominator / self.denominator
     radius = size / 2
     if factor > 0.5:
         painter.drawChord(rect, 0, 16 * 360 * 0.5)
         painter.drawChord(rect, 16 * 180, 16 * 360 * (factor - 0.5))
         zero_point = QPointF(0, radius)
     else:
         painter.drawChord(rect, 0, 16 * 360 * factor)
         zero_point = QPointF(size, radius)
     mid_point = QPointF(radius, radius)
     point = mid_point + QPointF(
         math.cos(math.pi *
                  (factor * 2)) * radius, -math.sin(math.pi *
                                                    (factor * 2)) * radius)
     polygon = QPolygonF()
     polygon += mid_point
     polygon += zero_point
     polygon += point
     painter.drawPolygon(polygon)
     painter.restore()
Пример #11
0
    def findAscent(self, font):
        dummy = "E"
        white = QColor(Qt.white)

        fm = self.fontmetrics(font)
        pm = QPixmap(fm.width(dummy), fm.height())
        pm.fill(white)

        p = QPainter(pm)
        p.setFont(font)
        p.drawText(0, 0, pm.width(), pm.height(), 0, dummy)
        p.end()

        img = pm.toImage()

        w = pm.width()
        linebytes = w * 4
        for row in range(img.height()):
            if PYSIDE2:
                line = bytes(img.scanLine(row))
            else:
                line = img.scanLine(row).asstring(linebytes)
            for col in range(w):
                color = struct.unpack("I", line[col * 4:(col + 1) * 4])[0]
                if color != white.rgb():
                    return fm.ascent() - row + 1
        return fm.ascent()
Пример #12
0
    def paintEvent(self, a0: QPaintEvent) -> None:

        super().paintEvent(a0)
        painter = QPainter(self)
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        rect = QRectF(self.margin, self.margin,
                      self.width() - self.margin * 2,
                      self.height() - 2 * self.margin)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawRect(rect)
        painter.restore()
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen()
        pen.setWidth(3)
        painter.setPen(pen)
        path = QPainterPath()
        height, width = rect.height() + self.margin, rect.width() + self.margin
        path.moveTo(self.margin, height)
        path.cubicTo(height * 0.5, width * 0.9, height * 0.9, width * 0.5,
                     height, self.margin)
        painter.drawPath(path)
        painter.restore()
Пример #13
0
    def paintEvent(self, a0: QPaintEvent) -> None:
        super().paintEvent(a0)
        painter = QPainter(self)
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        rect = QRectF(self.margin, self.margin,
                      self.width() - self.margin * 2,
                      self.height() - 2 * self.margin)
        painter.setBrush(Qt.white)
        painter.setPen(Qt.white)
        painter.drawEllipse(rect)

        painter.restore()
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        pen = QPen()
        pen.setWidth(2)
        painter.setPen(pen)
        mid_point = QPointF(a0.rect().width() / 2, a0.rect().height() / 2)
        radius = min(a0.rect().height(), a0.rect().width()) / 3
        rays_num = 10
        for i in range(rays_num):
            point = QPointF(
                math.sin(math.pi / (rays_num / 2) * i) * radius,
                math.cos(math.pi / (rays_num / 2) * i) * radius)
            painter.drawLine(mid_point + (point * 0.4), mid_point + point)
        painter.restore()
Пример #14
0
    def paintEvent(self, a0: QPaintEvent) -> None:
        super().paintEvent(a0)
        painter = QPainter(self)
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        pen2 = QPen()

        rect = QRectF(self.margin,
                      self.height() / 2,
                      self.width() - self.margin * 2,
                      self.height() / 2 - self.margin)
        rect2 = QRectF(3 * self.margin, 2 * self.margin,
                       self.width() - self.margin * 6, self.height())

        pen2.setWidth(6)
        painter.setPen(pen2)
        painter.drawArc(rect2, 0, 180 * 16)
        pen2.setWidth(3)
        pen2.setColor(Qt.white)
        painter.setPen(pen2)
        painter.drawArc(rect2, 0, 180 * 16)

        painter.fillRect(rect, Qt.white)
        pen2.setWidth(2)
        pen2.setColor(Qt.black)
        painter.setPen(pen2)
        painter.drawRect(rect)

        painter.restore()
Пример #15
0
def render_image(scene):
    image = QImage(scene.sceneRect().size().toSize(), QImage.Format_ARGB32)
    image.fill(Qt.transparent)
    painter = QPainter(image)
    scene.render(painter)
    painter.end()
    return image
Пример #16
0
    def paintEvent(self, event):
        """
        Override Qt method.
        Painting the scroll flag area
        """
        make_flag = self.make_flag_qrect
        make_slider = self.make_slider_range

        # Filling the whole painting area
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.editor.sideareas_color)
        block = self.editor.document().firstBlock()

        # Painting warnings and todos
        for line_number in range(1, self.editor.document().blockCount() + 1):
            data = block.userData()
            if data:
                position = self.value_to_position(line_number)
                if data.code_analysis:
                    # Warnings
                    color = self.editor.warning_color
                    for _message, error in data.code_analysis:
                        if error:
                            color = self.editor.error_color
                            break
                    self.set_painter(painter, color)
                    painter.drawRect(make_flag(position))
                if data.todo:
                    # TODOs
                    self.set_painter(painter, self.editor.todo_color)
                    painter.drawRect(make_flag(position))
                if data.breakpoint:
                    # Breakpoints
                    self.set_painter(painter, self.editor.breakpoint_color)
                    painter.drawRect(make_flag(position))
            block = block.next()

        # Occurrences
        if self.editor.occurrences:
            self.set_painter(painter, self.editor.occurrence_color)
            for line_number in self.editor.occurrences:
                position = self.value_to_position(line_number)
                painter.drawRect(make_flag(position))

        # Found results
        if self.editor.found_results:
            self.set_painter(painter, self.editor.found_results_color)
            for line_number in self.editor.found_results:
                position = self.value_to_position(line_number)
                painter.drawRect(make_flag(position))

        # Painting the slider range
        pen_color = QColor(Qt.white)
        pen_color.setAlphaF(.8)
        painter.setPen(pen_color)
        brush_color = QColor(Qt.white)
        brush_color.setAlphaF(.5)
        painter.setBrush(QBrush(brush_color))
        painter.drawRect(
            make_slider(self.editor.firstVisibleBlock().blockNumber()))
Пример #17
0
    def paintEvent(self, paint_event):
        QFrame.paintEvent(self, paint_event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

        rect = self.contentsRect()
        """@type: QRect"""

        painter.fillRect(rect, self.background_color)

        x = rect.x()
        y = rect.y()
        height = rect.height()
        width = floor(rect.width() * self.__progress)

        painter.fillRect(x, y, width, height, self.color)

        if self.__shiny:
            #Shiny overlay!
            gradient = QLinearGradient(rect.width() / 2, 0, rect.width() / 2, rect.height())
            gradient.setColorAt(0, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.2, QColor(255, 255, 255, 200))
            gradient.setColorAt(0.4, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.85, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.85, QColor(0, 0, 0, 0))
            gradient.setColorAt(1, QColor(0, 0, 0, 127))
            painter.fillRect(rect, gradient)
Пример #18
0
    def paintEvent(self, event):  # this puts the line numbers in the margin
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.background)
        block = self.parent.firstVisibleBlock()

        font = self.parent.font()

        while block.isValid():
            block_num = block.blockNumber()
            block_top = self.parent.blockBoundingGeometry(block).translated(
                self.parent.contentOffset()).top()

            # if the block is not visible stop wasting time
            if not block.isVisible() or block_top >= event.rect().bottom():
                break

            if block_num == self.parent.textCursor().blockNumber():
                font.setBold(True)
                painter.setFont(font)
                painter.setPen(self.highlight_color)
                background = self.highlight_background
            else:
                font.setBold(False)
                painter.setFont(font)
                painter.setPen(self.color)
                background = self.background

            text_rec = QRect(0, block_top, self.width(),
                             self.parent.fontMetrics().height())
            painter.fillRect(text_rec, background)
            painter.drawText(text_rec, Qt.AlignRight, str(block_num + 1))
            block = block.next()

        painter.end()
        QWidget.paintEvent(self, event)
Пример #19
0
    def paintEvent(self, e):
        height = self.height()
        width = self.width()

        # draw background
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(Qt.transparent)
        painter.setBrush(BACKGROUND)
        painter.setOpacity(1)
        path = QPainterPath()
        path.setFillRule(Qt.WindingFill)
        path.addRoundedRect(QRectF(8, 0, width - 8, height), 15, 15)
        painter.drawPath(path.simplified())

        # draw sidebar
        painter.setBrush(SIDEBAR)
        painter.setOpacity(1)
        path = QPainterPath()
        path.setFillRule(Qt.WindingFill)

        # we draw a fixed-width toolbar background
        path.addRoundedRect(QRectF(8, 0, 250 - 8, height), 15, 15)
        path.addRect(QRectF(200, 0, 50, 50))
        path.addRect(QRectF(200, height - 50, 50, 50))
        painter.drawPath(path.simplified())
Пример #20
0
    def paintEvent(self, e):
        """Paint star on frame."""
        qp = QPainter()
        qp.begin(self)

        self.drawStar(qp)
        qp.end()
Пример #21
0
    def paintEvent(self, event):
        """
        Paint events are sent to widgets that need to update themselves,
        for instance when part of a widget is exposed because a covering
        widget was moved.

        This method handles the painting with parameters from the stylesheet,
        configures the brush, pen and calls ```draw_icon``` so the specifics
        can be performed for each of the drawing classes.

        Parameters
        ----------
        event : QPaintEvent
        """
        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)
        painter.setClipping(True)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, painter, self)
        painter.setRenderHint(QPainter.Antialiasing)
        w = self.width()
        h = self.height()
        painter.translate(w / 2.0, h / 2.0)
        painter.rotate(self._rotation)
        painter.translate(-w / 2.0, -h / 2.0)
        painter.translate(self._pen_width / 2.0, self._pen_width / 2.0)
        painter.scale(w - self._pen_width, h - self._pen_width)
        painter.translate(0, 0)
        painter.setBrush(self._brush)
        painter.setPen(self._pen)
        self.draw_icon(painter)

        QWidget.paintEvent(self, event)
Пример #22
0
 def __save_atlas(self) -> None:
     """Save function as same as type synthesis widget."""
     count = self.collection_list.count()
     if count < 1:
         return
     lateral, ok = QInputDialog.getInt(self, "Atlas",
                                       "The number of lateral:", 5, 1)
     if not ok:
         return
     file_name = self.output_to("atlas image", qt_image_format)
     if not file_name:
         return
     icon_size = self.collection_list.iconSize()
     width = icon_size.width()
     image = self.collection_list.item(0).icon().pixmap(icon_size).toImage()
     image_main = QImage(
         QSize(lateral if count > lateral else count,
               (count // lateral) + bool(count % lateral)) * width,
         image.format())
     image_main.fill(Qt.transparent)
     painter = QPainter(image_main)
     for row in range(count):
         image = self.collection_list.item(row).icon().pixmap(
             icon_size).toImage()
         painter.drawImage(
             QPointF(row % lateral, row // lateral) * width, image)
     painter.end()
     pixmap = QPixmap()
     pixmap.convertFromImage(image_main)
     pixmap.save(file_name)
     self.save_reply_box("Atlas", file_name)
Пример #23
0
 def legendIcon(self, index, size):
     """
     :param int index: Index of the legend entry (ignored as there is only one)
     :param QSizeF size: Icon size
     :return: Icon representing the marker on the legend
     
     .. seealso::
     
         :py:meth:`qwt.plot.QwtPlotItem.setLegendIconSize()`,
         :py:meth:`qwt.plot.QwtPlotItem.legendData()`
     """
     if size.isEmpty():
         return QwtGraphic()
     icon = QwtGraphic()
     icon.setDefaultSize(size)
     icon.setRenderHint(QwtGraphic.RenderPensUnscaled, True)
     painter = QPainter(icon)
     painter.setRenderHint(
         QPainter.Antialiasing,
         self.testRenderHint(QwtPlotItem.RenderAntialiased))
     if self.__data.style != QwtPlotMarker.NoLine:
         painter.setPen(self.__data.pen)
         if self.__data.style in (QwtPlotMarker.HLine, QwtPlotMarker.Cross):
             y = 0.5 * size.height()
             painter.drawLine(0.0, y, size.width(), y)
         if self.__data.style in (QwtPlotMarker.VLine, QwtPlotMarker.Cross):
             x = 0.5 * size.width()
             painter.drawLine(x, 0.0, x, size.height())
     if self.__data.symbol:
         r = QRect(0, 0, size.width(), size.height())
         self.__data.symbol.drawSymbol(painter, r)
     return icon
Пример #24
0
 def __init__(self, parent=None, circle=False):
     super(PyDMBitIndicator, self).__init__(parent)
     self.setAutoFillBackground(True)
     self.circle = circle
     self._painter = QPainter()
     self._brush = QBrush(Qt.SolidPattern)
     self._pen = QPen(Qt.SolidLine)
Пример #25
0
    def paintEvent(self, event):
        super().paintEvent(event)
        painter = QPainter(self)
        font_metrics = painter.fontMetrics()
        text_layout = QTextLayout(self._text, painter.font())
        text_layout.beginLayout()

        y = 0
        while True:
            line = text_layout.createLine()
            if not line.isValid():
                break
            line.setLineWidth(self.width())
            nextLineY = y + font_metrics.lineSpacing()
            if self.height() >= nextLineY + font_metrics.lineSpacing():
                line.draw(painter, QPoint(0, y))
                y = nextLineY
            else:
                lastLine = self._text[line.textStart():]
                elidedLastLine = font_metrics.elidedText(
                    lastLine, Qt.ElideRight, self.width())
                painter.drawText(QPoint(0, y + font_metrics.ascent()),
                                 elidedLastLine)
                line = text_layout.createLine()
                break
        text_layout.endLayout()
Пример #26
0
    def paintEvent(self, event):
        """Paint the colorbox.  If no color, display a checkerboard pattern.

        Parameters
        ----------
        event : qtpy.QtCore.QEvent
            Event from the Qt context.
        """
        painter = QPainter(self)
        if self.layer._selected_color is None:
            for i in range(self._height // 4):
                for j in range(self._height // 4):
                    if (i % 2 == 0 and j % 2 == 0) or (i % 2 == 1
                                                       and j % 2 == 1):
                        painter.setPen(QColor(230, 230, 230))
                        painter.setBrush(QColor(230, 230, 230))
                    else:
                        painter.setPen(QColor(25, 25, 25))
                        painter.setBrush(QColor(25, 25, 25))
                    painter.drawRect(i * 4, j * 4, 5, 5)
        else:
            color = np.multiply(self.layer._selected_color, self.layer.opacity)
            color = np.round(255 * color).astype(int)
            painter.setPen(QColor(*list(color)))
            painter.setBrush(QColor(*list(color)))
            painter.drawRect(0, 0, self._height, self._height)
Пример #27
0
    def paintEvent(self, event):
        """Paint the colorbox.

        Parameters
        ----------
        event : qtpy.QtCore.QEvent
            Event from the Qt context.
        """
        painter = QPainter(self)
        if self.layer._selected_color is None:
            for i in range(self._height // 6):
                for j in range(self._height // 6):
                    if (i % 2 == 0 and j % 2 == 0) or (i % 2 == 1
                                                       and j % 2 == 1):
                        painter.setPen(QColor(230, 230, 230))
                        painter.setBrush(QColor(230, 230, 230))
                    else:
                        painter.setPen(QColor(25, 25, 25))
                        painter.setBrush(QColor(25, 25, 25))
                    painter.drawRect(i * 6, j * 6, 5, 5)
        else:
            color = 255 * self.layer._selected_color
            color = color.astype(int)
            painter.setPen(QColor(*list(color)))
            painter.setBrush(QColor(*list(color)))
            painter.drawRect(0, 0, self._height, self._height)
Пример #28
0
    def fillPixmap(self, widget, pixmap, offset=None):
        """
        Fill a pixmap with the content of a widget

        In Qt >= 5.0 `QPixmap.fill()` is a nop, in Qt 4.x it is buggy
        for backgrounds with gradients. Thus `fillPixmap()` offers 
        an alternative implementation.
        
        :param QWidget widget: Widget
        :param QPixmap pixmap: Pixmap to be filled
        :param QPoint offset: Offset
        
        .. seealso::
        
            :py:meth:`QPixmap.fill()`
        """
        if offset is None:
            offset = QPoint()
        rect = QRect(offset, pixmap.size())
        painter = QPainter(pixmap)
        painter.translate(-offset)
        autoFillBrush = widget.palette().brush(widget.backgroundRole())
        if not (widget.autoFillBackground() and autoFillBrush.isOpaque()):
            bg = widget.palette().brush(QPalette.Window)
            qwtFillRect(widget, painter, rect, bg)
        if widget.autoFillBackground():
            qwtFillRect(widget, painter, rect, autoFillBrush)
        if widget.testAttribute(Qt.WA_StyledBackground):
            painter.setClipRegion(QRegion(rect))
            opt = QStyleOption()
            opt.initFrom(widget)
            widget.style().drawPrimitive(QStyle.PE_Widget, opt, painter,
                                         widget)
Пример #29
0
    def __save_atlas(self) -> None:
        """Saving all the atlas to image file.

        We should turn transparent background to white first.
        Then using QImage class to merge into one image.
        """
        count = self.structure_list.count()
        if count < 1:
            return

        lateral = self.__save_atlas_ask()
        if not lateral:
            return

        file_name = self.output_to("atlas image", qt_image_format)
        if not file_name:
            return

        width = self.structure_list.iconSize().width()
        image_main = QImage(QSize(
            lateral * width if count > lateral else count * width,
            ((count // lateral) + bool(count % lateral)) * width
        ), self.__atlas_image(0).format())
        image_main.fill(Qt.transparent)
        painter = QPainter(image_main)
        for row in range(count):
            image = self.__atlas_image(row)
            painter.drawImage(QPointF(row % lateral, row // lateral) * width, image)
        painter.end()
        pixmap = QPixmap.fromImage(image_main)
        pixmap.save(file_name)
        self.save_reply_box("Atlas", file_name)
Пример #30
0
    def setData(
        self,
        x,
        height,
        width=0.8,
        bottom=None,
        *,
        align="center",
        fillcolor=None,
        edgecolor=None,
    ) -> None:
        # assume vertical
        cbook._check_in_list(["center", "edge"], align=align)

        y = bottom
        if y is None:
            y = 0

        x, height, width, y = np.broadcast_arrays(np.atleast_1d(x), height, width, y)

        if align == "center":
            try:
                left = x - width / 2
            except TypeError as e:
                raise TypeError(
                    f"the dtypes of parameters x ({x.dtype}) "
                    f"and width ({width.dtype}) "
                    f"are incompatible"
                ) from e
        elif align == "edge":
            left = x
        else:
            raise RuntimeError(f"unknown align mode {align}")
        bottom = y

        # prepare to draw
        if edgecolor is None:
            edgecolor = (128, 128, 128)  # getConfigOption("foreground")
        pen = mkPen(edgecolor)

        if fillcolor is None:
            fillcolor = (128, 128, 128)
        brush = mkBrush(fillcolor)

        self.qpicture = QPicture()
        self.path = QPainterPath()

        p = QPainter(self.qpicture)
        p.setPen(pen)
        p.setBrush(brush)

        # draw
        rects = zip(left, bottom, width, height)
        for l, b, w, h in rects:
            rect = QRectF(l, b, w, h)
            p.drawRect(rect)
            self.path.addRect(rect)

        p.end()
        self.prepareGeometryChange()