Ejemplo n.º 1
0
    def slot_canvasSaveImage(self):
        newPath = QFileDialog.getSaveFileName(self, self.tr("Save Image"), filter=self.tr("PNG Image (*.png);;JPEG Image (*.jpg)"))
        newPath = newPath[0]

        if not newPath:
            return

        self.scene.clearSelection()

        if newPath.lower().endswith(".jpg"):
            imgFormat = "JPG"
        elif newPath.lower().endswith(".png"):
            imgFormat = "PNG"
        else:
            # File-dialog may not auto-add the extension
            imgFormat = "PNG"
            newPath  += ".png"

        self.fExportImage = QImage(self.scene.sceneRect().width(), self.scene.sceneRect().height(), QImage.Format_RGB32)
        painter = QPainter(self.fExportImage)
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.TextAntialiasing, True)
        self.scene.render(painter)
        self.fExportImage.save(newPath, imgFormat, 100)
        painter.restore()
Ejemplo n.º 2
0
    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        if not self.isEnabled():
            painter.save()
            painter.setOpacity(0.2)
            painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect)
            painter.restore()

        elif self.isChecked() or self.isDown():
            painter.drawPixmap(self.fPixmapRect, self.fPixmapDown, self.fPixmapRect)

        elif self.fIsHovered:
            painter.drawPixmap(self.fPixmapRect, self.fPixmapHover, self.fPixmapRect)

        else:
            painter.drawPixmap(self.fPixmapRect, self.fPixmapNormal, self.fPixmapRect)

        if not self.fTopText:
            return

        painter.save()
        painter.setPen(self.fTopTextColor)
        painter.setBrush(self.fTopTextColor)
        painter.setFont(self.fTopTextFont)
        painter.drawText(QPointF(10, 16), self.fTopText)
        painter.restore()
Ejemplo n.º 3
0
    def paintEvent(self, event):
        if not self.isDisplayedWhenStopped() and not self.isRunning():
            return

        width = min(self.width(), self.height())

        p = QPainter(self)
        p.setRenderHint(QPainter.Antialiasing)

        outerRadius = (width-1) * 0.5
        innerRadius = (width-1) * 0.5 * 0.38

        capsuleHeight = outerRadius - innerRadius
        capsuleWidth  = capsuleHeight * 0.23 if width > 32 else capsuleHeight * 0.35
        capsuleRadius = capsuleWidth / 2

        for i in range(12):
            color = QColor(self.color)
            color.setAlphaF(float(1.0 - float(i / 12.0)))
            p.setPen(Qt.NoPen)
            p.setBrush(color)
            p.save()
            p.translate(self.rect().center())
            p.rotate(self._angle - float(i * 30.0))
            p.drawRoundedRect(-capsuleWidth * 0.5,
                              -(innerRadius + capsuleHeight),
                              capsuleWidth,
                              capsuleHeight,
                              capsuleRadius,
                              capsuleRadius)
            p.restore()
Ejemplo n.º 4
0
    def paintEvent(self, event):
        rect = QRect(10, 20, 80, 60)

        path = QPainterPath()
        path.moveTo(20, 80)
        path.lineTo(20, 30)
        path.cubicTo(80, 0, 50, 50, 80, 80)

        startAngle = 30 * 16
        arcLength = 120 * 16

        painter = QPainter(self)
        painter.setPen(self.pen)
        painter.setBrush(self.brush)
        if self.antialiased:
            painter.setRenderHint(QPainter.Antialiasing)

        for x in range(0, self.width(), 100):
            for y in range(0, self.height(), 100):
                painter.save()
                painter.translate(x, y)
                if self.transformed:
                    painter.translate(50, 50)
                    painter.rotate(60.0)
                    painter.scale(0.6, 0.9)
                    painter.translate(-50, -50)

                if self.shape == RenderArea.Line:
                    painter.drawLine(rect.bottomLeft(), rect.topRight())
                elif self.shape == RenderArea.Points:
                    painter.drawPoints(RenderArea.points)
                elif self.shape == RenderArea.Polyline:
                    painter.drawPolyline(RenderArea.points)
                elif self.shape == RenderArea.Polygon:
                    painter.drawPolygon(RenderArea.points)
                elif self.shape == RenderArea.Rect:
                    painter.drawRect(rect)
                elif self.shape == RenderArea.RoundedRect:
                    painter.drawRoundedRect(rect, 25, 25, Qt.RelativeSize)
                elif self.shape == RenderArea.Ellipse:
                    painter.drawEllipse(rect)
                elif self.shape == RenderArea.Arc:
                    painter.drawArc(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Chord:
                    painter.drawChord(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Pie:
                    painter.drawPie(rect, startAngle, arcLength)
                elif self.shape == RenderArea.Path:
                    painter.drawPath(path)
                elif self.shape == RenderArea.Text:
                    painter.drawText(rect, Qt.AlignCenter,
                            "PyQt by\nRiverbank Computing")
                elif self.shape == RenderArea.Pixmap:
                    painter.drawPixmap(10, 10, self.pixmap)

                painter.restore()

        painter.setPen(self.palette().dark().color())
        painter.setBrush(Qt.NoBrush)
        painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Ejemplo n.º 5
0
    def render(self, painter: QPainter) -> None:
        if self._item_style == FileItemStyle.SMALLICON:
            self.paint_smallicon_view(painter)
        elif self._item_style == FileItemStyle.DETAIL:
            self.paint_detail_view(painter)
        else:
            self.paint(painter)

        if self.is_selected:
            painter.save()
            painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
            painter.setOpacity(0.5)
            painter.fillRect(self.tile_rect, QColor(127, 192, 255))
            painter.setCompositionMode(QPainter.CompositionMode_SourceOver)
            painter.setOpacity(1.0)
            painter.setPen(QColor(96, 127, 255))
            painter.setBrush(Qt.NoBrush)
            painter.drawRect(self.tile_rect)
            painter.restore()

        if self.is_cursor:
            painter.setOpacity(1.0)
            painter.setPen(QColor(0, 0, 0))
            painter.setBrush(QColor(255, 255, 255, 96))
            painter.drawRect(self.tile_rect)
Ejemplo n.º 6
0
    def paintEvent(self, ev):
        layout_pos = self.layoutPosition()
        painter = QPainter(self.viewport())

        # pages to paint
        ev_rect = ev.rect().translated(-layout_pos)
        pages_to_paint = set(self._pageLayout.pagesAt(ev_rect))

        # paint the pages
        for p in pages_to_paint:
            rect = (p.rect() & ev_rect).translated(-p.pos())
            painter.save()
            painter.translate(p.pos() + layout_pos)
            p.paint(painter, rect, self.repaintPage)
            painter.restore()

        # TODO paint highlighting

        # remove pending render jobs for pages that were visible, but are not
        # visible now
        margin = 50
        rect = ev_rect.adjusted(-margin, -margin, margin, margin)
        for page in self._prev_pages_to_paint - pages_to_paint:
            if page.renderer and not rect.intersects(page.rect()):
                page.renderer.unschedule(page, self.repaintPage)
        self._prev_pages_to_paint = pages_to_paint
Ejemplo n.º 7
0
    def paintEvent(self, event):
        # TODO: maybe use self.upm*(1+2*BufferHeight) for the denominator as in
        # fontView
        scale = self.height() / (self.upm * 1.2)
        x_offset = \
            (self.width() - self.maxWidth * scale - self.padding * 2) / 2
        if x_offset < 0:
            scale *= 1 + 2 * x_offset / (self.maxWidth * scale)
            x_offset = 0
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.padding, self.padding +
                          (self.ascender * 1.2) * scale)
        painter.scale(scale, -scale)

        col = QColor(Qt.black)
        col.setAlphaF(.2)
        for glyph in self.glyphs:
            if self.alignRight:
                dist = self.maxWidth - glyph.width
            else:
                dist = 0
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.translate(x_offset + dist, 0)
            painter.fillPath(glyphPath, col)
            painter.restore()
Ejemplo n.º 8
0
    def paintEvent(self, QPaintEvent):
        self.updatePosition()
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.transparent)
        painter.setRenderHint(QPainter.Antialiasing, True)

        if self._currentCounter >= self._numberOfLines:
            self._currentCounter = 0

        painter.setPen(Qt.NoPen)
        for i in range(0, self._numberOfLines):
            painter.save()
            painter.translate(self._innerRadius + self._lineLength,
                              self._innerRadius + self._lineLength)
            rotateAngle = float(360 * i) / float(self._numberOfLines)
            painter.rotate(rotateAngle)
            painter.translate(self._innerRadius, 0)
            distance = self.lineCountDistanceFromPrimary(
                    i, self._currentCounter, self._numberOfLines)
            color = self.currentLineColor(distance, self._numberOfLines,
                                          self._trailFadePercentage,
                                          self._minimumTrailOpacity,
                                          self._color)
            painter.setBrush(color)
            rect = QRect(0, -self._lineWidth/2,
                         self._lineLength, self._lineWidth)
            painter.drawRoundedRect(
                    rect, self._roundness, self._roundness, Qt.RelativeSize)
            painter.restore()
Ejemplo n.º 9
0
    def render(self, size):
        image = QImage(size, QImage.Format_ARGB32_Premultiplied)
        if (self.mIncludeBackgroundColor):
            if (self.mMap.backgroundColor().isValid()):
                image.fill(self.mMap.backgroundColor())
            else:
                image.fill(Qt.gray)
        else :
            image.fill(Qt.transparent)
        
        mapSize = self.mRenderer.mapSize()
        margins = self.mRenderer.map().drawMargins()
        mapSize.setWidth(mapSize.width() + margins.left() + margins.right())
        mapSize.setHeight(mapSize.height() + margins.top() + margins.bottom())
        scale = min(size.width() / mapSize.width(), size.height() / mapSize.height())
        scaledSize = mapSize * scale
        painter = QPainter(image)
        # Center the thumbnail in the requested size
        painter.translate((size.width() - scaledSize.width()) / 2,
                          (size.height() - scaledSize.height()) / 2)
        # Scale the map and translate it to adjust for its margins
        painter.scale(scale, scale)
        painter.translate(margins.left() + (size.width() - scaledSize.width()) / 2,
                          margins.top() + (size.height() - scaledSize.height()) / 2)
        if (smoothTransform(scale)):
            painter.setRenderHints(QPainter.SmoothPixmapTransform)
        self.mRenderer.setPainterScale(scale)
        for layer in self.mMap.layers():
            if (self.mVisibleLayersOnly and not layer.isVisible()):
                continue
            painter.setOpacity(layer.opacity())
            tileLayer = dynamic_cast(layer, TileLayer)
            objGroup = dynamic_cast(layer, ObjectGroup)
            imageLayer = dynamic_cast(layer, ImageLayer)
            if (tileLayer):
                self.mRenderer.drawTileLayer(painter, tileLayer)
            elif (objGroup):
                objects = objGroup.objects()
                if (objGroup.drawOrder() == ObjectGroup.TopDownOrder):
                    objects = QList(sorted(objects, key=lambda x:x.y(), reverse=True))
                for object in objects:
                    if (object.isVisible()):
                        if object.rotation() != 0.0:
                            origin = self.mRenderer.pixelToScreenCoords(object.position())
                            painter.save()
                            painter.translate(origin)
                            painter.rotate(object.rotation())
                            painter.translate(-origin)
                        
                        color = MapObjectItem.objectColor(object)
                        self.mRenderer.drawMapObject(painter, object, color)
                        if (object.rotation() != 0):
                            painter.restore()

            elif (imageLayer):
                self.mRenderer.drawImageLayer(painter, imageLayer)

        return image
Ejemplo n.º 10
0
 def paintEvent(self, ev):
     layout_pos = self.layoutPosition()
     painter = QPainter(self.viewport())
     # paint the pages
     ev_rect = ev.rect().translated(-layout_pos)
     for p in self._pageLayout.pagesAt(ev_rect):
         rect = (p.rect() & ev_rect).translated(-p.pos())
         painter.save()
         painter.translate(p.pos() + layout_pos)
         p.paint(painter, rect, self.repaintPage)
         painter.restore()
Ejemplo n.º 11
0
    def paintEvent(self, event):
        # Init painter.
        painter = QPainter(self)
        painter.save()

        # Draw background.
        painter.setBrush(self.background_color)
        painter.setPen(self.background_color)
        painter.drawRect(0, 0, self.rect().width(), self.rect().height())

        # Get start/last render index.
        start_page_index = self.get_start_page_index()
        last_page_index = self.get_last_page_index()

        # Translate painter at y coordinate.
        translate_y = (start_page_index * self.scale * self.page_height) - self.scroll_offset
        painter.translate(0, translate_y)

        # Render pages in visible area.
        for index in list(range(start_page_index, last_page_index)):
            if index < self.page_total_number:
                # Get page image.
                qpixmap = self.get_page_pixmap(index, self.scale)

                # Init render rect.
                render_width = self.page_width * self.scale
                render_height = self.page_height * self.scale
                render_x = (self.rect().width() - render_width) / 2
                render_y = (index - start_page_index) * self.scale * self.page_height

                # Add padding between pages.
                if (index - start_page_index) > 0:
                    painter.translate(0, self.page_padding)

                # Draw page image.
                painter.drawPixmap(QRect(render_x, render_y, render_width, render_height), qpixmap)

        # Clean unused pixmap cache that avoid use too much memory.
        self.clean_unused_page_cache_pixmap()

        painter.restore()

        # Render current page.
        painter.setFont(self.font)
        painter.setPen(self.page_annotate_color)
        painter.drawText(QRect(self.rect().x(),
                               self.rect().y() + self.rect().height() - self.page_annotate_height - self.page_annotate_padding_bottom,
                               self.rect().width() - self.page_annotate_padding_right,
                               self.page_annotate_height),
                         Qt.AlignRight,
                         "{0}% ({1}/{2})".format(int((start_page_index + 1) * 100 / self.page_total_number), start_page_index + 1, self.page_total_number))
Ejemplo n.º 12
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(event.rect(), QBrush(Qt.white))

        painter.translate(66, 66)

        painter.save()
        self.transformPainter(painter)
        self.drawShape(painter)
        painter.restore()

        self.drawOutline(painter)

        self.transformPainter(painter)
        self.drawCoordinates(painter)
Ejemplo n.º 13
0
 def getPixmap(self):
     pixmap = QPixmap(self.width * self.pixelRatio, self.height * self.pixelRatio)
     pixmap.setDevicePixelRatio(self.pixelRatio)
     pixmap.fill(Qt.transparent)
     painter = QPainter(pixmap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.translate(0, self.height)
     painter.scale(1, -1)
     if self.headerAtBottom:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     else:
         bodyRect = (0, 0, self.width, self.height-self.headerHeight)
         headerRect = (0, 0, self.width, self.headerHeight)
     # background
     painter.save()
     if self.headerAtBottom:
         h = self.height
     else:
         h = self.height - self.headerHeight
     painter.translate(0, h)
     painter.scale(1, -1)
     self.drawCellBackground(painter, bodyRect)
     painter.restore()
     # glyph
     if self.headerAtBottom:
         painter.translate(0, self.headerHeight)
     if self.shouldDrawMetrics:
         self.drawCellHorizontalMetrics(painter, bodyRect)
         self.drawCellVerticalMetrics(painter, bodyRect)
     painter.save()
     painter.setClipRect(0, 0, self.width, self.height-self.headerHeight)
     painter.translate(self.xOffset, self.yOffset)
     painter.scale(self.scale, self.scale)
     self.drawCellGlyph(painter)
     painter.restore()
     # foreground
     painter.save()
     painter.translate(0, self.height - self.headerHeight)
     painter.scale(1, -1)
     self.drawCellForeground(painter, bodyRect)
     painter.restore()
     # header
     if self.shouldDrawHeader:
         painter.save()
         if self.headerAtBottom:
             h = 0
         else:
             h = self.height
         painter.translate(0, h)
         painter.scale(1, -1)
         self.drawCellHeaderBackground(painter, headerRect)
         self.drawCellHeaderText(painter, headerRect)
         painter.restore()
     return pixmap
Ejemplo n.º 14
0
    def paintEvent(self, event):
        painter = QPainter(self)
        if self.isEnabled() and not self.isDown() and not self.isChecked():
            painter.save()
            hover_color = QColor("#424242")
            faded_hover_color = QColor(hover_color)
            faded_hover_color.setAlpha(int(self._fader * hover_color.alpha()))
            painter.fillRect(event.rect(), faded_hover_color)
            painter.restore()
        elif self.isDown() or self.isChecked():
            painter.save()
            selected_color = QColor("#161719")
            painter.fillRect(event.rect(), selected_color)
            painter.restore()

        is_titled = bool(self.defaultAction().property("titled"))
        icon_rect = QRect(0, 0, 32, 32)
        icon_rect.moveCenter(event.rect().center())

        if is_titled:
            font = painter.font()
            center_rect = event.rect()
            font.setPointSizeF(6)
            fm = QFontMetrics(font)
            line_height = fm.height()
            text_flags = Qt.AlignHCenter | Qt.AlignTop
            project_name = self.defaultAction().property("heading")
            if project_name is not None:
                center_rect.adjust(0, line_height, 0, 0)
                icon_rect.moveTop(center_rect.top())
            else:
                icon_rect.moveCenter(center_rect.center())
            self.icon().paint(painter, icon_rect, Qt.AlignCenter)
            painter.setFont(font)
            r = QRect(0, 5, self.rect().width(), line_height)
            painter.setPen(Qt.white)
            margin = 5
            available_width = r.width() - margin
            ellided_project_name = fm.elidedText(
                project_name, Qt.ElideMiddle, available_width)
            painter.drawText(r, text_flags, ellided_project_name)
        else:
            self.icon().paint(painter, icon_rect, Qt.AlignCenter)
Ejemplo n.º 15
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        self._optionsRects = {}
        w, h = self.width(), self.height()
        metrics = self.fontMetrics()
        hphp = 2 * _hPad

        painter.save()
        path = QPainterPath()
        path.addRoundedRect(.5, .5, w - 1, h - 1, 4, 4)
        painter.fillPath(path, QColor(250, 250, 250))
        x = 0
        linePath = QPainterPath()
        for text in self._options[:-1]:
            x += hphp + metrics.width(text)
            linePath.moveTo(x, 0)
            linePath.lineTo(x, h)
        pen = painter.pen()
        pen.setColor(QColor(218, 218, 218))
        pen.setWidth(0)
        painter.setPen(pen)
        painter.drawPath(path)
        painter.setRenderHint(QPainter.Antialiasing, False)
        painter.drawPath(linePath)
        painter.restore()

        painter.translate(_hPad, _vPad + metrics.ascent())
        left = 0
        for index, text in enumerate(self._options):
            if index in self._selection:
                color = QColor(20, 146, 230)
            else:
                color = QColor(63, 63, 63)
            painter.setPen(color)
            painter.drawText(0, 0, text)
            textWidth = metrics.width(text)
            rectWidth = textWidth + hphp
            rect = (left, 0, rectWidth, h)
            self._optionsRects[index] = rect
            painter.translate(rectWidth, 0)
            left += rectWidth
Ejemplo n.º 16
0
    def paintEvent(self, event):

        side = min(self.width(), self.height())
        time = QTime.currentTime()
        time = time.addSecs(self.timeZoneOffset * 3600)

        painter = QPainter()
        painter.begin(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.hourColor))

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(self.hourHand)
        painter.restore()

        painter.setPen(self.hourColor)

        for i in range(0, 12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(self.minuteColor))

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(self.minuteHand)
        painter.restore()

        painter.setPen(QPen(self.minuteColor))

        for j in range(0, 60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)
            painter.rotate(6.0)

        painter.end()
Ejemplo n.º 17
0
    def paintEvent(self, ev):
        painter = QPainter(self)

        # calc bar offset
        y_offset = (self.height() - self._barHeight()) // 2
        ## prevent negative offset
        y_offset = 0 if y_offset < 0 else y_offset

        # frame around fraction indicator
        painter.setBrush(self.palette().dark())
        painter.save()
        ## no fill color
        b = painter.brush()
        b.setStyle(Qt.NoBrush)
        painter.setBrush(b)
        painter.drawRect(QRect(QPoint(0, y_offset), QSize(self._barWidth(), self._barHeight())))
        painter.restore()

        # fraction indicator
        painter.drawRect(QRect(QPoint(0, y_offset), QSize(self._barWidth() * self._fraction, self._barHeight())))
Ejemplo n.º 18
0
 def paintEvent(self, ev):
     """Called when paint is needed, finds out which page to magnify."""
     view = self.parent().parent()
     layout = view.pageLayout()
     
     scale = max(min(self._scale, view.MAX_ZOOM * self.MAX_EXTRA_ZOOM / layout.zoomFactor), view.MIN_ZOOM / layout.zoomFactor)
     
     # the position of our center on the layout
     c = self.rect().center() + self.pos() - view.layoutPosition()
     
     # make a region scaling back to the view scale
     rect = QRect(0, 0, self.width() / scale, self.height() / scale)
     rect.moveCenter(c)
     region = QRegion(rect, QRegion.Ellipse) # touches the Pages we need to draw
     
     # our rect on the enlarged pages
     our_rect = self.rect()
     our_rect.moveCenter(QPoint(c.x() * scale, c.y() * scale))
     
     # the virtual position of the whole scaled-up layout
     ev_rect = ev.rect().translated(our_rect.topLeft())
     
     painter = QPainter(self)
     for p in layout.pagesAt(region):
         # reuse the copy of the page if still existing
         try:
             page = self._pages[p]
         except KeyError:
             page = self._pages[p] = p.copy()
         page.x = p.x * scale
         page.y = p.y * scale
         page.width = p.width * scale
         page.height = p.height * scale
         # now paint it
         rect = (page.rect() & ev_rect).translated(-page.pos())
         painter.save()
         painter.translate(page.pos() - our_rect.topLeft())
         page.paint(painter, rect, self.repaintPage)
         painter.restore()
         
     self.drawBorder(painter)
Ejemplo n.º 19
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem,
              index: QModelIndex) -> None:
        painter.save()

        x = option.rect.x()
        y = option.rect.y()
        width = option.rect.width()

        view_type = index.data(Qt.DisplayRole)  # type: ViewRowType
        if view_type == ViewRowType.header:
            display_name, icon = index.data(Roles.device_details)

            self.deviceDisplay.paint_header(
                painter=painter,
                x=x,
                y=y,
                width=width,
                icon=icon,
                display_name=display_name,
            )
        else:
            assert view_type == ViewRowType.content

            data = index.data(Roles.storage)  # type: BackupVolumeUse
            details = make_body_details(
                bytes_total=data.bytes_total,
                bytes_free=data.bytes_free,
                files_to_display=data.backup_type,
                marked=data.marked,
                photos_size_to_download=data.photos_size_to_download,
                videos_size_to_download=data.videos_size_to_download,
            )

            self.deviceDisplay.paint_body(painter=painter,
                                          x=x,
                                          y=y,
                                          width=width,
                                          details=details)

        painter.restore()
Ejemplo n.º 20
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.black)

        if self.pixmap.isNull():
            painter.setPen(Qt.white)
            painter.drawText(self.rect(), Qt.AlignCenter,
                             "Rendering initial image, please wait...")
            return

        if self.curScale == self.pixmapScale:
            painter.drawPixmap(self.pixmapOffset, self.pixmap)
        else:
            scaleFactor = self.pixmapScale / self.curScale
            newWidth = int(self.pixmap.width() * scaleFactor)
            newHeight = int(self.pixmap.height() * scaleFactor)
            newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2
            newY = self.pixmapOffset.y() + (self.pixmap.height() -
                                            newHeight) / 2

            painter.save()
            painter.translate(newX, newY)
            painter.scale(scaleFactor, scaleFactor)
            exposed, _ = painter.matrix().inverted()
            exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1)
            painter.drawPixmap(exposed, self.pixmap, exposed)
            painter.restore()

        text = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \
                "hold left mouse button to scroll."
        metrics = painter.fontMetrics()
        textWidth = metrics.width(text)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0, 127))
        painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10,
                         metrics.lineSpacing() + 5)
        painter.setPen(Qt.white)
        painter.drawText((self.width() - textWidth) / 2,
                         metrics.leading() + metrics.ascent(), text)
Ejemplo n.º 21
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.save()
        painter.setRenderHint(QPainter.HighQualityAntialiasing)

        if self.qimg is not None:
            # painter.drawImage(QRectF(0., 0., self.width(), self.height()), self.qimg)
            painter.drawImage(QRectF(0., 0., self.width(), self.height()), self.qimg,
                              QRectF(0, 0, self.qimg.width(), self.qimg.height()))

        while len(self.lineQueue) > 0:
            l = self.lineQueue.pop()
            painter.setPen(QPen(QBrush(l.color), l.width))
            painter.drawLine(l.line)

        pen = painter.pen()
        # penwidth = pen.width()
        while len(self.squareQueue) > 0:
            r = self.squareQueue.pop()
            if r.fill is True:
                painter.setBrush(r.color)
            else:
                painter.setBrush(Qt.transparent)
            pen.setColor(r.color)
            pen.setWidth(r.width)
            painter.setPen(pen)
            if fabs(r.ang) > 0.01:
                center = r.rect.center()
                painter.translate(center)
                painter.rotate(r.ang)
                painter.drawRoundedRect(QRect(r.rect.topLeft() - center, r.rect.size()), 40, 40)
                painter.rotate(-r.ang)
                painter.translate(-center)
            else:
                painter.drawRect(r.rect)
            if r.id >= 0:
                painter.drawText(QPointF(r.rect.x(), r.rect.y()), s.setNum(r.id))

        painter.restore()
        super(ImgViewer, self).paintEvent(event)
Ejemplo n.º 22
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setFont(UIFont)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = event.rect()

        # draw the background
        painter.fillRect(rect, self._backgroundColor)
        if self._glyph is None:
            return

        # apply the overall scale
        painter.save()
        # + translate and flip
        painter.translate(0, self.height())
        painter.scale(self._scale, -self._scale)

        # move into position
        xOffsetInv, yOffsetInv, _, _ = self._drawingRect
        painter.translate(-xOffsetInv, -yOffsetInv)

        # gather the layers
        layerSet = self._glyph.layerSet
        if layerSet is None:
            layers = [(self._glyph, None, True)]
        else:
            glyphName = self._glyph.name
            layers = []
            for layerName in reversed(layerSet.layerOrder):
                layer = layerSet[layerName]
                if glyphName not in layer:
                    continue
                glyph = layer[glyphName]
                layers.append((glyph, layerName, layer == layerSet.defaultLayer))

        self.drawBackground(painter)
        for glyph, layerName, default in layers:
            self.drawGlyphLayer(painter, glyph, layerName, default)
        self.drawForeground(painter)
        painter.restore()
Ejemplo n.º 23
0
def draw_arrow(
        painter: QPainter,
        up: bool,
        x: int,
        y: int,
        width: int,
        height: int,
        brush: QBrush
):
    width_factor = 0.2
    height_factor = 0.33
    height_line = height * height_factor * 2
    width_line = width * width_factor

    painter.save()

    if up:
        painter.translate(x, y + height)
        painter.scale(1.0, -1.0)

    pen = QPen()
    pen.setBrush(brush)
    painter.setBrush(brush)
    painter.setPen(pen)

    path = QPainterPath()
    path.moveTo(width // 2 - width_line // 2, 0)
    path.lineTo(width // 2 + width_line // 2, 0)
    path.lineTo(width // 2 + width_line // 2, height_line)
    path.lineTo(width, height_line)
    path.lineTo(width // 2, height)
    path.lineTo(0, height_line)
    path.lineTo(width // 2 - width_line // 2, height_line)
    path.lineTo(width // 2 - width_line // 2, 0)

    painter.fillPath(path, brush)
    painter.drawPath(path)

    painter.restore()
Ejemplo n.º 24
0
    def paint(self,
              painter: QtGui.QPainter,
              option: 'QStyleOptionGraphicsItem',
              widget: typing.Optional[QWidget] = ...):

        if not self.path.length():

            path = QPainterPath()
            path.moveTo(0, 0)
            rand = np.random.rand(self.data_size) * 100
            for i in np.arange(self.data_size):
                path.lineTo(i, rand[i])

            self.path = path

        painter.save()
        pen = QPen()
        pen.setCosmetic(True)
        pen.setColor(Qt.darkBlue)
        painter.setPen(pen)
        painter.drawPath(self.path)
        painter.restore()
Ejemplo n.º 25
0
    def paintEvent(self, event):
        if not self._waiting:
            # 交给原来的绘制
            super(ProgressButton, self).paintEvent(event)
            return
        # 自定义绘制
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)

        for item, _ in self._items:
            painter.save()
            color = self._circleColor.toRgb()
            color.setAlphaF(item.opacity)
            painter.setBrush(color)
            diameter = 2 * self._circleRadius
            painter.drawRoundedRect(
                QRectF(item.x / 100 * self.width() - diameter,
                       (self.height() - self._circleRadius) / 2, diameter,
                       diameter), self._circleRadius, self._circleRadius)
            painter.restore()
Ejemplo n.º 26
0
    def _draw(self, painter: QPainter, width: int, height: int):
        painter.setBrush(QBrush(Color.brown))

        # main branch
        painter.drawPolygon(QPointF(-self.base_width(width) * smoothen_curve(self.age), 0),
                            QPointF(self.base_width(width) * smoothen_curve(self.age), 0),
                            QPointF(0, self.base_height(height) * smoothen_curve(self.age)))

        # other branches
        for h, rotation in self.branches:
            painter.save()

            # translate/rotate to the position from which the branches grow
            painter.translate(0, self.base_height(height * h * smoothen_curve(self.age)))
            painter.rotate(degrees(rotation))

            painter.drawPolygon(
                QPointF(-self.branch_width(width) * smoothen_curve(self.get_adjusted_age()) * (1 - h), 0),
                QPointF(self.branch_width(width) * smoothen_curve(self.get_adjusted_age()) * (1 - h), 0),
                QPointF(0, self.branch_height(height) * smoothen_curve(self.get_adjusted_age()) * (1 - h)))

            painter.restore()
Ejemplo n.º 27
0
    def _draw(self, painter: QPainter, width: int, height: int):
        self.x = self.flower_center_x(width) * smoothen_curve(self.age)
        self.y = self.flower_center_y(height) * smoothen_curve(self.age)

        painter.setPen(QPen(Color.green, self.stem_width * smoothen_curve(self.age)))

        # draw the stem
        path = QPainterPath()
        path.quadTo(0, self.y * 0.6, self.x, self.y)
        painter.drawPath(path)

        # draw the leaves
        for position, coefficient, rotation in self.leafs:
            painter.save()

            # find the point on the stem and rotate the leaf accordingly
            painter.translate(path.pointAtPercent(position))
            painter.rotate(degrees(rotation))

            # rotate according to where the flower is leaning towards
            if self.y != 0:
                painter.rotate(-degrees(sin(self.x / self.y)))

            # make it so both leaves are facing the same direction
            if rotation < 0:
                painter.scale(-1, 1)

            painter.setBrush(QBrush(Color.green))
            painter.setPen(QPen(0))

            # draw the leaf
            leaf = QPainterPath()
            leaf.setFillRule(Qt.WindingFill)
            ls = self.leaf_size(width) * smoothen_curve(self.age) ** 2 * coefficient
            leaf.quadTo(0.4 * ls, 0.5 * ls, 0, ls)
            leaf.cubicTo(0, 0.5 * ls, -0.4 * ls, 0.4 * ls, 0, 0)
            painter.drawPath(leaf)

            painter.restore()
Ejemplo n.º 28
0
    def paint(
        self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex
    ) -> None:
        """
        Paint a checkbox without a label
        """

        checked = index.data(Qt.CheckStateRole) == Qt.Checked
        enabled = int(index.flags() & Qt.ItemIsEditable) > 0

        if not checked and not enabled:
            return

        painter.save()

        checkboxStyleOption = QStyleOptionButton()
        if checked:
            checkboxStyleOption.state |= QStyle.State_On
        else:
            checkboxStyleOption.state |= QStyle.State_Off

        if enabled:
            checkboxStyleOption.state |= QStyle.State_Enabled
            checkboxStyleOption.state &= ~QStyle.State_ReadOnly
        else:
            checkboxStyleOption.state &= ~QStyle.State_Enabled
            checkboxStyleOption.state |= QStyle.State_ReadOnly
            color = checkboxStyleOption.palette.color(QPalette.Window).darker(130)
            checkboxStyleOption.palette.setColor(QPalette.Text, color)

        checkboxStyleOption.rect = option.rect
        checkboxStyleOption.rect.setX(
            option.rect.x() + round(option.rect.width() / 2) - self.checkboxHalfWidth
        )

        QApplication.style().drawControl(
            QStyle.CE_CheckBox, checkboxStyleOption, painter
        )
        painter.restore()
Ejemplo n.º 29
0
 def paintEvent(self, event):
     painter = QPainter(self)
     if self.isEnabled() and not self.isDown() and not self.isChecked():
         painter.save()
         hover_color = QColor("#424242")
         faded_hover_color = QColor(hover_color)
         faded_hover_color.setAlpha(int(self._fader * hover_color.alpha()))
         painter.fillRect(event.rect(), faded_hover_color)
         painter.restore()
     elif self.isDown() or self.isChecked():
         painter.save()
         selected_color = QColor("#090909")
         painter.fillRect(event.rect(), selected_color)
         painter.restore()
     # fm = QFontMetrics(painter.font())
     # rect = QRect(-3, 2, self.rect().width(), fm.height())
     rect = event.rect()
     icon_rect = QRect(0, 0, 22, 22)
     self.icon().paint(painter, icon_rect, Qt.AlignVCenter)
     painter.drawText(
         rect.adjusted(0, 0, -3, 0),
         Qt.AlignRight | Qt.AlignVCenter, self.text())
Ejemplo n.º 30
0
    def paint(self,
              painter: QtGui.QPainter,
              option: 'QStyleOptionGraphicsItem',
              widget=None):

        view = self.scene().views()[0]
        painter.save()

        pen = QPen(Qt.white)
        pen.setCosmetic(True)
        if self.mouse_over:
            view.setCursor(Qt.PointingHandCursor)
        else:
            view.setCursor(Qt.ArrowCursor)

        painter.setPen(pen)
        transform = QTransform()
        transform.scale(1 + self.data_range_x_pix / 1000, 1)
        painter.setTransform(transform)
        painter.drawPath(self.path)

        painter.restore()
Ejemplo n.º 31
0
def generateTheme(themeDatas, screenRect):
    # Window Background
    px = QPixmap(screenRect.size())
    px.fill(QColor(themeDatas["Background/Color"]))

    painter = QPainter(px)
    if themeDatas["Background/ImageFile"]:
        path = findBackground(themeDatas["Background/ImageFile"])
        _type = themeDatas["Background/Type"]
        if path and _type > 0:
            if _type == 1:  # Tiled
                painter.fillRect(screenRect, QBrush(QImage(path)))
            else:
                img = QImage(path)
                scaled = img.size()
                if _type == 3:  # Stretched
                    scaled.scale(screenRect.size(), Qt.IgnoreAspectRatio)
                elif _type == 4:  # Scaled
                    scaled.scale(screenRect.size(), Qt.KeepAspectRatio)
                elif _type == 5:  # Zoomed
                    scaled.scale(screenRect.size(), Qt.KeepAspectRatioByExpanding)

                painter.drawImage((screenRect.width() - scaled.width()) / 2,
                                  (screenRect.height() - scaled.height()) / 2, img.scaled(scaled))

    # Text Background
    textRect = themeTextRect(themeDatas, screenRect)

    painter.save()
    color = QColor(themeDatas["Foreground/Color"])
    color.setAlpha(themeDatas["Foreground/Opacity"] * 255 / 100)
    painter.setBrush(color)
    painter.setPen(Qt.NoPen)
    r = themeDatas["Foreground/Rounding"]
    painter.drawRoundedRect(textRect, r, r)
    painter.restore()

    painter.end()
    return px
Ejemplo n.º 32
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setOpacity(self._opacity)
     painter.setRenderHint(QPainter.Antialiasing, True)
     painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
     painter.save()
     pen = QPen(Qt.DashLine)
     pen.setWidthF(0.5)
     pen.setColor(Qt.white)
     painter.setPen(pen)
     c = QPoint(self.off, self.height() * 0.6)
     painter.drawPolyline(self._sw1.p1, c)
     painter.drawPolyline(self._sw1.p3, c)
     painter.drawPolyline(c, self._sw2.p8)
     painter.restore()
     pen = QPen(Qt.SolidLine)
     pen.setWidthF(0.5)
     pen.setColor(Qt.white)
     painter.setPen(pen)
     painter.drawPolyline(self._sw1.p2, self._sw1.p8)
     painter.drawPolyline(self._sw1.p7, self._sw1.p8)
     painter.drawPolyline(self._sw1.p8, self._sw1.p9)
Ejemplo n.º 33
0
    def paintEvent(self, event):
        side = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogPosition.positionHandColor)

        painter.save()
        painter.rotate(self.angle)

        painter.drawConvexPolygon(AnalogPosition.positionHand)
        painter.restore()

        painter.setPen(AnalogPosition.positionHandColor)

        for j in range(32):
            painter.drawLine(92, 0, 96, 0)
            painter.rotate(11.25)
Ejemplo n.º 34
0
Archivo: Danmu.py Proyecto: afawa/danmu
 def paintEvent(self, QPaintEvent):
     painter = QPainter(self)
     painter.save()
     metrics = QFontMetrics(self.getQFont())
     path = QPainterPath()
     pen = QPen(QColor(0, 0, 0, 230))
     painter.setRenderHint(QPainter.Antialiasing)
     penwidth = 4
     pen.setWidth(penwidth)
     len = metrics.width(self.__Dtext)
     w = self.width()
     px = (len - w) / 2
     if px < 0:
         px = -px
     py = (self.height() - metrics.height()) / 2 + metrics.ascent()
     if py < 0:
         py = -py
     path.addText(px + 2, py + 2, self.getQFont(), self.__Dtext)
     painter.strokePath(path, pen)
     painter.drawPath(path)
     painter.fillPath(path, QBrush(self.getQColor()))
     painter.restore()
Ejemplo n.º 35
0
    def paintEvent(self, event):
        side = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(AnalogPosition.positionHandColor)

        painter.save()
        painter.rotate(self.angle)

        painter.drawConvexPolygon(AnalogPosition.positionHand)
        painter.restore()

        painter.setPen(AnalogPosition.positionHandColor)

        for j in range(32):
            painter.drawLine(92, 0, 96, 0)
            painter.rotate(11.25)
Ejemplo n.º 36
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.black)

        if self.pixmap.isNull():
            painter.setPen(Qt.white)
            painter.drawText(self.rect(), Qt.AlignCenter,
                    "Rendering initial image, please wait...")
            return

        if self.curScale == self.pixmapScale:
            painter.drawPixmap(self.pixmapOffset, self.pixmap)
        else:
            scaleFactor = self.pixmapScale / self.curScale
            newWidth = int(self.pixmap.width() * scaleFactor)
            newHeight = int(self.pixmap.height() * scaleFactor)
            newX = self.pixmapOffset.x() + (self.pixmap.width() - newWidth) / 2
            newY = self.pixmapOffset.y() + (self.pixmap.height() - newHeight) / 2

            painter.save()
            painter.translate(newX, newY)
            painter.scale(scaleFactor, scaleFactor)
            exposed, _ = painter.matrix().inverted()
            exposed = exposed.mapRect(self.rect()).adjusted(-1, -1, 1, 1)
            painter.drawPixmap(exposed, self.pixmap, exposed)
            painter.restore()

        text = "Use mouse wheel or the '+' and '-' keys to zoom. Press and " \
                "hold left mouse button to scroll."
        metrics = painter.fontMetrics()
        textWidth = metrics.width(text)

        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0, 127))
        painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10,
                metrics.lineSpacing() + 5)
        painter.setPen(Qt.white)
        painter.drawText((self.width() - textWidth) / 2,
                metrics.leading() + metrics.ascent(), text)
Ejemplo n.º 37
0
    def paintEvent(self, event):
        super(CColorControl, self).paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        painter.setPen(Qt.NoPen)

        # 变换圆心
        painter.translate(self.rect().center())

        # 画背景方格图
        painter.save()
        # 保证方格在前景圆内部
        diameter = min(self.width(), self.height()) - 8
        radius = diameter / 2
        path = QPainterPath()
        path.addRoundedRect(-radius, -radius, diameter, diameter, radius,
                            radius)
        painter.setClipPath(path)

        pixSize = 5
        for x in range(int(self.width() / pixSize)):
            for y in range(int(self.height() / pixSize)):
                _x, _y = x * pixSize, y * pixSize
                painter.fillRect(_x - radius, _y - radius, pixSize, pixSize,
                                 Qt.white if x % 2 != y % 2 else Qt.darkGray)
        painter.restore()

        # 画前景颜色
        diameter = min(self.width(), self.height()) - 4
        radius = diameter / 2
        path = QPainterPath()
        path.addRoundedRect(-radius, -radius, diameter, diameter, radius,
                            radius)
        painter.setClipPath(path)

        painter.setBrush(self._color)
        painter.drawRoundedRect(-radius, -radius, diameter, diameter, radius,
                                radius)
Ejemplo n.º 38
0
    def drawBg(self, painter: QPainter):
        painter.save()
        painter.setPen(Qt.NoPen)
        if self.Checked:
            painter.setBrush(self.bgColorOn)
        else:
            painter.setBrush(self.bgColorOff)
        rect = QRect(0, 0, self.width(), self.height())
        radius = rect.height() / 2
        circleWidth = rect.height()

        path = QPainterPath()
        path.moveTo(radius, rect.left())
        path.arcTo(QRectF(rect.left(), rect.top(), circleWidth, circleWidth),
                   90, 180)
        path.lineTo(rect.width() - radius, rect.height())
        path.arcTo(
            QRectF(rect.width() - rect.height(), rect.top(), circleWidth,
                   circleWidth), 270, 180)
        path.lineTo(radius, rect.top())
        painter.drawPath(path)
        painter.restore()
Ejemplo n.º 39
0
def generateTheme(themeDatas, screenRect):
    # Window Background
    px = QPixmap(screenRect.size())
    px.fill(QColor(themeDatas["Background/Color"]))

    painter = QPainter(px)
    if themeDatas["Background/ImageFile"]:
        path = findBackground(themeDatas["Background/ImageFile"])
        _type = themeDatas["Background/Type"]
        if path and _type > 0:
            if _type == 1:  # Tiled
                painter.fillRect(screenRect, QBrush(QImage(path)))
            else:
                img = QImage(path)
                scaled = img.size()
                if _type == 3:  # Stretched
                    scaled.scale(screenRect.size(), Qt.IgnoreAspectRatio)
                elif _type == 4:  # Scaled
                    scaled.scale(screenRect.size(), Qt.KeepAspectRatio)
                elif _type == 5:  # Zoomed
                    scaled.scale(screenRect.size(), Qt.KeepAspectRatioByExpanding)

                painter.drawImage((screenRect.width() - scaled.width()) / 2,
                                  (screenRect.height() - scaled.height()) / 2, img.scaled(scaled))

    # Text Background
    textRect = themeTextRect(themeDatas, screenRect)

    painter.save()
    color = QColor(themeDatas["Foreground/Color"])
    color.setAlpha(themeDatas["Foreground/Opacity"] * 255 / 100)
    painter.setBrush(color)
    painter.setPen(Qt.NoPen)
    r = themeDatas["Foreground/Rounding"]
    painter.drawRoundedRect(textRect, r, r)
    painter.restore()

    painter.end()
    return px
Ejemplo n.º 40
0
    def paintEvent(self, event):
        locker = QMutexLocker(self.thread.mutex)
        img = self.thread.image

        dst = self.imgRect()
        qp = QPainter()
        qp.begin(self)

        # draw background
        brush = QBrush(Qt.SolidPattern)
        # brush.setColor(Qt.white)
        brush.setColor(Qt.black)
        qp.setBrush(brush)
        qp.drawRect(QRect(0,0,self.width(),self.height()))

        qp.save()
        qp.translate(dst.x()+dst.width()/2, dst.y()+dst.height()/2)
        qp.scale(dst.width()/img.width(), dst.width()/img.width())
        qp.translate(-img.width()/2, -img.height()/2)
        qp.drawImage(0,0,img)
        qp.restore()

        # draw orientation lines
        qp.setPen(QColor(255,255,255,150))
        qp.drawLine(dst.x()+dst.width()/3,dst.y()+0,
            dst.x()+dst.width()/3,dst.y()+dst.height())
        qp.drawLine(dst.x()+dst.width()/2,dst.y()+0,
            dst.x()+dst.width()/2,dst.y()+dst.height())
        qp.drawLine(dst.x()+dst.width()*2/3,dst.y()+0,
            dst.x()+dst.width()*2/3,dst.y()+dst.height())
        qp.drawLine(dst.x()+0,dst.y()+dst.height()/3,
            dst.x()+dst.width(),dst.y()+dst.height()/3)
        qp.drawLine(dst.x()+0,dst.y()+dst.height()/2,
            dst.x()+dst.width(),dst.y()+dst.height()/2)
        qp.drawLine(dst.x()+0,dst.y()+dst.height()*2/3,
            dst.x()+dst.width(),dst.y()+dst.height()*2/3)

        qp.end()
    def paintEvent(self, event):
        global real_time, minotaur_standard_time

        side = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(MSTAnalogClock.hourColor)

        painter.save()
        hour_adjust = 30.0 * ((int(minotaur_standard_time.hour) +
                               int(minotaur_standard_time.minute) / 60.0))
        hour = math.floor(hour_adjust / 30.0)
        painter.rotate(hour_adjust)
        painter.drawConvexPolygon(MSTAnalogClock.hourHand)
        painter.restore()

        painter.setPen(MSTAnalogClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(MSTAnalogClock.minuteColor)

        painter.save()
        minute_adjust = 6.0 * ((int(minotaur_standard_time.minute) +
                                int(minotaur_standard_time.second) / 60.0))
        if minute_adjust < 0:
            minute_adjust += 360
        minute = math.floor(minute_adjust / 6.0)
        painter.rotate(minute_adjust)
        painter.drawConvexPolygon(MSTAnalogClock.minuteHand)
        painter.restore()

        painter.setPen(Qt.NoPen)
        painter.setBrush(MSTAnalogClock.secondColor)

        painter.save()
        second_adjust = 6.0 * int(minotaur_standard_time.second)
        if second_adjust < 0:
            second_adjust += 360
        second = math.floor(second_adjust / 6.0)
        painter.rotate(second_adjust)
        painter.drawConvexPolygon(MSTAnalogClock.secondHand)
        painter.restore()

        painter.setPen(MSTAnalogClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)
            painter.rotate(6.0)
Ejemplo n.º 42
0
    def paintEvent(self, event):
        side = min(self.width(), self.height())
        time = QTime.currentTime()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(ShapedClock.hourColor)

        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)))
        painter.drawConvexPolygon(ShapedClock.hourHand)
        painter.restore()

        painter.setPen(ShapedClock.hourColor)

        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)

        painter.setPen(Qt.NoPen)
        painter.setBrush(ShapedClock.minuteColor)

        painter.save()
        painter.rotate(6.0 * (time.minute() + time.second() / 60.0))
        painter.drawConvexPolygon(ShapedClock.minuteHand)
        painter.restore()

        painter.setPen(ShapedClock.minuteColor)

        for j in range(60):
            if (j % 5) != 0:
                painter.drawLine(92, 0, 96, 0)

            painter.rotate(6.0)
Ejemplo n.º 43
0
def draw_labeled_value(
        painter: QPainter,
        label: str,
        value: int,
        label_font: QFont,
        value_font: QFont,
        center_x: int,
        center_y: int,
        color: QBrush = QBrush(QColor(255, 255, 255, 255))
):
    value_str = "{}".format(value)
    label_str = "{}".format(label)
    value_metrics = QFontMetrics(value_font)
    label_metrics = QFontMetrics(label_font)

    painter.save()

    center_y += abs(value_metrics.height() - label_metrics.height()) // 2

    draw_adjusted_text(
        painter,
        value_str,
        value_font,
        center_x,
        center_y - value_metrics.height() // 2,
        color
    )

    draw_adjusted_text(
        painter,
        label_str,
        label_font,
        center_x,
        center_y + label_metrics.height() // 2,
        color
    )

    painter.restore()
Ejemplo n.º 44
0
def draw_adjusted_text(
        painter: QPainter,
        label: str,
        font: QFont,
        center_x: int,
        center_y: int,
        color: QBrush = QBrush(QColor(0, 0, 0, 255))
):
    """
    Draw a string text with a particular format in the screen
    :param painter:
    :param label:
    :param font:
    :param center_x:
    :param center_y:
    :param color:
    """
    painter.save()
    painter.setRenderHints(QPainter.TextAntialiasing)
    painter.setFont(font)
    pen = QPen()
    pen.setBrush(color)
    painter.setPen(pen)
    metrics = QFontMetrics(font)
    label_width = metrics.boundingRect(label).width()
    label_height = metrics.boundingRect(label).height()

    painter.drawText(
        QRectF(
            center_x - label_width / 2,
            center_y - label_height / 2,
            label_width,
            label_height
        ),
        Qt.AlignHCenter,
        label
    )
    painter.restore()
Ejemplo n.º 45
0
    def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None:
        super().paint(painter, option, index)
        polygon_id = index.data(BaseColorMappingDialog.PolygonRole)
        brushstyle = index.data(BaseColorMappingDialog.BrushStyleRole)
        h = option.rect.height()

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setClipRect(option.rect)
        painter.setPen(QPen(Qt.lightGray, h/5.))
        if brushstyle is not None:
            painter.setBrush(QBrush(Qt.lightGray, brushstyle))
        zoom = .9
        painter.setTransform(QTransform()
                             .translate(option.rect.x()+h/2+10, option.rect.y()+h/2)
                             .rotate(-5.)
                             .scale(h/100.*zoom, h/100.*zoom))
        if polygon_id is None or polygon_id == NodePolygon.Circle:
            painter.drawEllipse(QRect(-50, -50, 100, 100))
        else:
            polygon = NODE_POLYGON_MAP.get(polygon_id, QPolygonF())
            painter.drawPolygon(polygon)
        painter.restore()
Ejemplo n.º 46
0
    def paintEvent(self, event):
        super(MetroLineProgress, self).paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(self.rect(), self.BackgroundColor)
        painter.setPen(Qt.NoPen)

        for item, _ in self._items:
            painter.save()
            color = self.Color.toRgb()
            color.setAlphaF(item.opacity)
            painter.setBrush(color)
            # 5<= radius <=10
            radius = qBound(self.Radius, self.Radius / 200 *
                            self.height(), 2 * self.Radius)
            diameter = 2 * radius
            painter.drawRoundedRect(
                QRectF(
                    item.x / 100 * self.width() - diameter,
                    (self.height() - radius) / 2,
                    diameter, diameter
                ), radius, radius)
            painter.restore()
Ejemplo n.º 47
0
    def draw(self, painter: QPainter):
        count = self.primary.count * self.secondary.count * self.tertiary.count
        da = (self.angle.max - self.angle.min) / count
        dv = (self.label.max - self.label.min) / count

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing)

        painter.translate(self.center)
        painter.rotate(-self.angle.min)

        for i in range(count + 1):
            if self.is_primary(i):
                self.draw_primary(painter)
                v = self.label.min + i * dv
                a = self.angle.min + da * i
                self.draw_label(painter, v, a)
            elif self.is_secondary(i):
                self.draw_secondary(painter)
            else:
                self.draw_tertiary(painter)
            painter.rotate(-da)
        painter.restore()
    def draw_on_canvas(self):
        painter = QPainter(self.canvas)
        painter.setPen(
            QPen(QColor(Qt.green), 5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))

        # draw select rectangle
        painter.save()

        # find the left top corner
        self.select_min_x = min(self.select_rec_start_pos[0], self.mouse_x)
        self.select_max_x = max(self.select_rec_start_pos[0], self.mouse_x)
        self.select_min_y = min(self.select_rec_start_pos[1], self.mouse_y)
        self.select_max_y = max(self.select_rec_start_pos[1], self.mouse_y)

        painter.drawRect(
            self.select_min_x, self.select_min_y,
            geometry_utils.two_points_distances(self.select_min_x,
                                                self.select_max_x),
            geometry_utils.two_points_distances(self.select_min_y,
                                                self.select_max_y))

        painter.restore()
        painter.end()
Ejemplo n.º 49
0
 def paintEvent(self, e):
     # myDebug(self.__class__.__name__, get_current_function_name())
     if self.mImage is not None:
         painter = QPainter(self)
         painter.save()
         painter.setRenderHint(QPainter.Antialiasing, True)
         image_height = (self.width() -
                         4) * self.mImage.height() / self.mImage.width()
         painter.drawPixmap(2,
                            self.height() / 2 - image_height / 2,
                            self.width() - 4, image_height,
                            QtGui.QPixmap.fromImage(self.mImage))
         painter.restore()
     else:
         painter = QPainter(self)
         painter.save()
         painter.setRenderHint(QPainter.Antialiasing, True)
         image_height = (self.width() - 4) * self.mBackImage.height(
         ) / self.mBackImage.width()
         painter.drawPixmap(2,
                            self.height() / 2 - image_height / 2,
                            self.width() - 4, image_height, self.mBackImage)
         painter.restore()
Ejemplo n.º 50
0
    def paintEvent(self, e):
        """
        draw pixmap as a the background with a dark overlay

        HELP: currently, this cost much CPU
        """
        painter = QPainter(self)
        painter.setPen(Qt.NoPen)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)

        # calculate available size
        draw_width = self.width()
        draw_height = 10  # spacing defined in table container
        draw_height += self.bottom_panel.height()
        if self.table_container.meta_widget.isVisible():
            draw_height += self.table_container.meta_widget.height()
        extra = self.table_container.current_extra
        if extra is not None and extra.isVisible():
            draw_height += extra.height()
        if self.table_container.toolbar.isVisible():
            draw_height += self.table_container.toolbar.height()

        scrolled = self.scrollarea.verticalScrollBar().value()
        max_scroll_height = draw_height - self.bottom_panel.height()

        if scrolled >= max_scroll_height:
            painter.save()
            painter.setBrush(self.palette().brush(QPalette.Window))
            painter.drawRect(self.bottom_panel.rect())
            painter.restore()
            return

        if self._pixmap is not None:
            self._draw_pixmap(painter, draw_width, draw_height, scrolled)
            self._draw_pixmap_overlay(painter, draw_width, draw_height,
                                      scrolled)
        else:
            # draw gradient for widgets(bottom panel + meta_widget + ...) above table
            self._draw_overlay(painter, draw_width, draw_height, scrolled)

            # if scrolled height > 30, draw background to seperate bottom_panel and body
            if scrolled >= 30:
                painter.save()
                painter.setBrush(self.palette().brush(QPalette.Window))
                painter.drawRect(self.bottom_panel.rect())
                painter.restore()
                return

            # since the body's background color is palette(base), we use
            # the color to draw background for remain empty area
            painter.save()
            painter.setBrush(self.palette().brush(QPalette.Base))
            painter.drawRect(0, draw_height, draw_width,
                             self.height() - draw_height)
            painter.restore()
        painter.end()
Ejemplo n.º 51
0
    def paint(self, painter: QPainter, option, index):
        # reference following link
        # https://stackoverflow.com/questions/53353450/how-to-highlight-a-words-in-qtablewidget-from-a-searchlist
        # https://stackoverflow.com/questions/34623036/implementing-a-delegate-for-wordwrap-in-a-qtreeview-qt-pyside-pyqt
        painter.save()
        doc = QTextDocument(self)
        options = QStyleOptionViewItem(option)
        self.initStyleOption(options, index)
        doc.setPlainText(options.text)
        # keyword = index.data(Qt.UserRole)
        # if self.keywords:
        self.keywordHighlight(doc)
        options.text = ""
        style = QApplication.style()
        style.drawControl(QStyle.CE_ItemViewItem, options,
                          painter)  # for selection highlight

        ctx = QAbstractTextDocumentLayout.PaintContext()
        if index.data(Qt.UserRole) == 'reserved':
            ctx.palette.setColor(QPalette.Text, QColor.fromRgb(204, 204, 204))
            doc.setDefaultFont(
                QFont(option.font.family(),
                      option.font.pointSize() * 2 // 3))

        else:
            doc.setDefaultFont(option.font)

        textRect = option.rect
        # margin = 4
        # textRect.setTop(textRect.top() + margin)
        textRect.setTop(textRect.top())
        painter.translate(textRect.topLeft())
        painter.setClipRect(textRect.translated(-textRect.topLeft()))

        doc.setTextWidth(option.rect.width())
        doc.documentLayout().draw(painter, ctx)
        painter.restore()
Ejemplo n.º 52
0
    def paintEvent(self, event):
        if (not self.m_displayedWhenStopped) and (not self.isAnimated()):
            return

        width = min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        outerRadius = (width - 1) * 0.5
        innerRadius = (width - 1) * 0.5 * 0.5

        capsuleHeight = outerRadius - innerRadius

        capsuleWidth = max(1.2, 1.0 + capsuleHeight * 0.19,
                           0.35 + capsuleHeight * 0.28)

        capsuleRadius = capsuleWidth / 2

        for i in range(0, 12):
            color = QtGui.QColor(self.m_color)

            if self.isAnimated():
                color.setAlphaF(1.0 - (i / 12.0))
            else:
                color.setAlphaF(0.2)

            painter.setPen(Qt.NoPen)
            painter.setBrush(color)
            painter.save()
            painter.translate(self.rect().center())
            painter.rotate(self.m_angle - (i * 30.0))
            painter.drawRoundedRect(capsuleWidth * -0.5,
                                    (innerRadius + capsuleHeight) * -1,
                                    capsuleWidth, capsuleHeight, capsuleRadius,
                                    capsuleRadius)
            painter.restore()
Ejemplo n.º 53
0
    def paintEvent(self, event):
        side = 0.8 * min(self.width(), self.height())

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.translate(self.width() / 2, self.height() / 2 / 0.95)
        painter.scale(side / 200.0 * 0.95, side / 200.0 * 0.95)

        painter.setPen(Qt.NoPen)

        painter.setBrush(self.ref_color)
        painter.save()
        painter.rotate(self.refValue)
        painter.drawConvexPolygon(self.hand)
        painter.restore()

        painter.setBrush(self.color)
        painter.save()
        painter.rotate(self.value - self.refValue)
        painter.drawConvexPolygon(self.hand)
        painter.restore()

        painter.save()
        painter.setPen(QColor(0, 0, 0))

        for i in range(27):
            painter.drawLine(88, 0, 92, 0)
            painter.rotate(15)

        painter.restore()
        painter.save()
        painter.setPen(QColor(0, 0, 0))
        painter.rotate(0.0)
        for i in range(9):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(45.0)

        painter.restore()

        painter.setPen(QColor(0, 0, 0))
        font = painter.font()
        font.setPointSize(font.pointSize() * 1.2)
        painter.setFont(font)
        painter.drawText(QRectF(-7.5, 100, 30, 20), '180°')
        painter.drawText(QRectF(-5, -110, 35, 20), '0°')
        painter.drawText(QRectF(-125, -5, 30, 20), '270°')
        painter.drawText(QRectF(105, -5, 35, 20), '90°')
Ejemplo n.º 54
0
    def paintEvent(self, e): 
        time = QTime.currentTime() 
        qp = QPainter()
 
        qp.begin(self)
        #qp.setRenderHint(QPainter.Antialiasing)  # 开启这个抗锯齿,会很占cpu的!
        qp.translate(self.width() / 2, self.height() / 2) 
        qp.scale(self.side / 200.0, self.side / 200.0)
  
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.hourColor)
        qp.save()
        qp.rotate(30.0 * ((time.hour() + time.minute()/ 60.0)))
        qp.drawConvexPolygon(self.hourHand)
        qp.restore()
         
        qp.setPen(self.minuteColor)
        qp.drawText(0,0,"Testdddddddddddddd")
        for i in range(12): 
            qp.drawLine(88, 0, 96, 0)
            qp.rotate(30.0) 
         
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.minuteColor)
        qp.save()
         
        qp.rotate(6.0 * ((time.minute() + (time.second()+time.msec()/1000.0) / 60.0)))
        qp.drawConvexPolygon(self.minuteHand)
        qp.restore()
         
         
        qp.setPen(self.minuteColor)
        for i in range(60): 
            if (i % 5) is not 0:
                qp.drawLine(92, 0, 96, 0)
            qp.rotate(6.0) 
        qp.setPen(QtCore.Qt.NoPen)
        qp.setBrush(self.secondColor)
        qp.save()
        qp.rotate(6.0*(time.second()+time.msec()/1000.0))
        qp.drawConvexPolygon(self.secondHand)
        qp.restore() 
        qp.end() 
Ejemplo n.º 55
0
    def paintEvent(self, event):
        linePen = QPen(Qt.black)
        linePen.setWidth(3)
        width = self.width() / self.scale

        def paintLineMarks(painter):
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            painter.setPen(linePen)
            painter.drawLine(0, self.ascender, width, self.ascender)
            painter.drawLine(0, 0, width, 0)
            painter.drawLine(0, self.descender, width, self.descender)
            painter.restore()

        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.fillRect(0, 0, self.width(), self.height(), Qt.white)
        if self._verticalFlip:
            baselineShift = -self.descender
            yDirection = 1
        else:
            baselineShift = self.ascender
            yDirection = -1
        painter.translate(self.padding, self.padding +
                          baselineShift * self.scale * self._lineHeight)
        # TODO: scale painter here to avoid g*scale everywhere below

        cur_width = 0
        if self._showMetrics:
            paintLineMarks(painter)
        for index, glyph in enumerate(self.glyphs):
            # line wrapping
            gWidth = glyph.width * self.scale
            doKern = index > 0 and self._showKerning and cur_width > 0
            if doKern:
                kern = self.lookupKerningValue(
                    self.glyphs[index - 1].name, glyph.name) * self.scale
            else:
                kern = 0
            if (self._wrapLines and cur_width + gWidth + kern +
                    2 * self.padding > self.width()) or glyph.unicode == 2029:
                painter.translate(-cur_width, self.ptSize * self._lineHeight)
                if self._showMetrics:
                    paintLineMarks(painter)
                cur_width = gWidth
            else:
                if doKern:
                    painter.translate(kern, 0)
                cur_width += gWidth + kern
            glyphPath = glyph.getRepresentation("defconQt.QPainterPath")
            painter.save()
            painter.scale(self.scale, yDirection * self.scale)
            if self._showMetrics:
                halfDescent = self.descender / 2
                painter.drawLine(0, 0, 0, halfDescent)
                painter.drawLine(glyph.width, 0, glyph.width, halfDescent)
            if self._selected is not None and index == self._selected:
                painter.fillRect(0, self.descender, glyph.width,
                                 self.upm, glyphSelectionColor)
            painter.fillPath(glyphPath, Qt.black)
            painter.restore()
            painter.translate(gWidth, 0)
Ejemplo n.º 56
0
Archivo: gui.py Proyecto: fqez/sandbox
	def paintEvent(self, event):
		  
		painter = QPainter(self)
		painter.setPen(self.pen)
		painter.setBrush(self.brush)
		if self.antialiased:
			painter.setRenderHint(QPainter.Antialiasing)

		angle_step = 360 / self.n_states

		painter.save()	#Save_1. Save the state of the system (push matrix)
		painter.translate(self.dist_center.x(), self.dist_center.y())		# go to the center of the render area
		painter.rotate(-180)	#to start painting from the left side of the circle (clockwise)

		#center of the circumference where through we are going to paint our states 
		x = self.dist_radius * math.cos(0)	
		y = self.dist_radius * math.sin(0)


		for h in range(self.n_states):

			rot = angle_step * h 	# each state is equidistant from the others. We paint them in circles

			painter.save()			#Save_2
			painter.rotate(rot)		#now our system is pointing to the next state to be drawn
			painter.translate(x,y)	#now our origin is in the center of the next state to be drawn

			#if the state is active, fill it green
			if self.machine.getState(h).isActive():	
				painter.setBrush(self.greenGradientBrush)			
			painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius)	#draw the new state

			#global position of transformed coordinates (before any transformation, origin at top-left corner)
			gx = painter.worldTransform().map(QPoint(0,0)).x()
			gy = painter.worldTransform().map(QPoint(0,0)).y()
			self.machine.getState(h).setPos(gx, gy)		#store the center of the state without any transformation applied

			# text transformation. Our origin is still in the center of the current state
			painter.save()			#Save_3
			painter.rotate(180)		#making the text go vertical
			painter.rotate(-rot)	#undoing the rotation made for painting the state. No the text is horizontal
			font = painter.font();
			font.setPixelSize(self.state_radius*.4);
			painter.setFont(font);
			rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
			painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName());
			painter.restore()	#Restore_3
			#end text transformation

			painter.restore()	#Restore_2
			
		painter.restore()	#Restore_1. Restore the state of the system (pop matrix)

		
		#drawing transitions. Line between states
		painter.save()	# Save_4
		pptv = QTransform()		#Define a new transformation. Needed to rotate the system along other axis than Z
		pptv.translate(0, self.height())	#We are now at the bottom-left corner of the screen
		pptv.rotate(-180, Qt.XAxis)			#Rotate along the X-axis so now we are in a typical cartesian system.
		painter.setTransform(pptv)			#Apply the transformation
		states = self.machine.getStates()
		for state in states:
			transitions = state.getTransitions()
			for transition in transitions:
				#get the center of the origin and destination states in our current system state
				orig = QPoint(state.getPos()[0], state.getPos()[1])
				end = QPoint(self.machine.getState(transition.getStateEnd()).getPos()[0], self.machine.getState(transition.getStateEnd()).getPos()[1])
				# get those coordinates without transformation
				orig2 = QPoint(painter.worldTransform().map(orig))
				end2 = QPoint(painter.worldTransform().map(end))

				#get the angle between states centers and the horizon
				angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x())

				#get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center)
				newX = self.state_radius * math.cos(angle) + orig2.x()
				newY = self.state_radius * math.sin(angle) + orig2.y()
				#now the transition starts at the border, not in the center
				orig2.setX(newX)
				orig2.setY(newY)

				#same for the destination state
				angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x())
				newX2 = self.state_radius * math.cos(angle2) + end2.x()
				newY2 = self.state_radius * math.sin(angle2) + end2.y()
				end2.setX(newX2)
				end2.setY(newY2)

				#draw the line between the origin and destination states
				painter.drawLine(orig2, end2)
				#get the start and the end of the transition untransformed
				init = QPoint(painter.worldTransform().map(orig2))
				end = QPoint(painter.worldTransform().map(end2))
				#store that info
				transition.setOrig(init.x(), init.y())
				transition.setDest(end.x(), end.y())	
				transition.setAngle(angle)
		painter.restore() #Restore_4


		#Appliying style to the transitions
		painter.setPen(QPen(QColor(Qt.gray), 3))
		for state in self.machine.getStates():
			for transition in state.getTransitions():
				#get the start and end coordinates of the transition
				i = QPoint(transition.getOrig()[0], transition.getOrig()[1])
				o = QPoint(transition.getDest()[0], transition.getDest()[1])			
				painter.drawPolyline(i, o)

				#Drawing the arrow at the end of the transition
				painter.save()	#Save_5
				painter.setPen(QPen(QColor(Qt.gray), 2))
				painter.translate(transition.getDest()[0],transition.getDest()[1])	#Go to the end of the transition
				painter.rotate(90 - transition.getAngle()*180/math.pi)		#Rotate to point in the direction of the transition

				#coordinates of the arrow (triangle)
				a = QPoint(0,0)
				b = QPoint(-5,10)
				c = QPoint(5,10)

				#coordinates of the arrow untransformed
				a1 = painter.worldTransform().map(a)
				b1 = painter.worldTransform().map(b)
				c1 = painter.worldTransform().map(c)

				#Drawin the actual arrow
				pointer = QPolygon([a,b,c])
				painter.drawPolygon(pointer)
				painter.restore()	#Restore_5

				#For the animation of the transition
				painter.save()	#Save_6
				if transition.isActive():	#if the current transition is the active one the wave function will be running, so it's updating the canvas

					painter.setPen(QPen(QColor(Qt.green), 3))
					painter.drawPolyline(i,o)
					
					painter.setPen(QPen(QColor(Qt.gray), 3))
					painter.drawPolyline(self.poly(self.pts))

					#Draw the arrow in the active state (red arrow)
					painter.setBrush(QBrush(QColor(255, 0, 0)))
					painter.setPen(QPen(QColor(Qt.red), 2))
					pointer = QPolygon([a1,b1,c1])
					painter.drawPolygon(pointer)
					
					#Ball that follows the line animation
					for x, y in self.pts:
						painter.drawEllipse(QRectF(self.pts[0][0] - 4, self.pts[0][1] - 4, 8, 8))
				painter.restore()	#Restore_6

				#Painting the text of the transition
				painter.save()	#Save_7
				pptv = QTransform()
				painter.setPen(QPen(QColor(Qt.black), 3))
				#get the middle point of the transition
				middleX = (transition.getOrig()[0] + transition.getDest()[0]) /2	
				middleY = (transition.getOrig()[1] + transition.getDest()[1]) /2
				pptv.translate(middleX, middleY)	#translate to that point
				painter.setTransform(pptv)			#apply the transformation
				font = painter.font();
				font.setPixelSize(self.state_radius*.2);
				painter.setFont(font);
				rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2)
				name = str(transition.getId())+ '. ' + transition.getName()
				painter.drawText(rect, Qt.AlignCenter, name)
				painter.restore()	#Restore_7


  
		#paint the actual canvas
		painter.setPen(self.palette().dark().color())
		painter.setBrush(Qt.NoBrush)
		painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
Ejemplo n.º 57
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setFont(headerFont)
        painter.setRenderHint(QPainter.Antialiasing)
        rect = self.rect()

        # draw the background
        painter.fillRect(rect, Qt.white)
        if self._glyph is None:
            return

        # apply the overall scale
        painter.save()
        # + translate and flip
        painter.translate(0, self.height())
        painter.scale(self._scale, -self._scale)

        # move into position
        widgetWidth = self.width()
        width = self._glyph.width * self._scale
        diff = widgetWidth - width
        xOffset = round((diff / 2) * self._inverseScale)

        yOffset = self._verticalCenterYBuffer * self._inverseScale
        yOffset -= self._descender

        painter.translate(xOffset, yOffset)

        # store the current drawing rect
        w, h = self.width(), self.height()
        w *= self._inverseScale
        h *= self._inverseScale
        self._drawingRect = (-xOffset, -yOffset, w, h)

        # gather the layers
        layerSet = self._glyph.layerSet
        if layerSet is None:
            layers = [(self._glyph, None)]
        else:
            glyphName = self._glyph.name
            layers = []
            for layerName in reversed(layerSet.layerOrder):
                layer = layerSet[layerName]
                if glyphName not in layer:
                    continue
                glyph = layer[glyphName]
                if glyph == self._glyph:
                    layerName = None
                layers.append((glyph, layerName))

        for glyph, layerName in layers:
            # draw the image
            if self.drawingAttribute("showGlyphImage", layerName):
                self.drawImage(painter, glyph, layerName)
            # draw the blues
            if layerName is None and self.drawingAttribute(
                    "showFontPostscriptBlues", None):
                self.drawBlues(painter, glyph, layerName)
            if layerName is None and self.drawingAttribute(
                    "showFontPostscriptFamilyBlues", None):
                self.drawFamilyBlues(painter, glyph, layerName)
            # draw the margins
            if self.drawingAttribute("showGlyphMargins", layerName):
                self.drawMargins(painter, glyph, layerName)
            # draw the vertical metrics
            if layerName is None and self.drawingAttribute(
                    "showFontVerticalMetrics", None):
                self.drawVerticalMetrics(painter, glyph, layerName)
            # draw the glyph
            if self.drawingAttribute("showGlyphFill", layerName) or \
                    self.drawingAttribute("showGlyphStroke", layerName):
                self.drawFillAndStroke(painter, glyph, layerName)
            if self.drawingAttribute("showGlyphOnCurvePoints", layerName) or \
                    self.drawingAttribute("showGlyphOffCurvePoints",
                                          layerName):
                self.drawPoints(painter, glyph, layerName)
            if self.drawingAttribute("showGlyphAnchors", layerName):
                self.drawAnchors(painter, glyph, layerName)
        self._currentTool.paint(painter)
        painter.restore()
Ejemplo n.º 58
0
    def paintEvent(self, event):
        selections = self.selectionModel()
        option = self.viewOptions()
        state = option.state

        background = option.palette.base()
        foreground = QPen(option.palette.color(QPalette.WindowText))
        textPen = QPen(option.palette.color(QPalette.Text))
        highlightedPen = QPen(option.palette.color(QPalette.HighlightedText))

        painter = QPainter(self.viewport())
        painter.setRenderHint(QPainter.Antialiasing)

        painter.fillRect(event.rect(), background)
        painter.setPen(foreground)

        # Viewport rectangles
        pieRect = QRect(self.margin, self.margin, self.pieSize,
                self.pieSize)
        keyPoint = QPoint(self.totalSize - self.horizontalScrollBar().value(),
                self.margin - self.verticalScrollBar().value())

        if self.validItems > 0:
            painter.save()
            painter.translate(pieRect.x() - self.horizontalScrollBar().value(),
                    pieRect.y() - self.verticalScrollBar().value())
            painter.drawEllipse(0, 0, self.pieSize, self.pieSize)
            startAngle = 0.0

            for row in range(self.model().rowCount(self.rootIndex())):

                index = self.model().index(row, 1, self.rootIndex())
                value = self.model().data(index)

                if value > 0.0:
                    angle = 360*value/self.totalValue

                    colorIndex = self.model().index(row, 0, self.rootIndex())
                    color = self.model().data(colorIndex, Qt.DecorationRole)

                    if self.currentIndex() == index:
                        painter.setBrush(QBrush(color, Qt.Dense4Pattern))
                    elif selections.isSelected(index):
                        painter.setBrush(QBrush(color, Qt.Dense3Pattern))
                    else:
                        painter.setBrush(QBrush(color))

                    painter.drawPie(0, 0, self.pieSize, self.pieSize,
                            int(startAngle*16), int(angle*16))

                    startAngle += angle

            painter.restore()

            keyNumber = 0

            for row in range(self.model().rowCount(self.rootIndex())):
                index = self.model().index(row, 1, self.rootIndex())
                value = self.model().data(index)

                if value > 0.0:
                    labelIndex = self.model().index(row, 0, self.rootIndex())

                    option = self.viewOptions()
                    option.rect = self.visualRect(labelIndex)
                    if selections.isSelected(labelIndex):
                        option.state |= QStyle.State_Selected
                    if self.currentIndex() == labelIndex:
                        option.state |= QStyle.State_HasFocus
                    self.itemDelegate().paint(painter, option, labelIndex)

                    keyNumber += 1
Ejemplo n.º 59
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        redrawRect = event.rect()
        beginRow = redrawRect.top() // self.squareSize
        endRow = redrawRect.bottom() // self.squareSize
        # XXX: do we need to maintain self._column when we have (endColumn -
        # beginColumn)?
        beginColumn = redrawRect.left() // self.squareSize
        endColumn = redrawRect.right() // self.squareSize

        gradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        gradient.setColorAt(0.0, cellHeaderBaseColor)
        gradient.setColorAt(1.0, cellHeaderLineColor)
        dirtyGradient = QLinearGradient(0, 0, 0, GlyphCellHeaderHeight)
        dirtyGradient.setColorAt(0.0, cellHeaderBaseColor.darker(125))
        dirtyGradient.setColorAt(1.0, cellHeaderLineColor.darker(125))
        markGradient = QLinearGradient(0, 0, 0, self.squareSize-GlyphCellHeaderHeight)

        for row in range(beginRow, endRow + 1):
            for column in range(beginColumn, endColumn + 1):
                key = row * self._columns + column
                if key >= len(self._glyphs): break
                glyph = self._glyphs[key]

                painter.save()
                painter.translate(column * self.squareSize, row * self.squareSize)
                painter.fillRect(0, 0, self.squareSize, self.squareSize, Qt.white)
                # prepare header colors
                brushColor = gradient
                linesColor = cellHeaderHighlightLineColor
                # mark color
                if not glyph.template:
                    if glyph.markColor is not None:
                        markColor = QColor.fromRgbF(*tuple(glyph.markColor))
                        markGradient.setColorAt(1.0, markColor)
                        markGradient.setColorAt(0.0, markColor.lighter(125))
                        painter.fillRect(0, GlyphCellHeaderHeight, self.squareSize,
                              self.squareSize - GlyphCellHeaderHeight, QBrush(markGradient))
                    if glyph.dirty:
                        brushColor = dirtyGradient
                        linesColor = cellHeaderHighlightLineColor.darker(110)

                # header gradient
                painter.fillRect(0, 0, self.squareSize, GlyphCellHeaderHeight,
                    QBrush(brushColor))
                # header lines
                painter.setPen(linesColor)
                minOffset = painter.pen().width()
                # disable antialiasing to avoid lines bleeding over background
                painter.setRenderHint(QPainter.Antialiasing, False)
                painter.drawLine(0, 0, 0, GlyphCellHeaderHeight - 1)
                painter.drawLine(self.squareSize - 2, 0, self.squareSize - 2, GlyphCellHeaderHeight -1)
                painter.setPen(QColor(170, 170, 170))
                painter.drawLine(0, GlyphCellHeaderHeight, self.squareSize, GlyphCellHeaderHeight)
                painter.setRenderHint(QPainter.Antialiasing)
                # header text
                painter.setFont(headerFont)
                painter.setPen(QColor(80, 80, 80))
                name = metrics.elidedText(glyph.name, Qt.ElideRight, self.squareSize - 2)
                painter.drawText(1, 0, self.squareSize - 2, GlyphCellHeaderHeight - minOffset,
                      Qt.TextSingleLine | Qt.AlignCenter, name)
                painter.restore()

                painter.setPen(cellGridColor)
                rightEdgeX = column * self.squareSize + self.squareSize
                bottomEdgeY = row * self.squareSize + self.squareSize
                painter.drawLine(rightEdgeX, row * self.squareSize + 1, rightEdgeX, bottomEdgeY)
                painter.drawLine(rightEdgeX, bottomEdgeY, column * self.squareSize + 1, bottomEdgeY)
                if self._currentDropIndex is not None:
                    painter.setPen(Qt.green)
                    if self._currentDropIndex == key:
                        painter.drawLine(column * self.squareSize, row * self.squareSize,
                            column * self.squareSize, bottomEdgeY)
                    # special-case the end-column
                    elif column == endColumn and self._currentDropIndex == key+1:
                        yPos = self.mapFromGlobal(QCursor.pos()).y()
                        if row == yPos // self.squareSize:
                            painter.drawLine(rightEdgeX - 1, row * self.squareSize,
                                rightEdgeX - 1, bottomEdgeY)

                # selection code
                if key in self._selection:
                    painter.setRenderHint(QPainter.Antialiasing, False)
                    painter.fillRect(column * self.squareSize + 1,
                            row * self.squareSize + 1, self.squareSize - 3,
                            self.squareSize - 3, cellSelectionColor)
                    painter.setRenderHint(QPainter.Antialiasing)

                if not glyph.template:
                    font = glyph.getParent()
                    outline = glyph.getRepresentation("defconQt.QPainterPath")
                    uPM = font.info.unitsPerEm
                    if uPM is None or not uPM > 0:
                        uPM = 1000
                    descender = font.info.descender
                    if descender is None or not descender < 0:
                        descender = -250
                    factor = (self.squareSize-GlyphCellHeaderHeight) / (uPM*(1+2*GlyphCellBufferHeight))
                    x_offset = (self.squareSize-glyph.width*factor)/2
                    # If the glyph overflows horizontally we need to adjust the scaling factor
                    if x_offset < 0:
                        factor *= 1+2*x_offset/(glyph.width*factor)
                        x_offset = 0
                    # TODO: the * 1.8 below is somewhat artificial
                    y_offset = descender*factor * 1.8
                    painter.save()
                    painter.setClipRect(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    painter.translate(column * self.squareSize + x_offset, row * self.squareSize + self.squareSize + y_offset)
                    painter.scale(factor, -factor)
                    painter.fillPath(outline, Qt.black)
                    painter.restore()
                else:
                    painter.save()
                    painter.setFont(voidFont)
                    painter.setPen(QPen(Qt.lightGray))
                    rect = QRectF(column * self.squareSize, row * self.squareSize+GlyphCellHeaderHeight,
                          self.squareSize, self.squareSize-GlyphCellHeaderHeight)
                    # TODO: need to flag template glyphs as to whether they have unicodings or not
                    if glyph.unicode is not None:
                        text = chr(glyph.unicode)
                    else:
                        text = "✌"
                    painter.drawText(rect, Qt.AlignCenter, text)
                    painter.restore()
Ejemplo n.º 60
0
    def paintEvent(self, event):
        painter = QPainter(self)
        event.accept()

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)

        if self.fLabel:
            if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_NULL:
                painter.setPen(self.fLabelGradientColor2)
                painter.setBrush(self.fLabelGradient)
                painter.drawRect(self.fLabelGradientRect)

            painter.setFont(self.fLabelFont)
            painter.setPen(self.fLabelGradientColorT[0 if self.isEnabled() else 1])
            painter.drawText(self.fLabelPos, self.fLabel)

        if self.isEnabled():
            normValue = float(self.fRealValue - self.fMinimum) / float(self.fMaximum - self.fMinimum)
            target    = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize)

            curLayer = int((self.fPixmapLayersCount - 1) * normValue)

            if self.fPixmapOrientation == self.HORIZONTAL:
                xpos = self.fPixmapBaseSize * curLayer
                ypos = 0.0
            else:
                xpos = 0.0
                ypos = self.fPixmapBaseSize * curLayer

            source = QRectF(xpos, ypos, self.fPixmapBaseSize, self.fPixmapBaseSize)
            painter.drawPixmap(target, self.fPixmap, source)

            # Custom knobs (Dry/Wet and Volume)
            if self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_WET, self.CUSTOM_PAINT_MODE_CARLA_VOL):
                # knob color
                colorGreen = QColor(0x5D, 0xE7, 0x3D).lighter(100 + self.fHoverStep*6)
                colorBlue  = QColor(0x3E, 0xB8, 0xBE).lighter(100 + self.fHoverStep*6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue  = (0.375 + 0.75*normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 216*16
                spanAngle  = -252*16*normValue

                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_WET:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    gradient = QConicalGradient(15.5, 15.5, -45)
                    gradient.setColorAt(0.0,   colorBlue)
                    gradient.setColorAt(0.125, colorBlue)
                    gradient.setColorAt(0.625, colorGreen)
                    gradient.setColorAt(0.75,  colorGreen)
                    gradient.setColorAt(0.76,  colorGreen)
                    gradient.setColorAt(1.0,   colorGreen)
                    painter.setBrush(gradient)
                    painter.setPen(QPen(gradient, 3))

                else:
                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 0))
                    painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                    painter.setBrush(colorBlue)
                    painter.setPen(QPen(colorBlue, 3))

                painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (L and R)
            elif self.fCustomPaintMode in (self.CUSTOM_PAINT_MODE_CARLA_L, self.CUSTOM_PAINT_MODE_CARLA_R):
                # knob color
                color = QColor(0xAD, 0xD5, 0x48).lighter(100 + self.fHoverStep*6)

                # draw small circle
                ballRect = QRectF(7.0, 8.0, 11.0, 12.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                #painter.drawRect(ballRect)
                tmpValue  = (0.375 + 0.75*normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.0, 2.0))

                # draw arc
                if self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_CARLA_L:
                    startAngle = 216*16
                    spanAngle  = -252.0*16*normValue
                else:
                    startAngle = 324.0*16
                    spanAngle  = 252.0*16*(1.0-normValue)

                painter.setPen(QPen(color, 2))
                painter.drawArc(3.5, 4.5, 22.0, 22.0, startAngle, spanAngle)

            # Custom knobs (Color)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_COLOR:
                # knob color
                color = self.fCustomPaintColor.lighter(100 + self.fHoverStep*6)

                # draw small circle
                ballRect = QRectF(8.0, 8.0, 15.0, 15.0)
                ballPath = QPainterPath()
                ballPath.addEllipse(ballRect)
                tmpValue  = (0.375 + 0.75*normValue)
                ballValue = tmpValue - floor(tmpValue)
                ballPoint = ballPath.pointAtPercent(ballValue)

                # draw arc
                startAngle = 216*16
                spanAngle  = -252*16*normValue

                painter.setBrush(color)
                painter.setPen(QPen(color, 0))
                painter.drawEllipse(QRectF(ballPoint.x(), ballPoint.y(), 2.2, 2.2))

                painter.setBrush(color)
                painter.setPen(QPen(color, 3))
                painter.drawArc(4.0, 4.0, 26.0, 26.0, startAngle, spanAngle)

            # Custom knobs (Zita)
            elif self.fCustomPaintMode == self.CUSTOM_PAINT_MODE_ZITA:
                a = normValue * pi * 1.5 - 2.35
                r = 10.0
                x = 10.5
                y = 10.5
                x += r * sin(a)
                y -= r * cos(a)
                painter.setBrush(Qt.black)
                painter.setPen(QPen(Qt.black, 2))
                painter.drawLine(QPointF(11.0, 11.0), QPointF(x, y))

            # Custom knobs
            else:
                painter.restore()
                return

            if self.HOVER_MIN < self.fHoverStep < self.HOVER_MAX:
                self.fHoverStep += 1 if self.fIsHovered else -1
                QTimer.singleShot(20, self.update)

        else: # isEnabled()
            target = QRectF(0.0, 0.0, self.fPixmapBaseSize, self.fPixmapBaseSize)
            painter.drawPixmap(target, self.fPixmap, target)

        painter.restore()