示例#1
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,
                                     "PySide 2\nQt %s" % qVersion())
                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))
示例#2
0
 def draw_letters(self, cell_width: float, cell_height: float,
                  left_border: int, top_border: int, painter: QPainter):
     font = painter.font()
     font_size = round(top_border * 0.99)
     font.setPixelSize(font_size)
     painter.setFont(font)
     ascii_code = ord('A')
     for i in range(self.rows):
         for j in range(self.cols):
             letter = chr(ascii_code)
             x = round(left_border + j * cell_width)
             y = round(top_border + i * cell_height)
             w = round(cell_width)
             h = round(cell_height)
             if i == 0:
                 y = top_border - font_size
                 h = font_size
             elif i == self.rows - 1:
                 y = self.rect.height() - top_border
                 h = font_size
             elif j == 0:
                 x = left_border - font_size
                 w = font_size
             elif j == self.cols - 1:
                 x = self.rect.width() - left_border
                 w = font_size
             else:
                 x = y = w = h = 0
             if w != 0:
                 painter.drawText(x, y, w, h, Qt.AlignmentFlag.AlignCenter,
                                  letter)
             ascii_code += 1
示例#3
0
    def paintEvent(self, event: QtGui.QPaintEvent) -> None:
        painter = QPainter(self)
        #painter.setPen(QPen(Qt.blue, 1, Qt.DashLine))

        # Create transformation for text and other things that will be drawn
        transform = QTransform()
        # Rotation
        shiftX = self.width() // 2
        shiftY = self.height() // 2
        transform.translate(shiftX, shiftY)
        transform.rotate(self._rotate)
        transform.translate(-shiftX, -shiftY)

        # Scale, NOTICE! Scale change position of the text, i. e. size of frame (?)
        scale_x = self._scale[0] / 100
        scale_y = self._scale[1] / 100
        transform.scale(scale_x, scale_y)

        # Apply transformation
        painter.setTransform(transform)

        # Draw text
        painter.setFont(QFont('Times', 20, QFont.Bold))
        painter.setPen(
            QPen(
                QColor(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)),
                1
            )
        )
        # Because of the scale size of the frame is changed, recalculate size according to scale
        width_tr = int(self.width() * (1 / scale_x))
        height_tr = int(self.height() * (1 / scale_y))
        painter.drawText(0, 0, width_tr, height_tr, Qt.AlignCenter | Qt.AlignTop, self._text)

        # Update transformation variables
        self._rotate += self._addRotation
        self._scale[0] += self._addScale[0]
        self._scale[1] += self._addScale[1]
        # Check bounds and keep variable in the loop
        if self._rotate >= max(self._rotationBounds) or self._rotate <= min(self._rotationBounds):
            self._addRotation *= (-1)

        if self._scale[0] >= max(self._scaleBounds[0]) or self._scale[0] <= min(self._scaleBounds[0]):
            self._addScale[0] *= (-1)

        if self._scale[1] >= max(self._scaleBounds[1]) or self._scale[1] <= min(self._scaleBounds[1]):
            self._addScale[1] *= (-1)
示例#4
0
	def __init__(self):
		# Sidebar icons are 28x28 points. Should be at least 56x56 pixels for
		# HiDPI display compatibility. They will be automatically made theme
		# aware, so you need only provide a grayscale image, where white is
		# the color of the shape.
		icon = QImage(56, 56, QImage.Format_RGB32)
		icon.fill(0)

		# Render an "H" as the example icon
		p = QPainter()
		p.begin(icon)
		p.setFont(QFont("Open Sans", 56))
		p.setPen(QColor(255, 255, 255, 255))
		p.drawText(QRectF(0, 0, 56, 56), Qt.AlignCenter, "H")
		p.end()

		SidebarWidgetType.__init__(self, icon, "Hello")
示例#5
0
    def drawText(self, p: QPainter, innerRect: QRectF, innerRadius: float,
                 value: float):
        if not self.m_format:
            return

        f = QFont(self.font())
        f.setPixelSize(10)

        fm = QFontMetricsF(f)
        maxWidth = fm.width(self.valueToText(self.m_max))
        delta = innerRadius / maxWidth
        fontSize = f.pixelSize() * delta * 0.75
        f.setPixelSize(int(fontSize))
        p.setFont(f)

        textRect = QRectF(innerRect)
        p.setPen(self.palette().text().color())
        p.drawText(textRect, Qt.AlignCenter, self.valueToText(value))
示例#6
0
def render_display(display: GameDisplay,
                   painter: QPainter,
                   is_closed: bool = True):
    """ Check scene size, render, then clear scene.

    You have to clear the scene to avoid a crash after running several unit
    tests.
    :param display: display widget whose children contain a QGraphicsView to
        render.
    :param painter: a canvas to render on
    :param is_closed: True if the display should be closed after rendering. Be
        sure to close the display before exiting the test, if it contains any
        items with reference cycles back to the scene.
    """
    __tracebackhide__ = True
    try:
        for child in display.children():
            if isinstance(child, QGraphicsView):
                view = child
                break
        else:
            raise ValueError("No QGraphicsView in display's children.")

        view.grab()  # Force layout to recalculate, if needed.
        scene_size = view.contentsRect().size()
        device = painter.device()
        assert isinstance(device, QPixmap)
        painter_size = device.size()
        if scene_size != painter_size:
            display_size = find_display_size(display, view, painter_size)
            message = (f"Try resizing display to "
                       f"{display_size.width()}x{display_size.height()}.")
            painter.drawText(
                QRect(0, 0, painter_size.width(), painter_size.height()),
                Qt.AlignCenter | Qt.TextWordWrap,  # type: ignore
                message)
            return
        assert scene_size == painter_size
        view.scene().render(painter)
    finally:
        if is_closed:
            display.close()
示例#7
0
    def paintEvent(self, event):
        sineTable = [
            0, 38, 71, 92, 100, 92, 71, 38, 0, -38, -71, -92, -100, -92, -71,
            -38
        ]

        metrics = QFontMetrics(self.font())
        x = (self.width() - metrics.horizontalAdvance(self.text)) / 2
        y = (self.height() + metrics.ascent() - metrics.descent()) / 2
        color = QColor()

        painter = QPainter(self)
        for i in range(len(self.text)):
            index = (self.step + i) % 16
            color.setHsv((15 - index) * 16, 255, 191)
            painter.setPen(color)
            painter.drawText(x,
                             y - ((sineTable[index] * metrics.height()) / 400),
                             str(self.text[i]))
            x += metrics.horizontalAdvance(self.text[i])
示例#8
0
    def lineNumberAreaPaintEvent(self, event):
        painter = QPainter(self.line_number_area)
        painter.fillRect(event.rect(), Qt.lightGray)
        block = self.firstVisibleBlock()
        block_number = block.blockNumber()
        offset = self.contentOffset()
        top = self.blockBoundingGeometry(block).translated(offset).top()
        bottom = top + self.blockBoundingRect(block).height()

        while block.isValid() and top <= event.rect().bottom():
            if block.isVisible() and bottom >= event.rect().top():
                number = str(block_number + 1)
                painter.setPen(Qt.black)
                width = self.line_number_area.width()
                height = self.fontMetrics().height()
                painter.drawText(0, top, width, height, Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + self.blockBoundingRect(block).height()
            block_number += 1
示例#9
0
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.fillRect(self.rect(), Qt.black)

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

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

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

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

        painter.setPen(Qt.NoPen)
        painter.setBrush(QColor(0, 0, 0, 127))
        painter.drawRect((self.width() - textWidth) / 2 - 5, 0, textWidth + 10,
                         metrics.lineSpacing() + 5)
        painter.setPen(Qt.white)
        painter.drawText((self.width() - textWidth) / 2,
                         metrics.leading() + metrics.ascent(), text)
示例#10
0
        def paintEvent(self, event):
            painter = QPainter(self)
            painter.fillRect(event.rect(), self.numberBarColor)

            block = self.editor.firstVisibleBlock()

            # Iterate over all visible text blocks in the document.
            while block.isValid():
                blockNumber = block.blockNumber()
                block_top = self.editor.blockBoundingGeometry(
                    block).translated(self.editor.contentOffset()).top()

                # Check if the position of the block is out side of the visible area.
                if not block.isVisible() or block_top >= event.rect().bottom():
                    break

                # We want the line number for the selected line to be bold.
                if blockNumber == self.editor.textCursor().blockNumber():
                    self.font.setBold(True)
                    painter.setPen(bnstyles["blockSelected"])
                else:
                    self.font.setBold(False)
                    painter.setPen(bnstyles["blockNormal"])
                painter.setFont(self.font)

                # Draw the line number right justified at the position of the line.
                paint_rect = QRect(0, block_top, self.width(),
                                   self.editor.fontMetrics().height())
                painter.drawText(paint_rect, Qt.AlignLeft,
                                 str(blockNumber + 1))

                block = block.next()

            painter.end()

            QWidget.paintEvent(self, event)
示例#11
0
def centered_text(painter: QtGui.QPainter, pos: QPointF, text: str):
    rect = QRectF(pos.x() - 32767 * 0.5, pos.y() - 32767 * 0.5, 32767, 32767)
    painter.drawText(rect, QtGui.Qt.AlignCenter, text)
示例#12
0
文件: Radio.py 项目: skpzk/Sharm
    def paintEvent(self, ev):
        # print("Radio paintEventCalled")
        # print("size =", self.paintSize)

        opt = QStyleOption()
        opt.initFrom(self)
        painter = QPainter(self)

        # print("minimum size : ", self.minimumSize())
        # print("radio: hasHforW : ", self.hasHeightForWidth())
        # print("radio: size : ", self.size())
        # print("radio : minimumSizeHint() :", self.minimumSizeHint())

        # s = self.style()

        # s.drawPrimitive(QStyle.PE_Widget, opt, painter, self)

        # self.computeSize()
        size = self.paintSize
        # size = np.min([1/8 * self.width(), self.height()/4])

        fontsizefactor = self.fontsizefactor

        linewidth = 1

        painter.setRenderHint(QPainter.Antialiasing)

        pointColor = QColor(painter.pen().color())
        bgColor = QColor(painter.background().color())
        # bgColor = QColor("white")

        painter.setBrush(QBrush(QColor("transparent")))
        painter.setPen(QPen(QColor(pointColor), linewidth))
        # painter.setBackgroundMode(Qt.TransparentMode)

        center = QtCore.QPoint(int(self.width() / 2), int(self.height() / 2))
        self.center = center
        self.radius = size

        painter.drawEllipse(center, size, size)

        margin = .4 * size

        # painter.drawRect(text_rect)
        # self.text()

        fontsize = size * fontsizefactor
        # self.fontsize = fontsize

        f = painter.font()
        f.setPointSizeF(fontsize)
        painter.setFont(f)

        text_rect = QRectF(center.x() + size + margin,
                           center.y() - fontsize, 100, 2 * fontsize)
        # painter.drawRect(text_rect)
        painter.drawText(text_rect, Qt.AlignLeft | Qt.AlignVCenter,
                         self.text())

        self.textRect = text_rect

        if self.isChecked():
            painter.setBrush(QBrush(QColor(int(colors[self._ID], 0))))
            # painter.setPen(QPen(Qt.NoPen))
            painter.drawEllipse(center, size, size)

        # painter.drawLine(QtCore.QPointF(self.width()/2, 0), QtCore.QPointF(self.width()/2, self.height()))

        pass
示例#13
0
class ScreenSelection(QtWidgets.QGroupBox):
    def __init__(self, parent: DisplayCalibration):
        QtWidgets.QGroupBox.__init__(self,
                                     'Fullscreen selection (double click)')
        self.main = parent

        self.setSizePolicy(QtWidgets.QSizePolicy.Policy.Expanding,
                           QtWidgets.QSizePolicy.Policy.Expanding)

        self.painter = QPainter()

    def mouseDoubleClickEvent(self, ev, *args, **kwargs):
        for screen_id, screen_coords in enumerate(
                self._get_widget_screen_coords()):
            rect = QtCore.QRectF(*screen_coords)

            if not rect.contains(QtCore.QPoint(ev.pos().x(), ev.pos().y())):
                continue

            print(f'Set display to fullscreen on screen {screen_id}')

            screen = access.application.screens()[screen_id]
            px_ratio = screen.devicePixelRatio()
            self.main.global_settings.screen_id.set_value(screen_id)
            self.main.global_settings.win_x_pos.set_value(
                screen.geometry().x())
            self.main.global_settings.win_y_pos.set_value(
                screen.geometry().y())
            self.main.global_settings.win_width.set_value(
                int(screen.geometry().width() * px_ratio))
            self.main.global_settings.win_height.set_value(
                int(screen.geometry().height() * px_ratio))

            access.application.processEvents()

    @staticmethod
    def _get_norm_screen_coords() -> np.ndarray:

        # Get connected screens
        avail_screens = access.application.screens()

        # Calculate total display area bounding box
        area = [[
            s.geometry().width() * s.devicePixelRatio(),
            s.geometry().height() * s.devicePixelRatio()
        ] for s in avail_screens]
        area = np.sum(area, axis=0)

        xmin = np.min([s.geometry().x() for s in avail_screens])
        ymin = np.min([s.geometry().y() for s in avail_screens])

        # Define normalization functions
        xnorm = lambda x: (x - xmin) / area[0]
        ynorm = lambda y: (y - ymin) / area[1]

        # Add screen dimensions
        screens = []
        for s in avail_screens:
            g = s.geometry()
            screens.append([
                xnorm(g.x() * s.devicePixelRatio()),  # x
                ynorm(g.y() * s.devicePixelRatio()),  # y
                xnorm(g.width() * s.devicePixelRatio()),  # width
                ynorm(g.height() * s.devicePixelRatio())
            ])  # height

        return np.array(screens)

    def _get_widget_screen_coords(self):
        s = self._get_norm_screen_coords()
        s[:, 0] *= self.size().width()
        s[:, 1] *= self.size().height()
        s[:, 2] *= self.size().width()
        s[:, 3] *= self.size().height()

        return s.astype(int)

    def paintEvent(self, QPaintEvent):

        for i, screen in enumerate(self._get_widget_screen_coords()):

            rect = QtCore.QRect(*screen)

            self.painter.begin(self)

            self.painter.setBrush(QtCore.Qt.BrushStyle.Dense4Pattern)
            self.painter.drawRect(rect)

            self.painter.setPen(QColor(168, 34, 3))
            self.painter.setFont(QFont('Decorative', 30))
            self.painter.drawText(rect, QtCore.Qt.AlignmentFlag.AlignCenter,
                                  str(i))

            self.painter.end()
示例#14
0
文件: Patchpoint.py 项目: skpzk/Sharm
    def paintEvent(self, pe) -> None:

        mainradius, fontsizefactor, center_x, center_y_pp, width = self.computeCenter(
        )

        painter = QPainter(self)
        # So that we can use the background color
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Smooth out the circle
        painter.setRenderHint(QPainter.Antialiasing)
        # Use background color
        textBgColor = QColor(painter.background().color())
        # print("bgcolor = ", bgColor)
        bgColor = QColor("transparent")
        pointColor = QColor(painter.pen().color())

        self.pointColor = pointColor
        self.bgColor = textBgColor

        alpha = 150

        if self.parent().displayPp == 'all' or self.parent(
        ).displayPp == self.io:
            pointColor.setAlpha(255)
        else:
            pointColor.setAlpha(alpha)

        # draw text
        if not self._hasFixedFontSize:
            fontsize = mainradius * fontsizefactor
        else:
            fontsize = self._fixedFontSize
        self.fontsize = fontsize
        textRect_ = QtCore.QRectF(0, center_y_pp - mainradius - 2 * fontsize,
                                  width, 2 * fontsize)
        f = painter.font()
        f.setPointSizeF(fontsize)

        # self._io = 'in'
        if self.io == 'out':
            fm = QFontMetrics(f).boundingRect(self._text)
            # print("fm = ", fm)
            painter.setBrush(pointColor)
            painter.setPen(QPen(pointColor))
            painter.drawRect(
                QtCore.QRectF(center_x - fm.width() / 2,
                              center_y_pp - mainradius - 2 * fontsize,
                              fm.width(), fm.height()))
            painter.setPen(QPen(textBgColor))

        painter.setFont(f)
        painter.setBackgroundMode(Qt.TransparentMode)
        painter.drawText(textRect_, Qt.AlignHCenter | Qt.AlignTop, self._text)

        # draw hexagon
        painter.setBrush(bgColor)
        painter.setPen(pointColor)
        painter.drawPolygon(
            self.createPoly(6, mainradius, center_x, center_y_pp))

        # draw outer circle
        radius_outer = mainradius * .8
        if self.title not in implementedPatchPoints:
            painter.setBrush(QtGui.QBrush(QtGui.QColor(int("0x999999", 0))))
        painter.drawEllipse(QtCore.QPointF(center_x, center_y_pp),
                            radius_outer, radius_outer)

        # draw inner circle
        radius_inner = mainradius * .5
        # painter.setBrush(QBrush(pointColor))
        painter.setBrush(QColor(self._ppColor))
        painter.drawEllipse(QtCore.QPointF(center_x, center_y_pp),
                            radius_inner, radius_inner)
示例#15
0
    def paintEvent(self, event):

        paint = QPainter()
        paint.begin(self)
        paint.save()

        size = self.size()
        width = size.width()
        height = size.height()
        units = self.data.get('units')

        proportion = self.getProportion()

        horizontalOrientation = self.data.get('horizontal_orientation')

        if horizontalOrientation:

            rulerLength = width
            traceLengthLimit = height

        else:  # vertical orientation
            rulerLength = height
            traceLengthLimit = width

            paint.translate(width, 0)
            paint.rotate(90)

            # the length of the traces (lines)
        small = traceLengthLimit / 6
        medium = traceLengthLimit / 4
        large = traceLengthLimit / 3

        limit = rulerLength / proportion

        # draw less lines for centimeters
        if units == 'cm':
            step = 10

        else:
            step = 5

        # begin drawing
        fontSize = 10
        font = QFont('Serif', fontSize)
        fontMetrics = QFontMetrics(font)

        # draw background
        background = self.data.get('background_color')
        paint.fillRect(0, 0, rulerLength, traceLengthLimit, background)

        # draw the lines
        paint.setPen(self.data.get('lines_color'))
        paint.setFont(font)

        # the builtin range() doesn't support floats
        def float_range(current, end, rangeStep):
            while current < end:
                yield current
                current += rangeStep

            # we skip 0 and start in the first step, since there's no point in drawing the first line/text (it would appear cut off, since we're at the limit)

        for a in float_range(step, limit, step):

            position = a * proportion

            if (a % 100) == 0:
                lineLength = large

                if units == 'px':
                    text = '{}{}'.format(str(a), units)
                else:
                    text = '{}{}'.format(str(int(a / 100)), units)

                textWidth = fontMetrics.boundingRect(text).width()

                paint.drawText(position - textWidth / 2,
                               traceLengthLimit / 2 + fontSize / 2, text)

            elif (a % 50) == 0:
                lineLength = large

                # since 'cm' has a different step compared to the other units
                if units == 'cm':
                    lineLength = medium

            elif (a % 25) == 0:
                lineLength = medium

            else:
                lineLength = small

            paint.drawLine(position, 0, position, lineLength)
            paint.drawLine(position, traceLengthLimit, position,
                           traceLengthLimit - lineLength)

        # paint the division lines

        if self.data.get('division_lines'):
            paint.setPen(self.data.get('divisions_color'))
            halfPoint = rulerLength / 2
            quarterPoint = rulerLength / 4
            threeQuarterPoint = 3 / 4 * rulerLength

            paint.drawLine(quarterPoint, 0, quarterPoint, traceLengthLimit)
            paint.drawLine(halfPoint, 0, halfPoint, traceLengthLimit)
            paint.drawLine(threeQuarterPoint, 0, threeQuarterPoint,
                           traceLengthLimit)

        paint.restore()
        paint.end()
示例#16
0
    def paintEvent(self, ev):
        p = QPainter(self)
        p.setFont(self.font)
        #p.fillRect(self.rect(), QBrush(Qt.blue))

        length = len(self.display_data)

        # Reduce to the number of lines that are available in the data
        num_rows = length // self.bytes_per_line
        if length % self.bytes_per_line > 0:
            num_rows += 1

        for l in range(num_rows):
            p.setPen(self.label_color)
            # Draw address label
            # self.instance.get_local_label(self.start_offset + l * self.bytes_per_line)
            position_string = self.display_labels[l]
            p.drawText(QPoint(self.label_offset_x, (l + 1) * self.line_height),
                       position_string)

            for i in range(
                    0,
                    min(self.bytes_per_line,
                        length - self.bytes_per_line * l)):

                #virtual_address = self.start_offset + l*self.bytes_per_line + i

                p.setPen(self.byte_color)

                current_byte = self.display_data[i + l * self.bytes_per_line]
                if current_byte.background is not None:
                    p.setBackground(current_byte.background)
                    p.setBackgroundMode(Qt.OpaqueMode)

                p.drawText(
                    QPoint(self.label_length + i * self.byte_width,
                           (l + 1) * self.line_height), current_byte.text)
                p.setBackgroundMode(Qt.TransparentMode)

                # Draw selection rects
                if current_byte.is_selected:
                    p.setPen(self.selection_color)
                    p.drawRect(
                        # TODO make these offsets configurable/dependent on font?
                        self.label_length + i * self.byte_width - 3,
                        (l) * self.line_height + 3,
                        self.byte_width,
                        self.line_height)

                # Draw annotation underlines
                if len(current_byte.annotations) > 0:
                    y_offset = 0
                    for annotation in current_byte.annotations:
                        self.annotation_pen.setColor(annotation.color)
                        p.setPen(self.annotation_pen)
                        x = self.label_length + i * self.byte_width
                        y = (l + 1) * self.line_height + y_offset + 2
                        p.drawLine(x, y, x + self.byte_width, y)
                        y_offset += 2

                # Draw constraint pipes
                if len(current_byte.constraints) > 0:
                    enabled = False
                    for constraint in current_byte.constraints:
                        if constraint.enabled:
                            enabled = True
                            break
                    if enabled:
                        p.setPen(self.enabled_constraint_pen)
                    else:
                        p.setPen(self.disabled_constraint_pen)
                    x = self.label_length + i * self.byte_width - 2
                    y = (l) * self.line_height + 3
                    p.drawLine(x, y, x, y + self.line_height)
示例#17
0
    def paintEvent(self, pe) -> None:
        if not self.inhibit_paint:

            extent = 1.5 * np.pi
            offset = 1.25 * np.pi

            painter = QPainter(self)

            # So that we can use the background color
            painter.setBackgroundMode(Qt.OpaqueMode)

            # Smooth out the circle
            painter.setRenderHint(QPainter.Antialiasing)

            # Use background color
            bgColor = painter.background().color()
            painter.setBrush(painter.background())
            if self._text not in implementedKnobs:
                painter.setBrush(QtGui.QBrush(QtGui.QColor(int("0xcccccc",
                                                               0))))

            # Store color from stylesheet, pen will be overridden
            pointColor = QColor(painter.pen().color())

            # print(QDial.width(self), QDial.height(self))

            # draw widget borders
            pen = QPen(QColor(self._ringColor), 1)
            pen.setCapStyle(Qt.SquareCap)
            painter.setPen(pen)
            # uncomment the following line to draw outer rect
            # painter.drawRect(0, 0, np.floor(QDial.width(self)), QDial.height(self))

            # No border
            painter.setPen(QPen(Qt.NoPen))

            # the heignt of the widget is 2*radius + 2*fontsize1 + 2*fontsize2
            # where fontsize1 = .4radius and fontsize2 = .9*.4*radius
            # so QDial.height = radius * (2+.4*2+.4*.9*2)
            #

            fontsize1factor = .4
            fontsize2reduction = .9
            fontsize2factor = fontsize1factor * fontsize2reduction

            center_x = QDial.width(self) / 2.0
            center_y = QDial.height(self) / 2.0

            if not self._hasFixedSize:
                if not self._hasFixedFontSize:
                    radius = np.min(
                        (QDial.width(self) / 2. - self._knobMargin,
                         QDial.height(self) /
                         (2. + 2 * fontsize1factor + 2 * fontsize2factor) -
                         self._knobMargin))
                    radius = np.max((radius, 1))
                    # print("Radius = ", radius, ", height = ", QDial.height(self), ", width = ", QDial.width(self))
                    center_y = center_y - radius * (fontsize1factor +
                                                    fontsize2factor)
                else:
                    radius = np.min(
                        (QDial.width(self) / 2. - self._knobMargin,
                         (QDial.height(self) - 4 * self._fixedFontSize) / 2. -
                         self._knobMargin))
                    radius = np.max((radius, 1))
                    center_y = center_y - (self._fixedFontSize *
                                           (1 + fontsize2reduction))
            else:
                radius = self._fixedSize / 2.
                radius = np.max((radius, 1))
                center_y = center_y - radius * (fontsize1factor +
                                                fontsize2factor)

            self.radius = radius

            # Draw arc
            rectangle = QtCore.QRectF(center_x - radius, center_y - radius,
                                      2 * radius, 2 * radius)
            """The startAngle and spanAngle must be specified in 1/16th of a degree, 
			i.e. a full circle equals 5760 (16 * 360). 
			Positive values for the angles mean counter-clockwise 
			while negative values mean the clockwise direction. 
			Zero degrees is at the 3 o'clock position."""

            linewidth = radius / 30. * 2

            # linewidth = 1
            pen = QPen(QColor(self._ringColor), linewidth)
            pen.setCapStyle(Qt.RoundCap)
            # pen.setCapStyle(Qt.FlatCap)

            painter.setPen(pen)

            # adapt to linewidth to make it more pleasant to the eye
            capRadius = linewidth / 4
            angleCap = np.arcsin(capRadius / radius)

            start_deg = (90 - np.rad2deg(extent / 2)) + np.rad2deg(angleCap)
            start_16deg = start_deg * 16

            extent_deg = np.rad2deg(extent) - 2 * np.rad2deg(angleCap)
            extent_16deg = extent_deg * 16

            painter.drawArc(rectangle, start_16deg, extent_16deg)

            #draw inner circle
            pen = QPen(QColor(pointColor), linewidth)
            pen.setCapStyle(Qt.RoundCap)

            painter.setPen(pen)
            painter.setBrush(QtGui.QColor(bgColor))

            radius_inner = 15. / 20. * radius
            painter.drawEllipse(QtCore.QPointF(center_x, center_y),
                                radius_inner, radius_inner)

            self.center = QtCore.QPointF(center_x, center_y)
            """
			# Get ratio between current value and maximum to calculate angle
			if (param != NULL):
				if (param->value != this->value()) 
					param->setValue(this->value())
			"""
            ratio = (QDial.value(self) - QDial.minimum(self)) / (
                QDial.maximum(self) - QDial.minimum(self))

            # The maximum amount of degrees is 270, offset by 225
            angle = ratio * extent - offset

            # Draw the indicator
            painter.setBrush(QBrush(pointColor))

            a_y = center_y + np.sin(angle) * (radius - .1)
            a_x = center_x + np.cos(angle) * (radius - .1)

            pen = QPen(pointColor, linewidth)
            pen.setCapStyle(Qt.RoundCap)
            painter.setPen(pen)

            painter.drawLine(a_x, a_y, np.round(center_x), center_y)

            if not self._hasFixedFontSize:
                fontsize1 = radius * fontsize1factor
                if self.sizeType == 1 and fontsize1 != Knob.fontsize1:
                    Knob.fontsize1 = fontsize1
                else:
                    fontsize1 = Knob.fontsize1
                fontsize2 = fontsize1 * fontsize2reduction
            else:
                fontsize1 = self._fixedFontSize
                fontsize2 = fontsize1 * fontsize2reduction

            self.fontsize1 = fontsize1

            textRect_ = QtCore.QRectF(0, center_y + radius, QDial.width(self),
                                      2 * fontsize1)

            if self.coloredTitle:
                painter.setPen(QColor(int(titleColor, 0)))

            f = painter.font()
            f.setPointSizeF(fontsize1)
            painter.setFont(f)
            # painter.drawRect(textRect_)
            painter.drawText(textRect_, Qt.AlignHCenter | Qt.AlignTop,
                             self._text)
            # painter.drawText(textRect_, Qt.AlignHCenter | Qt.AlignTop, str(fontsize1))

            textRect_ = QtCore.QRectF(0, center_y + radius + fontsize1 * 2,
                                      QDial.width(self), 2 * fontsize2)

            if self.hasFocus():
                painter.setPen(QtGui.QColor("red"))

            f.setPointSizeF(fontsize2)
            painter.setFont(f)
            # painter.drawRect(textRect_)
            painter.drawText(textRect_, Qt.AlignHCenter | Qt.AlignTop,
                             str(QDial.value(self)))

            painter.end()