示例#1
0
	def paintEvent(self, e):
		qp = QPainter()
		qp.begin(self)
		qp.setBrush(QColor(200, 0, 0))
		qp.drawEllipse(0,0,50,50)
		qp.setPen(QColor(0, 0, 0))
		qp.drawText(e.rect(), Qt.AlignVCenter,str(self.node.heuristicValue))
示例#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()
示例#3
0
文件: lineedit.py 项目: gpa14/enki
    def paintEvent(self, event):
        """QLineEdit.paintEvent implementation.
        Draws prompt
        """
        QLineEdit.paintEvent(self, event)

        if self._promptText and not self.text() and self.isEnabled():
            option = QStyleOptionFrameV3()
            self.initStyleOption(option)

            left, top, right, bottom = self.getTextMargins()

            va = self.style().visualAlignment(self.layoutDirection(), self.alignment())
            rect = (
                self.style()
                .subElementRect(QStyle.SE_LineEditContents, option, self)
                .adjusted(2, 0, 0, 0)
                .adjusted(left, top, -right, -bottom)
            )
            fm = QFontMetrics(self.font())
            text = fm.elidedText(self._promptText, Qt.ElideRight, rect.width())
            painter = QPainter(self)

            painter.setPen(self.palette().color(QPalette.Disabled, QPalette.Text))
            painter.drawText(rect, va, text)
示例#4
0
 def paintEvent(self, evt):
     """
     Protected method handling a paint event.
     
     @param evt reference to the paint event (QPaintEvent)
     """
     super(E5LineEdit, self).paintEvent(evt)
     
     if qVersion() < "4.7.0":
         if not self.text() and \
            self.__inactiveText and \
            not self.hasFocus():
             panel = QStyleOptionFrame()
             self.initStyleOption(panel)
             textRect = self.style().subElementRect(
                 QStyle.SE_LineEditContents, panel, self)
             textRect.adjust(2, 0, 0, 0)
             left = self.textMargin(self.LeftSide)
             right = self.textMargin(self.RightSide)
             textRect.adjust(left, 0, -right, 0)
             painter = QPainter(self)
             painter.setPen(self.palette().brush(
                 QPalette.Disabled, QPalette.Text).color())
             painter.drawText(
                 textRect, Qt.AlignLeft | Qt.AlignVCenter,
                 self.__inactiveText)
示例#5
0
 def paintEvent(self, event):    
     painter = QPainter(self)
     self.font.setPixelSize(self.height() - self.padding * 2)
     painter.setPen(QtGui.QColor(19, 125, 17, 255))
     painter.setFont(self.font)
     painter.drawText(0, 0, self.width(), self.height(), QtCore.Qt.AlignRight, self.info_string)
     painter.end()
示例#6
0
    def paint_detail_view(self, painter: QPainter) -> None:
        self.thumbnail_rect = QRect(0, 0, self.tile_rect.height(), self.tile_rect.height())

        self.paint_thumbnail(painter)

        lst = ([self.fileinfo.basename(), bytefmt.humanize(self.fileinfo.size())] +
               list(self.make_text()))

        text_option = QTextOption(Qt.AlignLeft | Qt.AlignVCenter)
        text_option.setWrapMode(QTextOption.NoWrap)

        total_width = self.tile_rect.width() - self.thumbnail_rect.width() - 8

        widths = [60, 10, 10, 10, 10, 10]
        x = self.thumbnail_rect.width() + 4
        for idx, text in enumerate(lst[:-1]):
            if idx != 0:
                text_option.setAlignment(Qt.AlignRight | Qt.AlignVCenter)

            width = total_width * (widths[idx] / 100)
            painter.drawText(QRectF(x, 0,
                                    width, self.tile_rect.height()),
                             text,
                             text_option)
            x += width
示例#7
0
    def image(cls, **kwargs):
        """
        Returns an image suitable for the palette.
        :rtype: QPixmap
        """
        # INITIALIZATION
        pixmap = QPixmap(kwargs['w'], kwargs['h'])
        pixmap.fill(Qt.transparent)
        painter = QPainter(pixmap)
        # INITIALIZE EDGE LINE
        pp1 = QPointF(((kwargs['w'] - 52) / 2), kwargs['h'] / 2)
        pp2 = QPointF(((kwargs['w'] - 52) / 2) + 52 - 2, kwargs['h'] / 2)
        line = QLineF(pp1, pp2)
        # CALCULATE HEAD COORDINATES
        angle = radians(line.angle())
        p1 = QPointF(line.p2().x() + 2, line.p2().y())
        p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8)
        p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8)
        # INITIALIZE EDGE HEAD
        head = QPolygonF([p1, p2, p3])
        # DRAW THE POLYGON
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        painter.drawLine(line)
        # DRAW HEAD
        painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        painter.setBrush(QColor(0, 0, 0))
        painter.drawPolygon(head)
        # DRAW THE TEXT ON TOP OF THE EDGE
        space = 2 if Platform.identify() is Platform.Darwin else 0
        painter.setFont(Font('Arial', 9, Font.Light))
        painter.drawText(pp1.x() + space, (kwargs['h'] / 2) - 4, 'instanceOf')

        return pixmap
示例#8
0
    def paintEvent(self, event):
        logger.debug("paintEvent: {0} - {1}".format(self, event.rect()))
        qp = QPainter()
        qp.begin(self)
        
        width = self.size().width() - 1 
        height = self.size().height() - 1 

        #draw border
        qp.setPen(self.border_color)
        qp.drawLine(0, 0, width, 0)
        qp.drawLine(0, 0, 0, height)
        qp.drawLine(width, 0, width, height)
        qp.drawLine(0, height, width, height)

        #draw bar
        width  -= 2
        height -= 2
        value = orig_value = self.data_source()
        value = min(self.max_range, value)
        value = max(self.min_range, value)
        qp.setPen(self.bar_color)
        qp.setBrush(self.bar_color)
        if self.orientation == 'horizontal':
            qp.drawRect(1, 1,
                        width / self.max_range * value, height)
        else:
            qp.drawRect(1, height - (height / self.max_range * value), width, height)
        qp.setPen(self.border_color)
        qp.drawText(event.rect(), Qt.AlignCenter, str(orig_value))
        qp.end()
        logger.debug("paintEvent End: {0}".format(self))
示例#9
0
文件: textedit.py 项目: hovo1990/GROM
    def lineNumberAreaPaintEvent(self, event):  # When text zoomed line number not zoomed
        """Painting line number area"""
        painter = QPainter(self.lineNumberArea)
        painter.fillRect(event.rect(), Qt.lightGray)

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        # font_height = self.fontMetrics().height()




        while block.isValid() and top <= event.rect().bottom():

            if block.isVisible() and bottom >= event.rect().top():
                font_original = self.document().defaultFont()
                size = font_original.pointSize()
                font = painter.font()
                font.setPointSize(size)
                painter.setFont(font)

                number = str(blockNumber + 1)
                painter.setPen(Qt.black)
                painter.drawText(0, top, self.lineNumberArea.width(),
                                 self.fontMetrics().height(),
                                 Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            blockNumber += 1
示例#10
0
    def paintEvent(self, event):
        """This method draws a left sidebar

        :param event: QEvent
        """

        painter = QPainter(self)
        painter.fillRect(event.rect(), Qt.white)
        width = self.width() - 8
        height = self.editor.fontMetrics().height()
        font = self.editor.font()
        font_bold = self.editor.font()
        font_bold.setBold(True)
        painter.setFont(font)
        pen = QPen(Qt.gray)
        painter.setPen(QPen(QColor("#e9e9e9")))
        painter.drawLine(width + 7, 0, width + 7, event.rect().height())
        painter.setPen(pen)
        current_line = self.editor.textCursor().blockNumber()

        for top, line, block in self.editor.visible_blocks:
            if current_line == line:
                painter.setFont(font_bold)
            else:
                painter.setFont(font)
            painter.drawText(5, top, width, height,
                             Qt.AlignRight, str(line + 1))
示例#11
0
 def drawPixmapFor3d(self):
     self.pixmap3d = QPixmap(self.itemWidth, self.itemHeight)
     self.pixmap3d.fill(Qt.transparent)
     painter = QPainter()
     painter.begin(self.pixmap3d)
     painter.setRenderHint(QPainter.Antialiasing)
     pen = QPen()
     pen.setWidth(2)
     painter.setPen(pen)
     painter.setBrush(QBrush(QColor(220, 220, 220)))
     top = [QPoint(5, 10),
            QPoint(self.itemWidth - 10, 10),
            QPoint(self.itemWidth - 5, 5),
            QPoint(10, 5),
            QPoint(5, 10)]
     painter.drawConvexPolygon(*top)
     left = [QPoint(self.itemWidth - 10, 10),
             QPoint(self.itemWidth - 10, self.itemHeight - 5),
             QPoint(self.itemWidth - 5, self.itemHeight - 10),
             QPoint(self.itemWidth - 5, 5),
             QPoint(self.itemWidth - 10, 10)]
     painter.drawConvexPolygon(*left)
     painter.setBrush(QBrush())
     painter.drawRect(QRect(5, 10, self.itemWidth - 15, self.itemHeight - 15))
     painter.drawText(QRect(5, 10, self.itemWidth - 15, self.itemHeight - 15), Qt.AlignCenter, '3D')
     painter.end()
	def drawROIBoxes(self, image):
		#print(self.frame_data)
		if not isinstance(self.frame_data, pd.DataFrame) or len(self.frame_data) == 0 \
		or not self.label_type in self.frame_data:
			return 
		 			
		self.img_h_ratio = image.height()/self.image_height;
		self.img_w_ratio = image.width()/self.image_width;

		painter = QPainter()
		painter.begin(image)
		for row_id, row_data in self.frame_data.iterrows():
			x = row_data['coord_x']*self.img_h_ratio
			y = row_data['coord_y']*self.img_w_ratio
			#check if the coordinates are nan
			if not (x == x) or  not (y == y): 
				continue

			x = int(x)
			y = int(y)
			c = self.wlabC[int(row_data[self.label_type])]
			
			painter.setPen(c)
			painter.setFont(QFont('Decorative', 10))
			
			painter.drawText(x, y, str(int(row_data[self.worm_index_type])))

			bb = row_data['roi_size']*self.img_w_ratio
			painter.drawRect(x-bb/2, y-bb/2, bb, bb);
		painter.end()
    def __redrawColorLabel(self, label, lc, uc):
        pixmap = QPixmap(101, 26)
        painter = QPainter(pixmap)
        lowerColorRect = QRect(0, 0, 50, 25)
        upperColorRect = QRect(50, 0, 50, 25)

        font = QFont("Times", 11)
        painter.setFont(font)

        painter.setPen(Qt.black)
        painter.setBrush(lc)
        painter.drawRect(lowerColorRect)
        lgray = lc.red() + lc.green() + lc.blue()
        painter.setPen(self.invert(lc))
        painter.drawText(lowerColorRect.translated(8, 2), 0, str(lgray))

        painter.setPen(Qt.black)
        painter.setBrush(uc)
        painter.drawRect(upperColorRect)
        ugray = uc.red() + uc.green() + uc.blue()
        painter.setPen(self.invert(uc))
        painter.drawText(upperColorRect.translated(8, 2), 0, str(ugray))
        del painter

        label.setPixmap(pixmap)
示例#14
0
    def paintEvent(self, event):
        super(TetrixBoard, self).paintEvent(event)

        painter = QPainter(self)
        rect = self.contentsRect()

        if self.isPaused:
            painter.drawText(rect, Qt.AlignCenter, "Pause")
            return

        boardTop = rect.bottom() - TetrixBoard.BoardHeight * self.squareHeight()

        for i in range(TetrixBoard.BoardHeight):
            for j in range(TetrixBoard.BoardWidth):
                shape = self.shapeAt(j, TetrixBoard.BoardHeight - i - 1)
                if shape != NoShape:
                    self.drawSquare(painter,
                            rect.left() + j * self.squareWidth(),
                            boardTop + i * self.squareHeight(), shape)

        if self.curPiece.shape() != NoShape:
            for i in range(4):
                x = self.curX + self.curPiece.x(i)
                y = self.curY - self.curPiece.y(i)
                self.drawSquare(painter, rect.left() + x * self.squareWidth(),
                        boardTop + (TetrixBoard.BoardHeight - y - 1) * self.squareHeight(),
                        self.curPiece.shape())
示例#15
0
    def paintEvent(self, event):
        """QWidget.paintEvent() implementation
        """
        painter = QPainter(self)
        painter.fillRect(event.rect(), self.palette().color(QPalette.Window))
        painter.setPen(Qt.black)

        block = self._qpart.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = int(self._qpart.blockBoundingGeometry(block).translated(self._qpart.contentOffset()).top())
        bottom = top + int(self._qpart.blockBoundingRect(block).height())
        singleBlockHeight = self._qpart.cursorRect().height()

        boundingRect = self._qpart.blockBoundingRect(block)
        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = str(blockNumber + 1)
                painter.drawText(0, top, self.__width - self._RIGHT_MARGIN - self._LEFT_MARGIN, self._qpart.fontMetrics().height(),
                                 Qt.AlignRight, number)
                if boundingRect.height() >= singleBlockHeight * 2:  # wrapped block
                    painter.fillRect(1, top + singleBlockHeight,
                                     self.__width - 2, boundingRect.height() - singleBlockHeight - 2,
                                     Qt.darkGreen)

            block = block.next()
            boundingRect = self._qpart.blockBoundingRect(block)
            top = bottom
            bottom = top + int(boundingRect.height())
            blockNumber += 1
示例#16
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))
示例#17
0
    def draw_indicator(indicator: int):
        pixmap = QPixmap(24, 24)

        painter = QPainter(pixmap)
        w, h = pixmap.width(), pixmap.height()

        painter.fillRect(0, 0, w, h, QBrush((QColor(0, 0, 200, 255))))

        pen = QPen(QColor("white"))
        pen.setWidth(2)
        painter.setPen(pen)

        font = util.get_monospace_font()
        font.setBold(True)
        font.setPixelSize(16)
        painter.setFont(font)

        f = QFontMetrics(painter.font())
        indicator_str = str(indicator) if indicator < 10 else "+"

        fw = f.width(indicator_str)
        fh = f.height()
        painter.drawText(math.ceil(w / 2 - fw / 2), math.ceil(h / 2 + fh / 4), indicator_str)

        painter.end()
        return QIcon(pixmap)
示例#18
0
    def lineNumberAreaPaintEvent(self, event):
        painter = QPainter(self.lineNumbers)
        painter.fillRect(event.rect(), QColor(230, 230, 230))
        d = event.rect().topRight()
        a = event.rect().bottomRight()
        painter.setPen(Qt.darkGray)
        painter.drawLine(d.x(), d.y(), a.x(), a.y())
        painter.setPen(QColor(100, 100, 100))
        painter.setFont(self.font())

        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber()
        top = int(
            self.blockBoundingGeometry(block).translated(
                self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = str(blockNumber + 1)
                painter.drawText(4, top, self.lineNumbers.width() - 8,
                                 self.fontMetrics().height(), Qt.AlignRight,
                                 number)
            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            blockNumber += 1
示例#19
0
    def numPaintEvent(self, event):
        """
        Paint the editor
        :param event:
        :return:
        """
        painter = QPainter(self.numArea)
        painter.fillRect(event.rect(), Qt.lightGray)

        block = self.firstVisibleBlock()
        block_num = block.blockNumber()
        top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
        bottom = top + self.blockBoundingRect(block).height()

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = block_num + 1
                painter.setPen(Qt.darkRed)
                painter.drawText(0, top, self.numArea.width(), self.fontMetrics().height(),
                                 Qt.AlignRight, ' %s ' % str(number))  # padding

            block = block.next()
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
            block_num += 1
示例#20
0
    def createImage(self, transform):
        scaledRect = transform.mapRect(QRect(0, 0, 25, 25))
        image = QImage(scaledRect.width(), scaledRect.height(),
                QImage.Format_ARGB32_Premultiplied)
        image.fill(0)
        painter = QPainter(image)
        painter.scale(transform.m11(), transform.m22())
        painter.setRenderHints(QPainter.TextAntialiasing | QPainter.Antialiasing | QPainter.SmoothPixmapTransform)
        painter.setPen(Qt.NoPen)

        if Colors.useEightBitPalette:
            painter.setBrush(QColor(102, 175, 54))
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255))
            painter.drawText(10, 15, self.letter)
        else:
            brush = QLinearGradient(0, 0, 0, 25)
            brush.setSpread(QLinearGradient.PadSpread)
            brush.setColorAt(0.0, QColor(102, 175, 54, 200))
            brush.setColorAt(1.0, QColor(102, 175, 54, 60))
            painter.setBrush(brush)
            painter.drawEllipse(0, 0, 25, 25)
            painter.setFont(Colors.tickerFont())
            painter.setPen(QColor(255, 255, 255, 255))
            painter.drawText(10, 15, self.letter)

        return image
示例#21
0
 def paintEvent(self, event):
     super().paintEvent(event)
     painter = QPainter(self)
     width = self.width() - self.RIGHT_MARGIN - self.LEFT_MARGIN
     height = self._neditor.fontMetrics().height()
     font = self._neditor.font()
     font_bold = self._neditor.font()
     font_bold.setBold(True)
     pen = QPen(self._color_unselected)
     painter.setPen(pen)
     painter.setFont(font)
     sel_start, sel_end = self._neditor.selection_range()
     has_sel = sel_start != sel_end
     current_line, _ = self._neditor.cursor_position
     # Draw visible blocks
     for top, line, block in self._neditor.visible_blocks:
         # Set bold to current line and selected lines
         if ((has_sel and sel_start <= line <= sel_end) or
                 (not has_sel and current_line == line)):
             painter.fillRect(
                 QRect(0, top, self.width(), height), self._color_selected)
         else:
             painter.setPen(pen)
             painter.setFont(font)
         painter.drawText(self.LEFT_MARGIN, top, width, height,
                          Qt.AlignRight, str(line + 1))
    def _redrawColorLabel(self, labelIndex, lc, uc, lValue, uValue) :
        if labelIndex >= len(self.__colorLabels) :
            return
        label = self.__colorLabels[labelIndex]
        pixmap = QPixmap(101, 26)
        painter = QPainter(pixmap)
        lowerColorRect = QRect(0, 0, 50, 25)
        upperColorRect = QRect(50, 0, 50, 25)

        font = QFont('Times', 11)
        painter.setFont(font)

        painter.setPen(Qt.black);
        painter.setBrush(lc);
        painter.drawRect(lowerColorRect);
        painter.setPen(self.invert(lc));
        painter.drawText(lowerColorRect.translated(8, 2), 0, str(lValue));

        painter.setPen(Qt.black);
        painter.setBrush(uc);
        painter.drawRect(upperColorRect);
        painter.setPen(self.invert(uc));
        painter.drawText(upperColorRect.translated(8, 2), 0, str(uValue));
        del painter

        label.setPixmap(pixmap);
示例#23
0
    def paintEvent(self, event):
        painter = QPainter(self)
        rect = event.rect()
        rect.setWidth(self.__width())
        painter.fillRect(rect, self._background_color)
        painter.setPen(Qt.white)

        font = self._console_widget.font()
        painter.setFont(font)

        width = self.__width()
        height = self._console_widget.fontMetrics().height()
        for top, line, block in self._console_widget.visible_blocks:
            data = self.user_data(block)
            prompt = data.get("prompt")
            text = self.PROMPT_IN
            color = Qt.white
            if prompt is not None:
                if prompt == self.PROMPT_INCOMPLETE:
                    text = self.PROMPT_INCOMPLETE
                    color = Qt.yellow
                else:
                    text = self.PROMPT_OUT
                    color = Qt.gray

            painter.setPen(color)
            painter.drawText(0, top, width, height,
                             Qt.AlignCenter, text)
示例#24
0
	def paintEvent(self, event):
		if not globalSettings.lineNumbersEnabled:
			return QWidget.paintEvent(self, event)
		painter = QPainter(self)
		painter.fillRect(event.rect(), colorValues['lineNumberArea'])
		painter.setPen(colorValues['lineNumberAreaText'])
		cursor = self.editor.cursorForPosition(QPoint(0, 0))
		atEnd = False
		fontHeight = self.fontMetrics().height()
		height = self.editor.height()
		if globalSettings.relativeLineNumbers:
			relativeTo = self.editor.textCursor().blockNumber()
		else:
			relativeTo = -1
		while not atEnd:
			rect = self.editor.cursorRect(cursor)
			if rect.top() >= height:
				break
			number = str(cursor.blockNumber() - relativeTo).replace('-', '−')
			painter.drawText(0, rect.top(), self.width() - 2,
			                 fontHeight, Qt.AlignRight, number)
			cursor.movePosition(QTextCursor.EndOfBlock)
			atEnd = cursor.atEnd()
			if not atEnd:
				cursor.movePosition(QTextCursor.NextBlock)
示例#25
0
文件: gauge.py 项目: estan/gauges
 def paintEvent(self, event):
     painter = QPainter(self)
     font = painter.font()
     font.setPointSize(self.width() / 6.0)
     painter.setFont(font)
     painter.drawText(self.rect(), Qt.AlignCenter | Qt.AlignVCenter, str(self.value()))
     QDial.paintEvent(self, event)
示例#26
0
    def __init__(self, text, parent):
        super(DragLabel, self).__init__(parent)

        metric = QFontMetrics(self.font())
        size = metric.size(Qt.TextSingleLine, text)

        image = QImage(size.width() + 12, size.height() + 12, QImage.Format_ARGB32_Premultiplied)
        image.fill(qRgba(0, 0, 0, 0))

        font = QFont()
        font.setStyleStrategy(QFont.ForceOutline)

        painter = QPainter()
        painter.begin(image)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(Qt.white)
        painter.drawRoundedRect(QRectF(0.5, 0.5, image.width() - 1, image.height() - 1), 25, 25, Qt.RelativeSize)

        painter.setFont(font)
        painter.setBrush(Qt.black)
        painter.drawText(QRect(QPoint(6, 6), size), Qt.AlignCenter, text)
        painter.end()

        self.setPixmap(QPixmap.fromImage(image))
        self.labelText = text
示例#27
0
 def paintEvent(self, ev) -> None:
     if self._text is not None:
         painter = QPainter(self)
         font = painter.font()
         fm = QFontMetrics(font)
         width = fm.width(self._text)
         painter.drawText(self.width() // 2 - width // 2, 14, self._text)
         painter.end()
示例#28
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.setPen(Qt.black)
     painter.translate(20, self.length-1)
     painter.rotate(-90)
     if self.text:
         painter.drawText(0, 0, self.text)
     painter.end()
示例#29
0
	def paintEvent(self, e):
		painter = QPainter()
		painter.begin(self)
		painter.setPen(self.color)
		
		painter.drawText(e.rect(), Qt.AlignLeft, self.text)
		
		painter.end()
示例#30
0
    def seed_img(self, is_seed = True):

        if is_seed:
            try:
                cseed = self.get_seed()
            except UserCancelled:
                return
            except InvalidPassword as e:
                self.d.show_error(str(e))
                return
            if not cseed:
                self.d.show_message(_("This wallet has no seed"))
                return
            txt = cseed.upper()
        else:
            txt = self.txt.upper()

        img = QImage(self.SIZE[0], self.SIZE[1], QImage.Format_Mono)
        bitmap = QBitmap.fromImage(img, Qt.MonoOnly)
        bitmap.fill(Qt.white)
        painter = QPainter()
        painter.begin(bitmap)
        QFontDatabase.addApplicationFont(os.path.join(os.path.dirname(__file__), 'SourceSansPro-Bold.otf') )
        if len(txt) < 102 :
            fontsize = 15
            linespace = 15
            max_letters = 17
            max_lines = 6
            max_words = 3
        else:
            fontsize = 12
            linespace = 10
            max_letters = 21
            max_lines = 9
            max_words = int(max_letters/4)

        font = QFont('Source Sans Pro', fontsize, QFont.Bold)
        font.setLetterSpacing(QFont.PercentageSpacing, 100)
        font.setPixelSize(fontsize)
        painter.setFont(font)
        seed_array = txt.split(' ')

        for n in range(max_lines):
            nwords = max_words
            temp_seed = seed_array[:nwords]
            while len(' '.join(map(str, temp_seed))) > max_letters:
               nwords = nwords - 1
               temp_seed = seed_array[:nwords]
            painter.drawText(QRect(0, linespace*n , self.SIZE[0], self.SIZE[1]), Qt.AlignHCenter, ' '.join(map(str, temp_seed)))
            del seed_array[:nwords]

        painter.end()
        img = bitmap.toImage()
        if (self.rawnoise == False):
            self.make_rawnoise()

        self.make_cypherseed(img, self.rawnoise, False, is_seed)
        return img
示例#31
0
    def paintEvent(self, event):

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

        if self.mode_edition == 0:
            n = len(self.poly)
            if n > 0:
                x, y = self.poly[-1]
                painter.setPen(self.style_base)
                painter.drawLine(QPoint(x, y),
                                 QPoint(self.x_mouse, self.y_mouse))

                x0, y0 = self.poly[0]
                painter.drawEllipse(QPoint(x0, y0), self.distance_min,
                                    self.distance_min)

            if n > 1:
                for i in range(n - 1):
                    painter.setPen(self.style_base)
                    painter.drawLine(self.poly[i][0], self.poly[i][1],
                                     self.poly[(i + 1)][0],
                                     self.poly[(i + 1)][1])

        if self.mode_edition != 0:
            points = self.map.Qpolygone

            Qpoly = QPolygon(points)
            painter.setPen(self.style_gris)
            painter.drawPolygon(Qpoly)
            painter.setPen(self.style_base)

            painter.setPen(self.style_jaune)
            painter.drawEllipse(self.map.startPoint, 2 * self.distance_min,
                                2 * self.distance_min)

            painter.setPen(self.style_vert)
            painter.drawEllipse(self.map.finishPoint, 2 * self.distance_min,
                                2 * self.distance_min)

        if self.mode_edition == 0:
            painter.setPen(self.style_base)
            painter.drawText(50, 100, ' - Tracez un polygone - ')
        elif self.mode_edition == 1:
            painter.setPen(self.style_jaune)
            painter.drawText(50, 100, ' - Placez un point de départ - ')
        elif self.mode_edition == 2:
            painter.setPen(self.style_vert)
            painter.drawText(50, 100, " - Placez un point d'arrivée - ")
示例#32
0
    def paintEvent(self, event):

        node_width = 10
        qp = QPainter(self)
        qp.setRenderHint(QPainter.Antialiasing, True)
        # edges = [(self.qt_coords[i[0]], self.qt_coords[i[1]]) for i in self.adj]
        edges = [[(self.g.nodes[e[0]]['x'], self.g.nodes[e[0]]['y']),
                  (self.g.nodes[e[1]]['x'], self.g.nodes[e[1]]['y'])]
                 for e in self.g.edges]

        # dumper([str(i) for i in edges])

        qp.setPen(QPen(Qt.green, 2, Qt.SolidLine))
        [
            self.draw_arrow(qp, e[0][0], e[0][1], e[1][0], e[1][1],
                            (node_width / 2) + 5) for e in edges
        ]
        # [qp.drawLine(e[0][0], e[0][1], e[1][0], e[1][1]) for e in edges]

        # qp.setPen(QPen(Qt.black, 3, Qt.SolidLine))

        # debug overlap

        qp.setPen(QPen(Qt.black, 3, Qt.SolidLine))
        for v in g.nodes:

            # if v == self.main_v:
            #     qp.setPen(QPen(Qt.blue, 3, Qt.SolidLine))

            # if v == self.cmpr_v:
            #     qp.setPen(QPen(Qt.blue, 3, Qt.SolidLine))

            # else:
            qp.drawRect(g.nodes[v]['x'] - (g.nodes[v]['width'] / 2),
                        g.nodes[v]['y'] - (g.nodes[v]['height'] / 2),
                        g.nodes[v]['width'], g.nodes[v]['height'])

        qp.setFont(QFont('Decorative', 10))
        [
            qp.drawText(g.nodes[v]['x'], g.nodes[v]['y'], str(v))
            for v in self.g.nodes
        ]
示例#33
0
文件: buffer.py 项目: yssource/obvz
    def paintEvent(self, event):
        # dumper(['start painting'])
        node_width = 10
        qp = QPainter(self)
        edges = [(self.qt_coords[i[0]], self.qt_coords[i[1]])
                 for i in self.adj]
        # dumper([str(i) for i in edges])

        qp.setPen(QPen(Qt.green, 2, Qt.SolidLine))

        # [qp.drawLine(e[0][0], e[0][1], e[1][0], e[1][1]) for e in edges]
        [
            self.draw_arrow(qp, e[0][0], e[0][1], e[1][0], e[1][1],
                            (node_width / 2) + 5) for e in edges
        ]

        qp.setPen(QColor(168, 34, 3))
        # qp.setPen(Qt.green)
        qp.setFont(QFont('Decorative', 10))
        [
            qp.drawText(t[0][0] + node_width, t[0][1], t[1])
            for t in zip(self.qt_coords, self.node_names)
        ]
        # dumper(['done painting'])

        qp.setPen(QPen(Qt.black, 3, Qt.SolidLine))
        # qp.setBrush(QBrush(Qt.green, Qt.SolidPattern))

        dumper(['painting nodes'])

        for i in zip(self.qt_coords, self.node_names):
            if self.emacs_var_dict['cur_node'] == i[1]:
                qp.setPen(QPen(Qt.black, 4, Qt.SolidLine))
                qp.drawEllipse(i[0][0] - (node_width / 2),
                               i[0][1] - (node_width / 2), node_width,
                               node_width)
                qp.setPen(QPen(Qt.black, 3, Qt.SolidLine))

            else:
                qp.drawEllipse(i[0][0] - (node_width / 2),
                               i[0][1] - (node_width / 2), node_width,
                               node_width)
示例#34
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        width = self.width() - 8
        height = 36

        previous = 0
        for partition in self.partitions:
            color = self.color_list[self.partitions.index(partition)]
            percent = self.__percentage(width, int(partition.getSize()),
                                        self.max_capacity)
            print(percent, width)
            painter.setPen(color)
            painter.setBrush(color)
            painter.drawRect(QRect(5 + previous, 5, percent, 34))
            previous += percent

        #Çerçeve
        painter.setPen(QColor(Qt.black))
        painter.setBrush(Qt.NoBrush)
        painter.drawRoundedRect(QRect(4, 4, width, height), 4, 4)
        #Parlaklık
        painter.drawPixmap(QRect(6, 6, width - 4, height - 4),
                           QPixmap(":/images/partitionwidget/light.svg"))

        #kareler
        for partition in self.partitions:
            counter = self.partitions.index(partition)
            painter.setPen(Qt.black)
            painter.setBrush(self.color_list[counter])
            painter.drawRoundedRect(QRect(4 + (counter * 150), 50, 12, 12), 2,
                                    2)
            painter.drawText(QRect(24 + (counter * 150), 50, 30, 12),
                             Qt.AlignVCenter | Qt.TextDontClip, partition.path)
            painter.setPen(Qt.darkGray)
            if partition.fileSystem:
                painter.drawText(
                    QRect(24 + (counter * 150), 64, 40,
                          12), Qt.AlignVCenter | Qt.TextDontClip,
                    "{}  {}".format(mbToGB(partition.getSize()),
                                    partition.fileSystem.type))

            else:
                painter.drawText(
                    QRect(24 + (counter * 150), 64, 40, 12),
                    Qt.AlignVCenter | Qt.TextDontClip,
                    self.tr("{}  Bilinmiyor").format(
                        mbToGB(partition.getSize())))
示例#35
0
 def drawChart(self, qp: QtGui.QPainter):
     qp.setPen(QtGui.QPen(self.textColor))
     qp.drawText(3, 15, self.name)
     qp.setPen(QtGui.QPen(QtGui.QColor("lightgray")))
     qp.drawLine(self.leftMargin, 20, self.leftMargin,
                 20 + self.chartHeight + 5)
     qp.drawLine(self.leftMargin - 5, 20 + self.chartHeight,
                 self.leftMargin + self.chartWidth, 20 + self.chartHeight)
     minAngle = -180
     maxAngle = 180
     span = maxAngle - minAngle
     for i in range(minAngle, maxAngle, 90):
         y = 30 + round((i - minAngle) / span * (self.chartHeight - 10))
         if i != minAngle and i != maxAngle:
             qp.setPen(QtGui.QPen(self.textColor))
             qp.drawText(3, y + 3, str(-i) + "°")
         qp.setPen(QtGui.QPen(QtGui.QColor("lightgray")))
         qp.drawLine(self.leftMargin - 5, y,
                     self.leftMargin + self.chartWidth, y)
     qp.setPen(self.textColor)
     qp.drawText(3, 35, str(-minAngle) + "°")
     qp.drawText(3, self.chartHeight + 20, str(-maxAngle) + "°")
示例#36
0
    def paintEvent(self, e):
        painter = QPainter(self)

        text_width, text_height = PaintTextbox(painter,self.textbox_x,self.textbox_y,self.textbox_text,colors[self.textbox_color])
        self.textbox_width = text_width + 32
        self.textbox_height = text_height + 32

        painter.setPen(QColor(0,0,0))
        painter.drawText(8,  10 + 16, "[Press ENTER to return to editor]")
        painter.drawText(12, 10 + 16, "[Press ENTER to return to editor]")
        painter.drawText(10, 8  + 16, "[Press ENTER to return to editor]")
        painter.drawText(10, 12 + 16, "[Press ENTER to return to editor]")
        painter.setPen(QColor(196,196,250))
        painter.drawText(10, 10 + 16, "[Press ENTER to return to editor]")
        
        painter.end()
示例#37
0
    def paintEvent(self, event):
        painter = QPainter(self)
        margin = 25
        pad = 10
        ind = 50
        cr = self.contentsRect()
        size = cr.size()
        boxWidth = (size.width() - 2 * margin - ind - 6 * pad) / 7
        boxHeight = boxWidth / 1.618

        date = datetime.date.today()
        prevMonth = date.month - 1
        top = cr.top() + margin

        while True:
            if not date.weekday():
                top += boxHeight + pad
            if prevMonth != date.month:
                top += boxHeight + pad

            rect = QRect(cr.left() + margin + ind + \
                    date.weekday() * (boxWidth + pad),
                    top, boxWidth, boxHeight)

            if rect.bottom() > cr.bottom() - margin:
                break

            if prevMonth != date.month:
                monRect = QRect(cr.left() + margin, top, ind, boxHeight)
                painter.drawText(monRect, Qt.AlignCenter, date.strftime('%b'))
            elif not date.weekday():
                monRect = QRect(cr.left() + margin, top, ind, boxHeight)
                painter.drawText(monRect, Qt.AlignCenter, date.strftime('%V'))

            if date in self.busyDays:
                color = QColor(200, 100, 100)
            elif date.weekday() > 4:
                color = QColor(0, 0, 120)
            else:
                color = QColor(60, 60, 180)

            painter.fillRect(rect, color)
            painter.drawText(rect, Qt.AlignCenter, str(date.day))

            prevMonth = date.month
            date += datetime.timedelta(days=1)
示例#38
0
    def Print(self, p: QPainter, m: QMargins, o: int = 0):
        if self.Report.TotalPagesCalculated is False or self.Visible is False:
            return

        r1, r2 = self.Report.onBeforePrint(
            self.Report._CurrentCopys, self.Section,
            self.Section._GetCurrentPrintRecord(), self)
        if r1:
            return
        txt = r2 if not (r2 is None) else self.getPrintText()
        rect = self._NewRect(m, o)
        # 填充颜色
        if self.FillColor:
            p.fillRect(rect, self.FillColor)
        # 绘制边框及文本
        if self.Bolder or self.FillColor:
            p.drawRect(rect)
            rect = rect - QMargins(1, 1, 1, 1)
        p.setFont(self.Font)

        if self.Transform:
            # 文本旋转的情况
            FontHeight = QFontMetrics(self.Font).height()
            p.save()
            p.translate(self.Rect.x() + m.left() + FontHeight,
                        self.Rect.y() + m.top() + o)
            # 第一个参数为距离
            p.rotate(90)
            p.drawText(QRect(0, 0, self.Rect.width(), self.Rect.height()),
                       self.AlignmentFlag, txt)
            # 第一个参数Left为调整后距离页面顶端的距离
            p.restore()
        else:
            # 文字不旋转的情况
            fm = p.fontMetrics()
            # 处理长文本省略
            if self.AutoEllipsis:
                elidedText = fm.elidedText(txt, Qt.ElideRight, rect.width())
            # 处理长文本自动缩小字体
            if self.AutoShrinkFont:
                self.__AutoShrinkFont(p, rect, txt)
            if self.AutoEllipsis:
                p.drawText(rect, self.AlignmentFlag, elidedText)
            else:
                p.drawText(rect, self.AlignmentFlag, txt)
示例#39
0
    def paintEvent(self, event):

        self.startX = (self.width() - self.textWidth) / 2
        self.startY = self.toolBarHeight + (
            self.height() - self.toolBarHeight - self.textHeight) / 2

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

        # pixelSize = self.font.pixelSize()
        # pixelSize += 1
        # self.font.setPixelSize(pixelSize)
        # self.setFont(self.font)
        # self.textHeight = self.fontMetrics().height()
        # spacing = (self.height() - self.toolBarHeight - self.textHeight) / 2
        # # if spacing > 0:

        painter.setFont(self.font)

        if self.boderFlag:
            color = QColor('lightgray')
            color.setAlpha(30)
            painter.fillRect(0, self.toolBarHeight, self.width(),
                             self.height() - self.toolBarHeight, color)

        painter.setPen(QColor(0, 0, 0, 200))
        painter.drawText(self.startX + 1, self.startY + 1, self.textWidth,
                         self.textHeight, Qt.AlignLeft, self.text)

        painter.setPen(QPen(self.linear_gradient, 0))
        painter.drawText(self.startX, self.startY, self.textWidth,
                         self.textHeight, Qt.AlignLeft, self.text)

        painter.setPen(QPen(self.mask_linear_gradient, 0))
        painter.drawText(self.startX, self.startY, self.textWidth * self.p,
                         self.textHeight, Qt.AlignLeft, self.text)

        self.p += 0.01

        if self.p >= 1:
            self.p = 0

        self.font.setPixelSize(30)
示例#40
0
    def paintEvent(self, event):
        super().paintEvent(event)
        if self._number is None:
            painter = QPainter(self)
            fm = self.fontMetrics()
            base_line = (self.height() - fm.height()) / 2 + fm.ascent()
            painter.drawText(event.rect(), Qt.AlignCenter, self._text)
        else:
            fm = self.fontMetrics()
            base_line = (self.height() - fm.height()) / 2 + fm.ascent()
            number_width = fm.width(self._number)

            painter = QPainter(self)
            # Draw shortcut number
            painter.drawText((15 - number_width) / 2, base_line, self._number)
            # Draw display name of tool button
            painter.drawText(
                18, base_line,
                fm.elidedText(self._text, Qt.ElideRight, self.width()))
示例#41
0
 def paintEvent(self, event):
     # инициализация
     qp = QPainter()
     qp.begin(self)
     # тесты
     qp.setFont(QFont('Lucida Console', 14))
     #size = self.size()
     qp.setBrush(QColor(100, 100, 150))
     qp.setPen(QPen(Qt.black, 2, Qt.SolidLine))
     
     #drawTiles of field. Рисуем тайлы - Вынести в функции(какого класса?)
     for x in range(field.w):
         for y in range(field.h):
             self.drawTile(qp, field.tiles[x][y], x, y)
     # рисуем динамические объекты
     for x in field.dynamicTiles:
         self.drawTile(qp, x, x.x, x.y) 
     self.drawTile(qp, field.player, field.player.x, field.player.y)
     
     # лог
     if self.log.visible:
         qp.setBrush(QColor(30, 30, 60))
         qp.setPen(QPen(Qt.white, 0, Qt.SolidLine))
         logRect = QRect(0, self.height-self.log.height, self.width, self.log.height)
         qp.drawRect(logRect)
         lines = ''
         #rlog = self.log.log
         #rlog.reverse()
         for line in self.log.log:
             lines += line + '\n'
         qp.drawText(logRect, Qt.AlignLeft, lines)
         #status
         qp.setPen(QPen(Qt.white, 2, Qt.SolidLine))
         qp.drawLine(self.width-self.log.statusWidht, self.height-self.log.height, \
         self.width-self.log.statusWidht, self.height)
         qp.drawText(QRect(self.width-self.log.statusWidht, self.height-self.log.height, \
         self.log.statusWidht, 20), Qt.AlignCenter, 'status:')
         qp.drawText(QRect(self.width-self.log.statusWidht, self.height-self.log.height+20, \
         self.log.statusWidht, 20), Qt.AlignCenter, 'cursor at(x,y):')
         
     # финализация
     qp.end()
示例#42
0
 def combineTiles(self):
     global radar1
     ii = QImage(self.tilesWidth * 256, self.tilesHeight * 256,
                 QImage.Format_ARGB32)
     painter = QPainter()
     painter.begin(ii)
     painter.setPen(QColor(255, 255, 255, 255))
     painter.setFont(QFont("Arial", 10))
     i = 0
     xo = self.cornerTiles["NW"]["X"]
     xo = int((int(xo) - xo) * 256)
     yo = self.cornerTiles["NW"]["Y"]
     yo = int((int(yo) - yo) * 256)
     for y in range(0, self.totalHeight, 256):
         for x in range(0, self.totalWidth, 256):
             painter.drawImage(x, y, self.tileQimages[i])
             # painter.drawRect(x, y, 255, 255)
             # painter.drawText(x+3, y+12, self.tiletails[i])
             i += 1
     painter.end()
     painter = None
     self.tileQimages = []
     ii2 = ii.copy(-xo, -yo, self.rect.width(), self.rect.height())
     ii = None
     painter2 = QPainter()
     painter2.begin(ii2)
     timestamp = "{0:%H:%M} RainView.com".format(
         datetime.datetime.fromtimestamp(self.getTime))
     painter2.setPen(QColor(63, 63, 63, 255))
     painter2.setFont(QFont("Arial", 8))
     painter2.setRenderHint(QPainter.TextAntialiasing)
     painter2.drawText(3 - 1, 12 - 1, timestamp)
     painter2.drawText(3 + 2, 12 + 1, timestamp)
     painter2.setPen(QColor(255, 255, 255, 255))
     painter2.drawText(3, 12, timestamp)
     painter2.drawText(3 + 1, 12, timestamp)
     painter2.end()
     painter2 = None
     ii3 = QPixmap(ii2)
     ii2 = None
     self.frameImages.append({"time": self.getTime, "image": ii3})
     ii3 = None
示例#43
0
    def paintEvent(self, event):
        if type(event) is not bool:
            painter = QPainter(self)
            painter.setPen(QPen(QColor(80, 255, 80), 2))
            if self.cluster:
                if self.mark == "yellow":
                    painter.setOpacity(0.5)
            else:
                if self.mark == "yellow":
                    painter.setOpacity(0.8)
                elif self.mark == "red":
                    painter.setOpacity(0.5)
            painter.drawImage(event.rect(), self.im1)
            if not self.cluster:
                painter.drawLine(self.line1)
                painter.drawLine(self.line2)

            # draw decision mark
            fontsize = int(self.im1.size().height() * 0.65)
            if self.mark == "green":
                pass
            elif self.mark == "yellow" and not self.cluster:
                painter.setOpacity(0.9)
                painter.setPen(QPen(QColor(220, 220, 0)))
                painter.setFont(QFont("Helvetica", fontsize))
                painter.drawText(self.im1.rect(),
                                 Qt.AlignHCenter | Qt.AlignVCenter, "?")
            elif self.mark == "yellow" and self.cluster:
                painter.setOpacity(0.9)
                painter.setPen(QPen(QColor(220, 220, 0)))
                painter.setFont(QFont("Helvetica", fontsize))
                painter.drawText(self.im1.rect(),
                                 Qt.AlignHCenter | Qt.AlignVCenter, "√")
            elif self.mark == "red":
                painter.setOpacity(0.8)
                painter.setPen(QPen(QColor(220, 0, 0)))
                painter.setFont(QFont("Helvetica", fontsize))
                painter.drawText(self.im1.rect(),
                                 Qt.AlignHCenter | Qt.AlignVCenter, "X")
            else:
                print("ERROR: unrecognised segment mark")
                return
 def paintImage(self, pixmap):
     painter = QPainter(pixmap)
     pen = QPen(self.car_detection_color)  # TODO: Fix coloring
     pen.setWidth(3)
     painter.setPen(pen)
     painter.setFont(QFont('Decorative', 10))
     if self.warning_msg:
         painter.drawText(
             0, 20, "Distance: %i.%im, Velocity:%f" %
             (self.lidar_distance / 100, self.lidar_distance % 100,
              self.lidar_velocity))
         painter.drawText(0, 60, "WARNING!")
     if self.car_detected:
         for square in range(len(self.ROIs)):
             roi = self.ROIs[square]
             painter.drawRect(roi[0], roi[1], roi[2], roi[3])
             painter.drawText(roi[0], roi[1], "ROI:%i" % square)
     del pen
     del painter
     return pixmap
示例#45
0
    def _paintSoundLevel(self, painter: QPainter) -> None:
        """Paint wave (power)
        """
        fontMetrics = painter.fontMetrics()
        pen = painter.pen()
        width = self.width()
        height = self.height()
        text_height = fontMetrics.height()

        # write times
        pen.setColor(Qt.black)
        start_string = time_str(self._view[0])
        end_string = time_str(self._view[1])
        painter.drawText(0, height, start_string)
        painter.drawText(width - fontMetrics.width(end_string), height,
                         end_string)

        # draw sound wave
        if self._path is not None:
            painter.drawPath(self._path)

        # draw position indicator
        if self._player is not None:
            position = self._player.position
            if position is not None:
                x_position = int(((position - self._view[0]) /
                                  (self._view[1] - self._view[0])) * width)
                if 0 <= x_position <= width:
                    # draw vertical line
                    painter.setPen(QPen(Qt.red, 1))
                    painter.drawLine(x_position, 0, x_position, height)
                    # write time
                    position_string = time_str(self._player.position)
                    text_width = fontMetrics.width(position_string)
                    x_location = max(
                        0, min(x_position - text_width // 2,
                               width - text_width))
                    painter.drawText(x_location, text_height, position_string)
示例#46
0
    def paintEvent(self, event):
        qp = QPainter()
        blackPen = QPen(QBrush(Qt.black), 1)
        qp.begin(self)
        qp.fillRect(event.rect(), Qt.white)

        qp.setPen(blackPen)
        index = 0
        for r in range(len(self.__board)):
            for c in range(len(self.__board[r])):
                qp.drawRect(GRID_ORIGINX + c * CELL_SIZE,
                            GRID_ORIGINY + r * CELL_SIZE, CELL_SIZE, CELL_SIZE)
                if self.list[index] == '16':
                    pass
                else:
                    qp.drawText(GRID_ORIGINX + 20 + c * CELL_SIZE,
                                GRID_ORIGINY + 25 + r * CELL_SIZE,
                                self.list[index])
                qp.drawText(10, 20, self.movesstring)
                index = index + 1
        if self.gameover() == True:
            qp.drawText(10, 40, 'Game Over!')
            sounds.make_sound(self)
        qp.end()
示例#47
0
    def paintEvent(self, event):
        painter = QPainter(self.viewport())
        painter.fillRect(0, 0, self.viewport().width(), self.viewport().height(), QColor('#181818'))

        self.pos = self.verticalScrollBar().value()
        data_start = 0
        data_end = 0

        if len(self.data) > self.visible_lines():
            data_start = self.pos
            data_end = self.pos + self.visible_lines()
        else:
            data_end = len(self.data)

        drawing_pos_y = 10
        trace_depth = 0

        fontMetrics = QFontMetrics(QFont(self.font))
        text_options = QTextOption()
        text_options.setAlignment(Qt.AlignLeft)
        text_options.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere)

        for i, line in enumerate(self.data):
            if i == self.pos:
                break
            if line['event'] == 'leave':
                trace_depth -= 1
            elif line['event'] == 'enter':
                trace_depth += 1

        for i, line in enumerate(self.data[data_start:data_end]):
            if i > self.visible_lines():
                break

            is_obj = False
            if isinstance(line['data'], str) and line['data'].startswith('{'):
                is_obj = True
                line['data'] = json.loads(line['data'])

            drawing_pos_x = 10
            painter.setPen(QColor('#fff'))

            if line['event'] == 'leave':
                if trace_depth:
                    trace_depth -= 1
                drawing_pos_x += (trace_depth * 20)
                painter.setPen(QColor('crimson'))
                painter.setBrush(QColor('#222'))
                polygon = QPolygon()
                polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5)))
                painter.drawPolygon(polygon)
            elif line['event'] == 'enter':
                trace_depth += 1
                drawing_pos_x += (trace_depth * 20)
                painter.setPen(QColor('yellowgreen'))
                painter.setBrush(QColor('#222'))
                polygon = QPolygon()
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y - (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 5, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y + self._char_height + (self._char_height * 0.5)))
                #polygon.append(QPoint(drawing_pos_x + 21, drawing_pos_y + (self._char_height * 0.5)))
                polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5)))
                painter.drawPolygon(polygon)

            drawing_pos_x += 20
            rect = QRectF(drawing_pos_x, drawing_pos_y, self.viewport().width() - 25 - drawing_pos_x, self._char_height + 10)

            if line['event'] == 'enter':
                arg_str = '('
                for a in range(len(line['data'])):
                    arg_str += 'arg_{0}, '.format(a)

                if len(line['data']):
                    arg_str = arg_str[:-2]
                arg_str += ')'
                painter.drawText(rect, line['class'] + arg_str, option=text_options)
            else:
                painter.drawText(rect, line['class'], option=text_options)

            drawing_pos_y += self._char_height + 15

            if isinstance(line['data'], str):
                if line['data']:
                    rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, self.viewport().width() - drawing_pos_x - 25, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, line['data'])
                    rect = QRectF(drawing_pos_x, drawing_pos_y, rect.width(), rect.height())
                    painter.setPen(QColor('#888'))
                    painter.drawText(rect, line['data'], option=text_options)
                    drawing_pos_y += rect.height() + 5
            else:
                width = int(floor(self.viewport().width() - drawing_pos_x - (5 * self._char_width) - 35))
                max_chars = int(floor(width / self._char_width))
                hold_x = drawing_pos_x + 5
                width -= 20
                painter.setPen(QColor('#888'))
                for data in line['data']:
                    drawing_pos_x = hold_x
                    if isinstance(line['data'][data], int):
                        text = '{0:d}'.format(line['data'][data])
                    elif isinstance(line['data'][data], str):
                        text = line['data'][data]
                    elif isinstance(line['data'][data], list):
                        text = str(line['data'][data])
                    else:
                        text = str(line['data'][data])

                    if line['event'] == 'enter':
                        arg = 'arg_{0}: '.format(data)
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, arg)
                        drawing_pos_x += len(arg) * self._char_width
                    elif line['event'] == 'leave':
                        retval = data + ': '
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, retval)
                        drawing_pos_x += len(retval) * self._char_width

                    if len(text) * self._char_width < width:
                        painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, text)
                        drawing_pos_y += self._char_height + 5
                    else:
                        rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, width, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, text)
                        rect = QRectF(rect)
                        painter.drawText(rect, text, option=text_options)
                        drawing_pos_y += rect.height() + 5

            drawing_pos_y += self._char_height + 5
    def paintEvent(self, e):
        painter = QPainter()
        painter.begin(self)
        painter.setFont(self.font)

        #For each grid
        for x in range(self.n_x):
            for y in range(self.n_y):
                #Draw goal
                if self.grid_map[x, y] == 1:
                    if self.win_reward > 0:
                        c = QColor(0, 255, 0)
                    elif self.win_reward < 0:
                        c = QColor(255, 0, 0)
                    else:
                        c = QColor(255, 255, 255)

                    self.draw_rect(painter,
                                   color=c,
                                   rect=QRect(self.offset + x * self.grid_size,
                                              self.offset + y * self.grid_size,
                                              self.grid_size, self.grid_size))
                    painter.drawText(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size, self.grid_size,
                              self.grid_size), Qt.AlignCenter,
                        "{:.2f}".format(self.grid_reward[x, y]))
                    painter.drawPixmap(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size, self.grid_size,
                              self.grid_size), self.goal_pixmap)

                #Draw hole
                elif self.grid_map[x, y] == -1:
                    if self.loss_reward > 0:
                        c = QColor(0, 255, 0)
                    elif self.loss_reward < 0:
                        c = QColor(255, 0, 0)
                    else:
                        c = QColor(255, 255, 255)

                    self.draw_rect(painter,
                                   color=c,
                                   rect=QRect(self.offset + x * self.grid_size,
                                              self.offset + y * self.grid_size,
                                              self.grid_size, self.grid_size))
                    painter.drawText(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size, self.grid_size,
                              self.grid_size), Qt.AlignCenter,
                        "{:.2f}".format(self.grid_reward[x, y]))
                    painter.drawPixmap(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size, self.grid_size,
                              self.grid_size), self.hole_pixmap)

                #Draw block
                elif self.grid_map[x, y] == -2:
                    self.draw_rect(painter,
                                   color=QColor(128, 128, 128),
                                   rect=QRect(self.offset + x * self.grid_size,
                                              self.offset + y * self.grid_size,
                                              self.grid_size, self.grid_size))

                #Draw grid
                else:
                    if self.grid_value[x, y] < 0:
                        if self.loss_reward == 0:
                            alpha = 0
                        else:
                            alpha = self.grid_value[x, y] / self.loss_reward

                        if alpha > 1: alpha = 1.

                        c = red * alpha + white * (1. - alpha)
                    else:
                        if self.win_reward == 0:
                            alpha = 0
                        else:
                            alpha = self.grid_value[x, y] / self.win_reward

                        if alpha > 1: alpha = 1.

                        c = green * alpha + white * (1. - alpha)

                    if self.grid_policy[x, y] == 0: arrow = "^"
                    elif self.grid_policy[x, y] == 1: arrow = "v"
                    elif self.grid_policy[x, y] == 2: arrow = "<"
                    else: arrow = ">"

                    self.draw_rect(painter,
                                   color=QColor(int(c[0]), int(c[1]),
                                                int(c[2])),
                                   rect=QRect(self.offset + x * self.grid_size,
                                              self.offset + y * self.grid_size,
                                              self.grid_size, self.grid_size))
                    painter.drawText(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size, self.grid_size,
                              self.grid_size), Qt.AlignCenter,
                        "{:.2f}".format(self.grid_value[x, y]))
                    painter.drawText(
                        QRect(self.offset + x * self.grid_size,
                              self.offset + y * self.grid_size + 20,
                              self.grid_size, self.grid_size), Qt.AlignCenter,
                        arrow)

        painter.end()
示例#49
0
 def tray(self):
     temp_decimal = eval(self.settings.value('Decimal') or 'False')
     try:
         if temp_decimal:
             temp_tray = self.temp_decimal
         else:
             temp_tray = self.temp
     except:
         # First time launch
         return
     if self.inerror or not hasattr(self, 'temp'):
         logging.critical('Cannot paint icon!')
         if hasattr(self, 'overviewcity'):
             try:
                 # delete dialog to prevent memory leak
                 self.overviewcity.close()
             except:
                 pass
         return
     try:
         self.gif_loading.stop()
     except:
         # In first time run the gif is not animated
         pass
     logging.debug('Paint tray icon...')
     # Place empty.png here to initialize the icon
     # don't paint the T° over the old value
     icon = QPixmap(':/empty')
     self.traycolor = self.settings.value('TrayColor') or ''
     self.fontsize = self.settings.value('FontSize') or '18'
     self.tray_type = self.settings.value('TrayType') or 'icon&temp'
     pt = QPainter()
     pt.begin(icon)
     if self.tray_type != 'temp':
         pt.drawPixmap(0, -12, 64, 64, self.wIcon)
     pt.setFont(QFont('sans-sertif', int(self.fontsize)))
     pt.setPen(QColor(self.traycolor))
     if self.tray_type == 'icon&temp':
         pt.drawText(icon.rect(), Qt.AlignBottom | Qt.AlignCenter,
                     str(temp_tray))
     if self.tray_type == 'temp':
         pt.drawText(icon.rect(), Qt.AlignCenter, str(temp_tray))
     pt.end()
     if self.tray_type == 'icon':
         self.systray.setIcon(QIcon(self.wIcon))
     else:
         self.systray.setIcon(QIcon(icon))
     try:
         if not self.overviewcity.isVisible():
             notifier = self.settings.value('Notifications') or 'True'
             notifier = eval(notifier)
             if notifier:
                 temp = int(re.search('\d+', self.temp_decimal).group())
                 if temp != self.notification_temp or self.id_ != self.notifications_id:
                     self.notifications_id = self.id_
                     self.notification_temp = temp
                     self.systray.showMessage('meteo-qt', self.notification)
     except:
         logging.debug('OverviewCity has been deleted' +
                       'Download weather information again...')
         self.try_again()
         return
     self.restore_city()
     self.tentatives = 0
     self.tooltip_weather()
     logging.info('Actual weather status for: ' + self.notification)
示例#50
0
 def paintEvent(self, event):
     painter = QPainter(self)
     painter.drawText(self.rect(), Qt.TextWordWrap, self.text())
示例#51
0
    def paintEvent(self, event):
        if self.minimum() == self.maximum() == 0:
            return
        # 正弦曲线公式 y = A * sin(ωx + φ) + k
        # 当前值所占百分比
        percent = 1 - (self.value() - self.minimum()) / \
                  (self.maximum() - self.minimum())
        # w表示周期,6为人为定义
        w = 6 * self.waterDensity * math.pi / self.width()
        # A振幅 高度百分比,1/26为人为定义
        A = self.height() * self.waterHeight * 1 / 26
        # k 高度百分比
        k = self.height() * percent

        # 波浪1
        waterPath1 = QPainterPath()
        waterPath1.moveTo(0, self.height())  # 起点在左下角
        # 波浪2
        waterPath2 = QPainterPath()
        waterPath2.moveTo(0, self.height())  # 起点在左下角

        # 偏移
        self._offset += 0.6
        if self._offset > self.width() / 2:
            self._offset = 0

        for i in range(self.width() + 1):
            # 从x轴开始计算y轴点
            y = A * math.sin(w * i + self._offset) + k
            waterPath1.lineTo(i, y)

            # 相对第一条需要进行错位
            y = A * math.sin(w * i + self._offset + self.width() / 2 * A) + k
            waterPath2.lineTo(i, y)

        # 封闭两条波浪,形成一个 U形 上面加波浪的封闭区间
        waterPath1.lineTo(self.width(), self.height())
        waterPath1.lineTo(0, self.height())
        waterPath2.lineTo(self.width(), self.height())
        waterPath2.lineTo(0, self.height())

        # 整体形状(矩形或者圆形)
        bgPath = QPainterPath()
        if self.styleType:
            bgPath.addRect(QRectF(self.rect()))
        else:
            radius = min(self.width(), self.height())
            bgPath.addRoundedRect(QRectF(self.rect()), radius, radius)

        # 开始画路径
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        # 设置没有画笔
        painter.setPen(Qt.NoPen)

        if not self.styleType:
            # 圆形
            painter.setClipPath(bgPath)

        # 先整体绘制背景,然后再在背景上方绘制两条波浪
        painter.save()
        painter.setBrush(self.backgroundColor)
        painter.drawPath(bgPath)
        painter.restore()

        # 波浪1
        painter.save()
        painter.setBrush(self.waterColor1)
        painter.drawPath(waterPath1)
        painter.restore()

        # 波浪2
        painter.save()
        painter.setBrush(self.waterColor2)
        painter.drawPath(waterPath2)
        painter.restore()

        # 绘制文字
        if not self.isTextVisible():
            return
        painter.setPen(self.textColor)
        font = self.font() or QFont()
        font.setPixelSize(int(min(self.width(), self.height()) / 2))
        painter.setFont(font)
        painter.drawText(self.rect(), Qt.AlignCenter, '%d%%' %
                         (self.value() / self.maximum() * 100))
示例#52
0
 def drawText(self, text: str, position):
     pen = QPen()
     painter = QPainter(self.canvas)
     painter.setPen(pen)
     painter.drawText(QPoint(position.x, position.y), text)
示例#53
0
    def drawValues(self, qp: QtGui.QPainter):
        if len(self.data) == 0 and len(self.reference) == 0:
            return
        pen = QtGui.QPen(self.sweepColor)
        pen.setWidth(self.pointSize)
        line_pen = QtGui.QPen(self.sweepColor)
        line_pen.setWidth(self.lineThickness)
        highlighter = QtGui.QPen(QtGui.QColor(20, 0, 255))
        highlighter.setWidth(1)
        if not self.fixedSpan:
            if len(self.data) > 0:
                fstart = self.data[0].freq
                fstop = self.data[len(self.data) - 1].freq
            else:
                fstart = self.reference[0].freq
                fstop = self.reference[len(self.reference) - 1].freq
            self.fstart = fstart
            self.fstop = fstop
        else:
            fstart = self.fstart = self.minFrequency
            fstop = self.fstop = self.maxFrequency

        # Draw bands if required
        if self.bands.enabled:
            self.drawBands(qp, fstart, fstop)

        if self.fixedValues:
            maxValue = self.maxDisplayValue / 10e11
            minValue = self.minDisplayValue / 10e11
            self.maxValue = maxValue
            self.minValue = minValue
        else:
            # Find scaling
            minValue = 1
            maxValue = -1
            for d in self.data:
                val = d.capacitiveEquivalent()
                if val > maxValue:
                    maxValue = val
                if val < minValue:
                    minValue = val
            for d in self.reference:  # Also check min/max for the reference sweep
                if d.freq < self.fstart or d.freq > self.fstop:
                    continue
                val = d.capacitiveEquivalent()
                if val > maxValue:
                    maxValue = val
                if val < minValue:
                    minValue = val
            self.maxValue = maxValue
            self.minValue = minValue

        span = maxValue - minValue
        if span == 0:
            logger.info(
                "Span is zero for CapacitanceChart, setting to a small value.")
            span = 1e-15
        self.span = span

        target_ticks = math.floor(self.chartHeight / 60)
        fmt = Format(max_nr_digits=1)
        for i in range(target_ticks):
            val = minValue + (i / target_ticks) * span
            y = self.topMargin + round(
                (self.maxValue - val) / self.span * self.chartHeight)
            qp.setPen(self.textColor)
            if val != minValue:
                valstr = str(Value(val, fmt=fmt))
                qp.drawText(3, y + 3, valstr)
            qp.setPen(QtGui.QPen(self.foregroundColor))
            qp.drawLine(self.leftMargin - 5, y,
                        self.leftMargin + self.chartWidth, y)

        qp.setPen(QtGui.QPen(self.foregroundColor))
        qp.drawLine(self.leftMargin - 5, self.topMargin,
                    self.leftMargin + self.chartWidth, self.topMargin)
        qp.setPen(self.textColor)
        qp.drawText(3, self.topMargin + 4, str(Value(maxValue, fmt=fmt)))
        qp.drawText(3, self.chartHeight + self.topMargin,
                    str(Value(minValue, fmt=fmt)))
        self.drawFrequencyTicks(qp)

        self.drawData(qp, self.data, self.sweepColor)
        self.drawData(qp, self.reference, self.referenceColor)
        self.drawMarkers(qp)
示例#54
0
    def paintEvent(self, e):

        super(LabeledSlider, self).paintEvent(e)

        style = self.sl.style()
        painter = QPainter(self)
        st_slider = QStyleOptionSlider()
        st_slider.initFrom(self.sl)
        st_slider.orientation = self.sl.orientation()

        length = style.pixelMetric(QStyle.PM_SliderLength, st_slider, self.sl)
        available = style.pixelMetric(QStyle.PM_SliderSpaceAvailable,
                                      st_slider, self.sl)

        for v, v_str in self.levels:

            # get the size of the label
            rect = painter.drawText(QRect(), Qt.TextDontPrint, v_str)

            if self.sl.orientation() == Qt.Horizontal:
                # I assume the offset is half the length of slider, therefore
                # + length//2
                x_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),
                                                       self.sl.maximum(), v,
                                                       available) + length // 2

                # left bound of the text = center - half of text width + L_margin
                left = x_loc - rect.width() // 2 + self.left_margin
                bottom = self.rect().bottom()

                # enlarge margins if clipping
                if v == self.sl.minimum():
                    if left <= 0:
                        self.left_margin = rect.width() // 2 - x_loc
                    if self.bottom_margin <= rect.height():
                        self.bottom_margin = rect.height()

                    self.layout.setContentsMargins(self.left_margin,
                                                   self.top_margin,
                                                   self.right_margin,
                                                   self.bottom_margin)

                if v == self.sl.maximum(
                ) and rect.width() // 2 >= self.right_margin:
                    self.right_margin = rect.width() // 2
                    self.layout.setContentsMargins(self.left_margin,
                                                   self.top_margin,
                                                   self.right_margin,
                                                   self.bottom_margin)

            else:
                y_loc = QStyle.sliderPositionFromValue(self.sl.minimum(),
                                                       self.sl.maximum(),
                                                       v,
                                                       available,
                                                       upsideDown=True)

                bottom = y_loc + length // 2 + rect.height(
                ) // 2 + self.top_margin - 3
                # there is a 3 px offset that I can't attribute to any metric

                left = self.left_margin - rect.width()
                if left <= 0:
                    self.left_margin = rect.width() + 2
                    self.layout.setContentsMargins(self.left_margin,
                                                   self.top_margin,
                                                   self.right_margin,
                                                   self.bottom_margin)

            pos = QPoint(left, bottom)
            painter.drawText(pos, v_str)

        return
示例#55
0
    def paintForeground(self, painter: QtGui.QPainter) -> None:
        assert self._note_area is not None
        self._edit_areas.clear()

        ymid = self.height() // 2

        base_stave_line = self.measure.clef.center_pitch.stave_line
        base_octave = self.measure.clef.base_octave

        acc_map = {
            'C#': 'C%d' % (base_octave + 1),
            'D#': 'D%d' % (base_octave + 1),
            'E#': 'E%d' % (base_octave + 1),
            'F#': 'F%d' % (base_octave + 1),
            'G#': 'G%d' % (base_octave + 1),
            'A#': 'A%d' % base_octave,
            'B#': 'B%d' % base_octave,
            'Cb': 'C%d' % (base_octave + 1),
            'Db': 'D%d' % (base_octave + 1),
            'Eb': 'E%d' % (base_octave + 1),
            'Fb': 'F%d' % base_octave,
            'Gb': 'G%d' % base_octave,
            'Ab': 'A%d' % base_octave,
            'Bb': 'B%d' % base_octave,
        }

        active_accidentals = {}
        for acc in self.measure.key_signature.accidentals:
            value = acc_map[acc]
            active_accidentals[value[:1]] = acc[1:]

        x, note_area_width = self._note_area
        if note_area_width > 80:
            px = x - 20
            note_time = audioproc.MusicalDuration(0)
            for idx, note in enumerate(self.measure.notes):
                overflow = note_time + note.duration > self.measure.duration

                if note.is_rest:
                    sym = {
                        1: 'rest-whole',
                        2: 'rest-half',
                        4: 'rest-quarter',
                        8: 'rest-8th',
                        16: 'rest-16th',
                        32: 'rest-32th',
                    }[note.base_duration.denominator]
                    svg_symbol.paintSymbol(painter, sym,
                                           QtCore.QPoint(x, ymid))

                    if note.base_duration >= audioproc.MusicalDuration(1, 2):
                        dx = 25
                        dy = -10
                    else:
                        dx = 12
                        dy = 0

                    for d in range(note.dots):
                        painter.setPen(Qt.NoPen)
                        painter.setBrush(Qt.black)
                        painter.drawEllipse(dx - 4 + 10 * d, dy - 4, 9, 9)

                    if note.tuplet != 0:
                        painter.setPen(Qt.black)
                        painter.drawText(-5, -45, '%d' % note.tuplet)

                    # if overflow:
                    #     n.setOpacity(0.4)
                elif len(note.pitches) > 0:
                    min_stave_line = 1000
                    max_stave_line = -1000

                    for pitch in note.pitches:
                        stave_line = pitch.stave_line - base_stave_line
                        min_stave_line = min(min_stave_line, stave_line)
                        max_stave_line = max(max_stave_line, stave_line)

                    painter.setPen(Qt.black)
                    painter.setOpacity(0.4 if overflow else 0.8)

                    # Ledger lines above stave.
                    for l in range(6, max_stave_line + 1, 2):
                        painter.drawLine(x - 20, ymid - 10 * l, x + 20,
                                         ymid - 10 * l)

                    # Ledger lines below stave.
                    for l in range(-6, min_stave_line - 1, -2):
                        painter.drawLine(x - 20, ymid - 10 * l, x + 20,
                                         ymid - 10 * l)

                    painter.setOpacity(1.0)

                    for pitch in note.pitches:
                        stave_line = pitch.stave_line - base_stave_line

                        y = ymid - 10 * stave_line

                        active_accidental = active_accidentals.get(
                            pitch.value, '')
                        if pitch.accidental != active_accidental:
                            sym = self._accidental_map[pitch.accidental]
                            svg_symbol.paintSymbol(painter, sym,
                                                   QtCore.QPoint(x - 12, y))
                            active_accidentals[pitch.value] = pitch.accidental

                        if note.base_duration >= audioproc.MusicalDuration(
                                1, 2):
                            svg_symbol.paintSymbol(painter, 'note-head-void',
                                                   QtCore.QPoint(x, y))
                        else:
                            svg_symbol.paintSymbol(painter, 'note-head-black',
                                                   QtCore.QPoint(x, y))

                        if note.base_duration <= audioproc.MusicalDuration(
                                1, 2):
                            painter.fillRect(x + 8, y - 63, 3, 60, Qt.black)

                        if note.base_duration == audioproc.MusicalDuration(
                                1, 8):
                            flags = 1
                        elif note.base_duration == audioproc.MusicalDuration(
                                1, 16):
                            flags = 2
                        elif note.base_duration == audioproc.MusicalDuration(
                                1, 32):
                            flags = 3
                        else:
                            flags = 0

                        for f in range(flags):
                            svg_symbol.paintSymbol(
                                painter, 'note-flag-down',
                                QtCore.QPoint(x + 11, y - 63 + 12 * f))

                        for d in range(note.dots):
                            painter.setPen(Qt.NoPen)
                            painter.setBrush(Qt.black)
                            painter.drawEllipse(x + 12 + 10 * d, y - 4, 9, 9)

                        if note.tuplet != 0:
                            painter.drawText(x - 5, y - 85, '%d' % note.tuplet)

                    # if overflow:
                    #     n.setOpacity(0.4)

                x1 = max(x - 12, px)
                x2 = max(x + 13, x1)
                if x1 > px:
                    self._edit_areas.append((px, x1, idx, False))
                    px = x1
                if x2 > x1:
                    self._edit_areas.append((x1, x2, idx, True))
                    px = x2

                note_time += note.duration
                x += int(note_area_width * note.duration.fraction)

            if px < self.width():
                self._edit_areas.append(
                    (px, self.width(), len(self.measure.notes), False))
        else:
            self._note_area = (0, self.width())
示例#56
0
    def paintBackground(self, painter: QtGui.QPainter) -> None:
        ymid = self.height() // 2

        painter.setPen(Qt.black)
        painter.setBrush(Qt.black)

        for l in range(-2, 3):
            painter.drawLine(0, ymid + 20 * l, self.width() - 1, ymid + 20 * l)

        if self.is_first:
            painter.fillRect(0, ymid - 40, 2, 20 * 4, Qt.black)

        painter.drawLine(self.width() - 1, ymid - 40,
                         self.width() - 1, ymid + 40)

        if not self.measure_reference.is_first:
            prev_sibling = down_cast(
                model.ScoreMeasure,
                self.measure_reference.prev_sibling.measure)
        else:
            prev_sibling = None

        base_stave_line = self.measure.clef.center_pitch.stave_line
        base_octave = self.measure.clef.base_octave
        x = 0

        paint_clef = prev_sibling is None or self.measure.clef != prev_sibling.clef

        if paint_clef and self.width() - x > 200:
            svg_symbol.paintSymbol(
                painter, 'clef-%s' % self.measure.clef.symbol,
                QtCore.QPoint(
                    x + 30, ymid - 10 *
                    (self.measure.clef.base_pitch.stave_line - base_stave_line)
                ))
            x += 60

        acc_map = {
            'C#': 'C%d' % (base_octave + 1),
            'D#': 'D%d' % (base_octave + 1),
            'E#': 'E%d' % (base_octave + 1),
            'F#': 'F%d' % (base_octave + 1),
            'G#': 'G%d' % (base_octave + 1),
            'A#': 'A%d' % base_octave,
            'B#': 'B%d' % base_octave,
            'Cb': 'C%d' % (base_octave + 1),
            'Db': 'D%d' % (base_octave + 1),
            'Eb': 'E%d' % (base_octave + 1),
            'Fb': 'F%d' % base_octave,
            'Gb': 'G%d' % base_octave,
            'Ab': 'A%d' % base_octave,
            'Bb': 'B%d' % base_octave,
        }

        paint_key_signature = (
            prev_sibling is None
            or self.measure.key_signature != prev_sibling.key_signature)

        if paint_key_signature and self.width() - x > 200:
            for acc in self.measure.key_signature.accidentals:
                value = acc_map[acc]
                stave_line = value_types.Pitch(
                    value).stave_line - base_stave_line

                svg_symbol.paintSymbol(
                    painter, self._accidental_map[acc[1:]],
                    QtCore.QPoint(x + 10, ymid - 10 * stave_line))

                x += 10

            if self.measure.key_signature.accidentals:
                x += 10

        paint_time_signature = (
            prev_sibling is None
            or self.measure.time_signature != prev_sibling.time_signature)

        if paint_time_signature and self.width() - x > 200:
            font = QtGui.QFont('FreeSerif', 30, QtGui.QFont.Black)
            font.setStretch(120)
            painter.setFont(font)

            painter.drawText(x, ymid - 5,
                             '%d' % self.measure.time_signature.upper)
            painter.drawText(x, ymid + 32,
                             '%d' % self.measure.time_signature.lower)

            x += 40

        if self.width() - x > 100:
            self._note_area = (x + 20, self.width() - x - 20)

        else:
            self._note_area = (0, self.width())
    def paintInfoColumn(self, painter, option, index, width_limit=0):
        left = option.rect.left() + 3
        top = option.rect.top()
        width = option.rect.width() - width_limit

        pixmap = QPixmap(option.rect.size())
        pixmap.fill(Qt.transparent)

        p = QPainter(pixmap)
        p.setRenderHint(QPainter.Antialiasing, True)
        p.translate(-option.rect.topLeft())

        textInner = 2 * ICON_PADDING + ROW_HEIGHT - 10
        itemHeight = ROW_HEIGHT + 2 * ICON_PADDING

        margin = left + ICON_PADDING - 10

        title = index.model().data(index, NameRole).toString()
        summary = index.model().data(index, SummaryRole).toString()
        ptype = str(index.model().data(index, TypeRole).toString())
        rate = int(index.model().data(index, RateRole).toInt()[0])
        installed = index.model().data(index, InstalledRole).toBool()

        # We need to request update if its not possible to get meta data about the package
        try:
            # Get Package Icon if exists
            _icon = index.model().data(index, Qt.DecorationRole).toString()
        except:
            p.end()
            painter.drawPixmap(option.rect.topLeft(), pixmap)
            self.parent.requestUpdate()
            return

        icon = None

        if _icon:
            overlay = [CHECK_ICON] if installed else []
            KIconLoader._forceCache = True
            pix = KIconLoader.loadOverlayed(_icon, overlay, 32)
            if not pix.isNull():
                icon = QIcon(
                    pix.scaled(QSize(32, 32), Qt.KeepAspectRatio,
                               Qt.SmoothTransformation))
            KIconLoader._forceCache = False

        if not icon:
            icon = self.defaultIcon if not installed else self.defaultInstalledIcon

        # Paint the Icon
        icon.paint(p, margin, top + ICON_PADDING, ROW_HEIGHT, ROW_HEIGHT,
                   Qt.AlignCenter)

        fix_pos = 0
        if index.model().columnCount() <= 1:
            fix_pos = 22

        if config.USE_APPINFO:
            # Rating Stars
            for _rt_i in range(5):
                self._rt_0.paint(p, width + 10 * _rt_i - 30 - fix_pos,
                                 top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter)
            for _rt_i in range(rate):
                self._rt_1.paint(p, width + 10 * _rt_i - 30 - fix_pos,
                                 top + ROW_HEIGHT / 4, 10, 10, Qt.AlignCenter)

        foregroundColor = option.palette.color(QPalette.Text)
        p.setPen(foregroundColor)

        # Package Name
        p.setFont(self.boldFont)
        p.drawText(left + textInner, top, width - textInner, itemHeight / 2,
                   Qt.AlignBottom | Qt.AlignLeft, title)

        tagWidth = 0

        _component_width = 0
        if self.parent.showComponents:
            component = str(index.model().data(index,
                                               ComponentRole).toString())
            widthOfTitle = self.boldFontFM.width(title) + 6 + left + textInner

            p.setFont(self.tagFont)
            rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap,
                                               component)
            p.setPen(LIGHTGREEN)
            p.setBrush(LIGHTGREEN)
            p.drawRoundRect(widthOfTitle, top + 12,
                            rect.width() + 4, rect.height(), 10, 10)
            p.setPen(DARKGREEN)
            p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(),
                       Qt.AlignCenter, component)
            p.setPen(foregroundColor)
            _component_width = rect.width() + 8

        if self.parent.showIsA:
            isa = str(index.model().data(index, IsaRole).toString())
            if not isa == '':
                widthOfTitle = self.boldFontFM.width(
                    title) + 6 + left + textInner + _component_width

                p.setFont(self.tagFont)
                rect = self.tagFontFM.boundingRect(option.rect,
                                                   Qt.TextWordWrap, isa)
                p.setPen(LIGHTBLUE)
                p.setBrush(LIGHTBLUE)
                p.drawRoundRect(widthOfTitle, top + 12,
                                rect.width() + 4, rect.height(), 10, 10)
                p.setPen(DARKVIOLET)
                p.drawText(widthOfTitle + 2, top + 12, rect.width(),
                           rect.height(), Qt.AlignCenter, isa)
                p.setPen(foregroundColor)
                _component_width += rect.width() + 8

        if ptype not in ('None', 'normal'):
            widthOfTitle = self.boldFontFM.width(
                title) + 6 + left + textInner + _component_width
            p.setFont(self.tagFont)
            rect = self.tagFontFM.boundingRect(option.rect, Qt.TextWordWrap,
                                               self.types[ptype][1])
            p.setPen(self.types[ptype][0])
            p.setBrush(self.types[ptype][0])
            p.drawRoundRect(widthOfTitle, top + 12,
                            rect.width() + 4, rect.height(), 10, 10)
            p.setPen(WHITE)
            p.drawText(widthOfTitle + 2, top + 12, rect.width(), rect.height(),
                       Qt.AlignCenter, self.types[ptype][1])
            p.setPen(foregroundColor)
            tagWidth = rect.width()

        # Package Summary
        p.setFont(self.normalFont)
        foregroundColor.setAlpha(160)
        p.setPen(foregroundColor)
        elided_summary = self.normalFontFM.elidedText(
            summary, Qt.ElideRight, width - textInner - tagWidth - 22)
        p.drawText(left + textInner, top + itemHeight / 2, width - textInner,
                   itemHeight / 2, Qt.TextDontClip, elided_summary)
        foregroundColor.setAlpha(255)
        p.setPen(foregroundColor)

        buttonStyle = None
        if self.rowAnimator.currentRow() == index.row():
            description = index.model().data(index, DescriptionRole).toString()
            size = index.model().data(index, SizeRole).toString()
            homepage = index.model().data(index, HomepageRole).toString()
            installedVersion = str(index.model().data(
                index, InstalledVersionRole).toString())
            version = index.model().data(index, VersionRole)

            # Package Detail Label
            position = top + ROW_HEIGHT

            p.setFont(self.normalDetailFont)
            baseRect = QRect(left, position, width - 8, option.rect.height())
            rect = self.normalDetailFontFM.boundingRect(
                baseRect, Qt.TextWordWrap | Qt.TextDontClip, description)
            p.drawText(left + 2, position, width - 8, rect.height(),
                       Qt.TextWordWrap | Qt.TextDontClip, description)

            # Package Detail Homepage
            position += rect.height() + 4

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE, position, width - textInner,
                       itemHeight / 2, Qt.AlignLeft, self._titles['website'])

            p.setFont(self.normalDetailFont)
            homepage = self.normalDetailFontFM.elidedText(
                homepage, Qt.ElideRight, width - self._titleFM['website'])
            rect = self.normalDetailFontFM.boundingRect(
                option.rect, Qt.TextSingleLine, homepage)
            self.rowAnimator.hoverLinkFilter.link_rect = QRect(
                left + self._titleFM['website'] + 2, position + 2 + 32,
                rect.width(), rect.height())

            p.setPen(option.palette.color(QPalette.Link))
            p.drawText(left + self._titleFM['website'], position, width,
                       rect.height(), Qt.TextSingleLine, homepage)
            p.setPen(foregroundColor)

            # Package Detail Version
            position += rect.height()

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE, position, width - textInner,
                       itemHeight / 2, Qt.AlignLeft, self._titles['release'])

            p.setFont(self.normalDetailFont)
            rect = self.normalDetailFontFM.boundingRect(
                option.rect, Qt.TextWordWrap, version.toString())
            p.drawText(left + self._titleFM['release'], position, width,
                       rect.height(), Qt.TextWordWrap, version.toString())

            if not installedVersion == '':
                position += rect.height()

                p.setFont(self.boldDetailFont)
                p.drawText(left + ICON_SIZE, position, width - textInner,
                           itemHeight / 2, Qt.AlignLeft,
                           self._titles['installVers'])

                p.setFont(self.normalDetailFont)
                rect = self.normalDetailFontFM.boundingRect(
                    option.rect, Qt.TextWordWrap, installedVersion)
                p.drawText(left + self._titleFM['installVers'], position,
                           width, rect.height(), Qt.TextWordWrap,
                           installedVersion)

            # Package Detail Repository
            repository = index.model().data(index, RepositoryRole).toString()
            if not repository == '':
                repository = self.tr(
                    'Unknown') if repository == 'N/A' else repository
                position += rect.height()

                p.setFont(self.boldDetailFont)
                p.drawText(left + ICON_SIZE, position, width - textInner,
                           itemHeight / 2, Qt.AlignLeft,
                           self._titles['repository'])

                p.setFont(self.normalDetailFont)
                p.drawText(left + self._titleFM['repository'], position, width,
                           itemHeight / 2, Qt.TextWordWrap, repository)

            # Package Detail Size
            position += rect.height()

            p.setFont(self.boldDetailFont)
            p.drawText(left + ICON_SIZE, position, width - textInner,
                       itemHeight / 2, Qt.AlignLeft, self._titles['size'])

            p.setFont(self.normalDetailFont)
            p.drawText(left + self._titleFM['size'], position, width,
                       itemHeight / 2, Qt.TextWordWrap, size)
            position += rect.height()
            self.rowAnimator.max_height = position - top + 8

            # Package More info button
            opt = QStyleOptionViewItem(option)

            buttonStyle = QStyleOptionButton()
            if option.state & QStyle.State_MouseOver or option.state & QStyle.State_HasFocus:
                buttonStyle.state |= QStyle.State_HasFocus
            buttonStyle.state |= QStyle.State_Enabled
            buttonStyle.text = self.tr("Details")

            buttonStyle.rect = QRect(width - 100, position - 22, 100, 22)

        p.end()

        # FIXME
        # if option.state & QStyle.State_HasFocus and self.animatable:
        #     option.state |= QStyle.State_MouseOver
        # Use Plastique style to draw focus rect like MouseOver effect of Oxygen.
        # self.plastik.drawPrimitive(QStyle.PE_FrameLineEdit, option, painter, None)

        if not self.rowAnimator.running() and buttonStyle:
            if self.show_details_button and (installed or config.USE_APPINFO):
                PackageDelegate.AppStyle().drawControl(QStyle.CE_PushButton,
                                                       buttonStyle, painter,
                                                       None)
                self.rowAnimator.hoverLinkFilter.button_rect = QRect(
                    buttonStyle.rect)

        painter.drawPixmap(option.rect.topLeft(), pixmap)
        del pixmap
示例#58
0
    def __paintEventNoStyle(self):
        p = QPainter(self)
        opt = QStyleOptionToolButton()
        self.initStyleOption(opt)

        fm = QFontMetrics(opt.font)
        palette = opt.palette

        # highlight brush is used as the background for the icon and background
        # when the tab is expanded and as mouse hover color (lighter).
        brush_highlight = palette.highlight()
        foregroundrole = QPalette.ButtonText
        if opt.state & QStyle.State_Sunken:
            # State 'down' pressed during a mouse press (slightly darker).
            background_brush = brush_darker(brush_highlight, 110)
            foregroundrole = QPalette.HighlightedText
        elif opt.state & QStyle.State_MouseOver:
            background_brush = brush_darker(brush_highlight, 95)
            foregroundrole = QPalette.HighlightedText
        elif opt.state & QStyle.State_On:
            background_brush = brush_highlight
            foregroundrole = QPalette.HighlightedText
        else:
            # The default button brush.
            background_brush = palette.button()

        rect = opt.rect

        icon_area_rect = QRect(rect)
        icon_area_rect.setRight(int(icon_area_rect.height() * 1.26))

        text_rect = QRect(rect)
        text_rect.setLeft(icon_area_rect.right() + 10)

        # Background  (TODO: Should the tab button have native
        # toolbutton shape, drawn using PE_PanelButtonTool or even
        # QToolBox tab shape)

        # Default outline pen
        pen = QPen(palette.color(QPalette.Mid))

        p.save()
        p.setPen(Qt.NoPen)
        p.setBrush(QBrush(background_brush))
        p.drawRect(rect)

        # Draw the background behind the icon if the background_brush
        # is different.
        if not opt.state & QStyle.State_On:
            p.setBrush(brush_highlight)
            p.drawRect(icon_area_rect)
            # Line between the icon and text
            p.setPen(pen)
            p.drawLine(icon_area_rect.topRight(), icon_area_rect.bottomRight())

        if opt.state & QStyle.State_HasFocus:
            # Set the focus frame pen and draw the border
            pen = QPen(QColor(FOCUS_OUTLINE_COLOR))
            p.setPen(pen)
            p.setBrush(Qt.NoBrush)
            # Adjust for pen
            rect = rect.adjusted(0, 0, -1, -1)
            p.drawRect(rect)

        else:
            p.setPen(pen)
            # Draw the top/bottom border
            if self.position == QStyleOptionToolBox.OnlyOneTab or \
                    self.position == QStyleOptionToolBox.Beginning or \
                    self.selected & \
                        QStyleOptionToolBox.PreviousIsSelected:

                p.drawLine(rect.topLeft(), rect.topRight())

            p.drawLine(rect.bottomLeft(), rect.bottomRight())

        p.restore()

        p.save()
        text = fm.elidedText(opt.text, Qt.ElideRight, text_rect.width())
        p.setPen(QPen(palette.color(foregroundrole)))
        p.setFont(opt.font)

        p.drawText(text_rect,
                   int(Qt.AlignVCenter | Qt.AlignLeft) | \
                   int(Qt.TextSingleLine),
                   text)

        if not opt.icon.isNull():
            if opt.state & QStyle.State_Enabled:
                mode = QIcon.Normal
            else:
                mode = QIcon.Disabled
            if opt.state & QStyle.State_On:
                state = QIcon.On
            else:
                state = QIcon.Off
            icon_area_rect = icon_area_rect
            icon_rect = QRect(QPoint(0, 0), opt.iconSize)
            icon_rect.moveCenter(icon_area_rect.center())
            opt.icon.paint(p, icon_rect, Qt.AlignCenter, mode, state)
        p.restore()
示例#59
0
def cvt_vtr(self):
    QSWATMOD_path_dict = self.dirs_and_paths()
    selectedVector = self.dlg.comboBox_vector_lyrs.currentText()
    layer = QgsProject.instance().mapLayersByName(str(selectedVector))[0]

    # Find .dis file and read number of rows, cols, x spacing, and y spacing (not allowed to change)
    for filename in glob.glob(str(QSWATMOD_path_dict['SMfolder']) + "/*.dis"):
        with open(filename, "r") as f:
            data = []
            for line in f.readlines():
                if not line.startswith("#"):
                    data.append(line.replace('\n', '').split())
        nrow = int(data[0][1])
        ncol = int(data[0][2])
        delr = float(data[2][1])  # is the cell width along rows (y spacing)
        delc = float(
            data[3][1])  # is the cell width along columns (x spacing).

    # get extent
    ext = layer.extent()
    xmin = ext.xMinimum()
    xmax = ext.xMaximum()
    ymin = ext.yMinimum()
    ymax = ext.yMaximum()
    extent = "{a},{b},{c},{d}".format(a=xmin, b=xmax, c=ymin, d=ymax)

    fdnames = [
        field.name() for field in layer.dataProvider().fields()
        if not (field.name() == 'fid' or field.name() == 'id'
                or field.name() == 'xmin' or field.name() == 'xmax'
                or field.name() == 'ymin' or field.name() == 'ymax'
                or field.name() == 'grid_id' or field.name() == 'row'
                or field.name() == 'col' or field.name() == 'elev_mf')
    ]

    # Create swatmf_results tree inside
    root = QgsProject.instance().layerTreeRoot()
    if root.findGroup("swatmf_results"):
        swatmf_results = root.findGroup("swatmf_results")
    else:
        swatmf_results = root.insertGroup(0, "swatmf_results")

    if root.findGroup(selectedVector):
        rastergroup = root.findGroup(selectedVector)
    else:
        rastergroup = swatmf_results.insertGroup(0, selectedVector)
    per = 0
    self.dlg.progressBar_cvt_vtr.setValue(0)
    for fdnam in fdnames:
        QCoreApplication.processEvents()
        nodata = float(self.dlg.lineEdit_nodata.text())
        mincolor = self.dlg.mColorButton_min_rmap.color().name()
        maxcolor = self.dlg.mColorButton_max_rmap.color().name()
        name = fdnam
        name_ext = "{}.tif".format(name)
        output_dir = QSWATMOD_path_dict['SMshps']
        # create folder for each layer output
        rasterpath = os.path.join(output_dir, selectedVector)
        if not os.path.exists(rasterpath):
            os.makedirs(rasterpath)
        output_raster = os.path.join(rasterpath, name_ext)
        params = {
            'INPUT': layer,
            'FIELD': fdnam,
            'UNITS': 1,
            'WIDTH': delc,
            'HEIGHT': delr,
            'EXTENT': extent,
            'NODATA': nodata,
            'DATA_TYPE': 5,  #Float32
            'OUTPUT': output_raster
        }
        processing.run("gdal:rasterize", params)
        rasterlayer = QgsRasterLayer(output_raster,
                                     '{0} ({1})'.format(fdnam, selectedVector))
        QgsProject.instance().addMapLayer(rasterlayer, False)
        rastergroup.insertChildNode(0, QgsLayerTreeLayer(rasterlayer))
        stats = rasterlayer.dataProvider().bandStatistics(
            1, QgsRasterBandStats.All)
        rmin = stats.minimumValue
        rmax = stats.maximumValue
        fnc = QgsColorRampShader()
        lst = [
            QgsColorRampShader.ColorRampItem(rmin, QColor(mincolor)),
            QgsColorRampShader.ColorRampItem(rmax, QColor(maxcolor))
        ]
        fnc.setColorRampItemList(lst)
        fnc.setColorRampType(QgsColorRampShader.Interpolated)
        shader = QgsRasterShader()
        shader.setRasterShaderFunction(fnc)
        renderer = QgsSingleBandPseudoColorRenderer(rasterlayer.dataProvider(),
                                                    1, shader)
        rasterlayer.setRenderer(renderer)
        rasterlayer.triggerRepaint()

        # create image
        img = QImage(QSize(800, 800), QImage.Format_ARGB32_Premultiplied)
        # set background color
        # bcolor = QColor(255, 255, 255, 255)
        bcolor = QColor(255, 255, 255, 0)
        img.fill(bcolor.rgba())
        # create painter
        p = QPainter()
        p.begin(img)
        p.setRenderHint(QPainter.Antialiasing)
        # create map settings
        ms = QgsMapSettings()
        ms.setBackgroundColor(bcolor)

        # set layers to render
        flayer = QgsProject.instance().mapLayersByName(rasterlayer.name())
        ms.setLayers([flayer[0]])

        # set extent
        rect = QgsRectangle(ms.fullExtent())
        rect.scale(1.1)
        ms.setExtent(rect)

        # set ouptut size
        ms.setOutputSize(img.size())

        # setup qgis map renderer
        render = QgsMapRendererCustomPainterJob(ms, p)
        render.start()
        render.waitForFinished()
        # get timestamp
        p.drawImage(QPoint(), img)
        pen = QPen(Qt.red)
        pen.setWidth(2)
        p.setPen(pen)

        font = QFont()
        font.setFamily('Times')
        # font.setBold(True)
        font.setPointSize(18)
        p.setFont(font)
        # p.setBackground(QColor('sea green')) doesn't work
        p.drawText(QRect(0, 0, 800, 800), Qt.AlignRight | Qt.AlignBottom,
                   fdnam)
        p.end()

        # save the image
        img.save(os.path.join(rasterpath, '{:03d}_{}.jpg'.format(per, fdnam)))

        # Update progress bar
        per += 1
        progress = round((per / len(fdnames)) * 100)
        self.dlg.progressBar_cvt_vtr.setValue(progress)
        QCoreApplication.processEvents()
        self.dlg.raise_()

    duration = self.dlg.doubleSpinBox_ani_r_time.value()

    # filepaths
    fp_in = os.path.join(rasterpath, '*.jpg')
    fp_out = os.path.join(rasterpath, '{}.gif'.format(selectedVector))

    # https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html#gif
    fimg, *fimgs = [Image.open(f) for f in sorted(glob.glob(fp_in))]
    fimg.save(fp=fp_out,
              format='GIF',
              append_images=fimgs,
              save_all=True,
              duration=duration * 1000,
              loop=0,
              transparency=0)

    msgBox = QMessageBox()
    msgBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png'))
    msgBox.setWindowTitle("Coverted!")
    msgBox.setText(
        "Fields from {} were converted successfully!".format(selectedVector))
    msgBox.exec_()

    questionBox = QMessageBox()
    questionBox.setWindowIcon(QtGui.QIcon(':/QSWATMOD2/pics/sm_icon.png'))
    reply = QMessageBox.question(questionBox, 'Open?',
                                 'Do you want to open the animated gif file?',
                                 QMessageBox.Yes, QMessageBox.No)
    if reply == QMessageBox.Yes:
        os.startfile(os.path.join(rasterpath, '{}.gif'.format(selectedVector)))
示例#60
0
    def paintEvent(self, e):
        # Three valid cases: there are both a goal and current framerate
        # or either of them
        if self.fps is not None:
            if self.g_fps is not None:
                lb = min(self.fps_inertia_min, self.g_fps)
                ub = max(self.fps_inertia_max, self.g_fps)
            else:
                lb = self.fps_inertia_min
                ub = self.fps_inertia_max
        else:
            if self.g_fps is not None:
                lb = self.g_fps
                ub = self.g_fps
            else:
                return

        min_bound = np.floor(lb * 0.08) * 10
        max_bound = np.ceil(ub * 0.12) * 10
        delta_bound = max_bound - min_bound

        size = self.size()
        pad = 6
        w = size.width()
        h = size.height()

        p = QPainter()
        p.begin(self)
        fm = p.fontMetrics()

        if max_bound == min_bound:
            max_bound += 1

        limit_color = (200, 200, 200)
        goal_color = (80, 80, 80)

        if self.fps is not None and self.g_fps is not None and self.fps < self.g_fps:
            indicator_color = self.error_indicator_color
            shadow_color = self.error_indicator_shadow_color
        else:
            indicator_color = self.indicator_color
            shadow_color = self.indicator_shadow_color

        w_min = 0
        w_max = w - pad
        delta_w = w_max - w_min
        text_height = 16
        h_max = h - pad
        h_min = text_height + pad

        if self.set_fps and self.fps is not None:
            loc = (self.fps - min_bound) / delta_bound
            w_l = int(w_min + loc * delta_w)

            w_shadow_min = int(
                w_min + (self.fps_inertia_min - min_bound) * delta_w / delta_bound
            )
            w_shadow_max = int(
                w_min + (self.fps_inertia_max - min_bound) * delta_w / delta_bound
            )

            # Draw the inertially moving rectangle
            p.setPen(Qt.NoPen)
            p.setBrush(QBrush(QColor(*shadow_color)))

            l_corner = w_shadow_min
            w_rect = w_shadow_max - w_shadow_min
            p.drawRect(l_corner, h_min, w_rect, h_max - h_min)

            # Draw the indicator line
            p.setPen(QPen(QColor(*indicator_color)))

            p.drawLine(w_l, h_min, w_l, h_max + 5)

            val_str = "{:.1f}".format(self.fps)
            textw = fm.width(val_str)

            p.drawText(QPoint((w_max + w_min - textw) // 2, text_height), val_str)

        if self.g_fps is not None:
            # Draw the goal line
            loc_g = (self.g_fps - min_bound) / delta_bound
            p.setPen(QPen(QColor(*goal_color), 3))
            w_l = int(w_min + loc_g * delta_w)
            p.drawLine(w_l, h_min, w_l, h_max)

        # Draw the limits
        p.setPen(QPen(QColor(*limit_color)))
        p.drawLine(w_min, h_min, w_min, h_max)
        p.drawLine(w_max, h_min, w_max, h_max)

        p.drawText(QPoint(w_min, text_height), str(min_bound))
        maxst = str(max_bound)
        textw = fm.width(maxst)
        p.drawText(QPoint(w_max - textw, text_height), maxst)

        p.end()