Esempio n. 1
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
Esempio n. 2
0
    def drawBackground(self, painter: QPainter, rect: QRectF):
        currentColor = self.backgroundBrush().color()
        if currentColor != self.backgroundColor:
            self.setBackgroundBrush(QBrush(self.backgroundColor))

        super().drawBackground(painter, rect)

        if self._zoom <= self.gridZoomThreshold or not self.showGrid:
            return

        painter.setPen(QPen(self.gridColor, self.gridThickness))

        lines = []
        if self.gridSpacing.width() > 0:
            xStart = rect.left() - rect.left() % self.gridSpacing.width()
            while xStart <= rect.right():
                line = QLineF(xStart, rect.bottom(), xStart, rect.top())
                lines.append(line)
                xStart = xStart + self.gridSpacing.width()

        if self.gridSpacing.height() > 0:
            yStart = rect.top() - rect.top() % self.gridSpacing.height()
            while yStart <= rect.bottom():
                line = QLineF(rect.left(), yStart, rect.right(), yStart)
                lines.append(line)
                yStart = yStart + self.gridSpacing.height()

        painter.drawLines(lines)
Esempio n. 3
0
    def paint(self, painter: QPainter):

        brush = QBrush(QColor("#007430"))

        painter.setBrush(brush)
        painter.setPen(Qt.NoPen)
        painter.setRenderHint(QPainter.Antialiasing)

        itemSize = self.size()

        painter.drawRoundedRect(0, 0, itemSize.width(), itemSize.height() - 10, 10, 10)

        if self.rightAligned:
            points = [
                QPointF(itemSize.width() - 10.0, itemSize.height() - 10.0),
                QPointF(itemSize.width() - 20.0, itemSize.height()),
                QPointF(itemSize.width() - 30.0, itemSize.height() - 10.0),
            ]
        else:
            points = [
                QPointF(10.0, itemSize.height() - 10.0),
                QPointF(20.0, itemSize.height()),
                QPointF(30.0, itemSize.height() - 10.0),
            ]
        painter.drawConvexPolygon(points)
Esempio n. 4
0
    def image_display(self):
        """
        Update the ct_image to be displayed on the DICOM View.
        """
        # Lead CT
        ct_pixmaps = self.pt_ct_dict_container.get(
            "ct_pixmaps_" + self.slice_view)
        slider_id = self.slider.value()
        ct_image = ct_pixmaps[slider_id].toImage()

        # Load PT
        pt_pixmaps = self.pt_ct_dict_container.get(
            "pt_pixmaps_" + self.slice_view)
        m = float(len(pt_pixmaps)) / len(ct_pixmaps)
        pt_image = pt_pixmaps[int(m * slider_id)].toImage()

        # Get alpha
        alpha = float(self.alpha_slider.value() / 100)

        # Merge Images
        painter = QPainter()
        painter.begin(ct_image)
        painter.setOpacity(alpha)
        painter.drawImage(0, 0, pt_image)
        painter.end()

        # Load merged images
        merged_pixmap = QtGui.QPixmap.fromImage(ct_image)
        label = QtWidgets.QGraphicsPixmapItem(merged_pixmap)
        self.scene = QtWidgets.QGraphicsScene()
        self.scene.addItem(label)
Esempio n. 5
0
 def draw(self, painter: QPainter):
     super().draw(painter)
     pen = painter.pen()
     pen.setColor(QColor('darkgrey'))
     painter.setPen(pen)
     w = self.width
     h = self.height
     painter.drawLine(w//2, h*3//4, w*13//14, h*3//12)
Esempio n. 6
0
 def draw(self, painter: QPainter):
     super().draw(painter)
     w = self.width
     h = self.height
     length = int(self.width * 0.32)
     x = int(w * 0.28)
     y = int(h * 0.7)
     painter.drawLine(x, y, x + length, y - length)
def draw_text(expected: QPainter, x: int, y: int, text: str):
    window = expected.window()
    scene = QGraphicsScene(0, 0, window.width(), window.height())
    text_item = scene.addSimpleText(text)
    font = expected.font()
    text_item.setFont(font)
    center_text_item(text_item, x, y)
    scene.render(expected)
Esempio n. 8
0
 def draw(self, painter: QPainter):
     super().draw(painter)
     pen = painter.pen()
     pen.setColor(QColor('darkgrey'))
     painter.setPen(pen)
     w = self.width
     h = self.height
     x = int(w * 0.71)
     painter.drawLine(x, int(h * 0.48), x, int(h * 0.7))
Esempio n. 9
0
    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()
Esempio n. 10
0
 def create_painter(self) -> typing.Iterator[QPainter]:
     white = QColor('white')
     pixmap = QPixmap(self.width, self.height)
     pixmap.fill(white)
     painter = QPainter(pixmap)
     try:
         yield painter
     finally:
         painter.end()
Esempio n. 11
0
 def draw(self, painter: QPainter):
     super().draw(painter)
     pen = painter.pen()
     pen.setColor(QColor('darkgrey'))
     painter.setPen(pen)
     w = self.width
     h = self.height
     length = int(w * 0.2)
     x = int(w * 0.4)
     y = int(h * 0.58)
     painter.drawLine(x, y, x + length, y - length)
Esempio n. 12
0
File: main.py Progetto: KDAB/KDChart
    def slotPrintPreview(self):
        pix = QPixmap(1000, 200)
        pix.fill(Qt.white)

        painter = QPainter(pix)
        view.print(painter, pix.rect())
        painter.end()

        label = QLabel(this)
        label.setPixmap(pix)
        label.show()
Esempio n. 13
0
 def create_icon(player_colour: QColor) -> QPixmap:
     size = 200
     icon = QPixmap(size, size)
     icon.fill(Qt.transparent)
     painter = QPainter(icon)
     try:
         painter.setBrush(player_colour)
         pen = QPen()
         pen.setWidth(3)
         painter.setPen(pen)
         painter.drawEllipse(1, 1, size - 2, size - 2)
     finally:
         painter.end()
     return icon
Esempio n. 14
0
 def export(self, filename=None, add_margin=False):
     pw = QPdfWriter(filename)
     dpi = int(QApplication.primaryScreen().logicalDotsPerInch())
     pw.setResolution(dpi)
     pw.setPageMargins(QMarginsF(0, 0, 0, 0))
     size = QPageSize(self.getTargetRect().size())
     pw.setPageSize(size)
     painter = QPainter(pw)
     try:
         self.setExportMode(
             True, {
                 'antialias': True,
                 'background': self.background,
                 'painter': painter
             })
         painter.setRenderHint(QPainter.Antialiasing, True)
         painter.setRenderHint(QPainter.LosslessImageRendering, True)
         source_rect = self.getSourceRect()
         if add_margin:
             source_rect.setWidth(source_rect.width() + 25)
         self.getScene().render(painter, QRectF(self.getTargetRect()),
                                QRectF(source_rect))
     finally:
         self.setExportMode(False)
     painter.end()
Esempio n. 15
0
 def paintEvent(self, event):
     """ Paint the editor, offloading the work to the StarRating class. """
     painter = QPainter(self)
     self.starRating.paint(painter,
                           self.rect(),
                           self.palette(),
                           isEditable=True)
Esempio n. 16
0
    def paintEvent(self, event: QFrame.paintEvent):
        """
        Paint all shapes of the game

        """
        painter = QPainter(self)
        rect = self.contentsRect()
        #painter.begin(self)
        boardTop = rect.bottom() - self._boardHeight * self.get_square_height()

        self.drawGameBox(painter)

        for i in range(self._boardHeight):
            for j in range(self._boardWidth):
                shape = self.shapeAt(j, self._boardHeight - i - 1)

                if shape != TetrisFiguresEnum.NoShape:
                    self.drawSquare(painter,
                                    rect.left() + j * self.get_square_width(),
                                    boardTop + i * self.get_square_height(),
                                    shape)

        if self.curPiece.get_shape() != TetrisFiguresEnum.NoShape:

            for i in range(self.curPiece.length):
                x = self.curX + self.curPiece.get_x(i)
                y = self.curY - self.curPiece.get_y(i)
                self.drawSquare(
                    painter,
                    rect.left() + x * self.get_square_width(), boardTop +
                    (self._boardHeight - y - 1) * self.get_square_height(),
                    self.curPiece.get_shape())
Esempio n. 17
0
def create_blue_green_rect():
    pixmap = QPixmap(4, 2)
    painter = QPainter(pixmap)
    try:
        painter.fillRect(0, 0, 2, 2, QColor('blue'))
        painter.fillRect(2, 0, 2, 2, QColor('green'))
    finally:
        painter.end()
    return pixmap
Esempio n. 18
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)
Esempio n. 19
0
    def paintEvent(self, event):
        super(QtBubbleLabel, self).paintEvent(event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)  # 抗锯齿

        rectPath = QPainterPath()  # 圆角矩形

        height = self.height() - 8  # 往上偏移8
        rectPath.addRoundedRect(QRectF(0, 0, self.width(), height), 5, 5)
        x = self.width() / 5 * 4
        # 边框画笔
        painter.setPen(
            QPen(self.BorderColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        # 背景画刷
        painter.setBrush(self.BackgroundColor)
        # 绘制形状
        painter.drawPath(rectPath)
Esempio n. 20
0
def paint_with_opacity(pixmap: QPixmap, opacity: float):
    transparent_image = QImage(QSize(36, 36),
                               QImage.Format_ARGB32_Premultiplied)
    transparent_image.fill(Qt.transparent)
    painter = QPainter(transparent_image)
    painter.setOpacity(opacity)
    painter.drawPixmap(18 - pixmap.width() / 2, 18 - pixmap.height() / 2,
                       pixmap)
    painter.end()
    return QPixmap.fromImage(transparent_image)
Esempio n. 21
0
 def paintEvent(self, e):
     "(re)draw everything inside the rectangle associated with event e"
     if self.model is not None:
         # get the painting area:
         w = QPainter(self.viewport())
         f = self.font()
         w.setFont(f)
         # get rectangle that needs paint:
         r = e.rect()
         # get line indices for this rectangle:
         line0 = self.vb.value()
         h = self.line.height
         first = line0 + r.top() // h
         last = line0 + r.bottom() // h
         count = last - first
         # update drawing:
         self.paintlines(w, first, count, line0)
         self.paintframes(w)
         self.paintmap(w)
Esempio n. 22
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()
Esempio n. 23
0
    def paint_puzzle(self, writer: QPaintDevice):
        self.check_clues()
        painter = QPainter(writer)
        try:
            print_shuffler = ArtShuffler(self.art_shuffler.rows,
                                         self.art_shuffler.cols,
                                         writer,
                                         QRect(0, 0, writer.width(),
                                               round(writer.height() / 2)),
                                         clues=self.clues,
                                         row_clues=self.row_clues,
                                         column_clues=self.column_clues)
            print_shuffler.cells = self.art_shuffler.cells[:]
            print_shuffler.is_shuffled = self.art_shuffler.is_shuffled
            selected_pixmap = self.get_selected_pixmap()
            print_shuffler.draw(selected_pixmap, painter)

            print_shuffler.rect.moveTop(writer.height() / 2)
            print_shuffler.draw_grid(selected_pixmap, painter)
        finally:
            painter.end()
Esempio n. 24
0
 def paintEvent(self, event):
     """ Поскольку это полностью прозрачное фоновое окно, жесткая для поиска
         граница с прозрачностью 1 рисуется в событии перерисовывания, чтобы отрегулировать размер окна. """
     super(FramelessWindow, self).paintEvent(event)
     painter = QPainter(self)
     painter.setPen(QPen(QColor(255, 255, 255, 1), 2 * self.Margins))
     painter.drawRect(self.rect())
Esempio n. 25
0
    def paintEvent(self, event):
        super().paintEvent(event)
        rect = QLine(self.x0, self.y0, self.x1, self.y1)

        painter = QPainter(self)
        painter.setPen(QPen(Qt.red, 2, Qt.SolidLine))
        painter.drawLine(rect)
Esempio n. 26
0
    def paintEvent(self, event):
        """
        Paint the widget.
        """
        super(WaTorGraph, self).paintEvent(event)

        painter = QPainter(self)

        fish, sharks = self._world.stats()

        shark = self.helper_calc_y_pos(sharks)
        fish = self.helper_calc_y_pos(fish)

        draw = ImageDraw.Draw(self._image)
        draw.line([(self._prev_tick, self._prev_shark),
                   (self._tick, shark)], (0, 0, 255), 2)
        draw.line([(self._prev_tick, self._prev_fish),
                   (self._tick, fish)], (0, 255, 0), 2)

        painter.drawImage(QPoint(0, 0), ImageQt(self._image))
        painter.end()

        self._prev_tick = self._tick
        self._prev_shark = shark
        self._prev_fish = fish
        self._tick += 2

        if self._tick >= self._widget_size.width():
            self.reset()
Esempio n. 27
0
    def start(self, width: int, height: int,
              name: str) -> typing.Tuple[QPainter, QPainter]:
        """ Create painters for the actual and expected images.

        Caller must either call end() or assert_equal() to properly clean up
        the painters and pixmaps. Caller may either paint through the returned
        painters, or call the end() method and create a new painter on the
        same device. Order matters, though!
        """
        assert name not in self.names, f'Duplicate name: {name!r}.'
        self.names.add(name)
        self.name = name

        white = QColor('white')
        self.actual_pixmap = QPixmap(width, height)
        self.actual_pixmap.fill(white)
        self.actual = QPainter(self.actual_pixmap)
        self.expected_pixmap = QPixmap(width, height)
        self.expected_pixmap.fill(white)
        self.expected = QPainter(self.expected_pixmap)

        return self.actual, self.expected
    def paintEvent(self, event):
        painter = QPainter(self)
        output_size = QSize()

        if self.mode == Mode.PngMode:
            output_size = self.zoomed_image.size()
            output_rect = QRect(QPoint(), output_size)
            output_rect.translate(self.rect().center() - output_rect.center())
            painter.drawImage(output_rect.topLeft(), self.zoomed_image)

        elif self.mode == Mode.SvgMode:
            output_size = self.svgRenderer.defaultSize()
            if self.zoom_scale != ZOOM_ORIGINAL_SCALE:
                zoom = float(self.zoom_scale) / ZOOM_ORIGINAL_SCALE
                output_size.scale(output_size.width() * zoom,
                                  output_size.height() * zoom,
                                  Qt.IgnoreAspectRatio)

            output_rect = QRect(QPoint(), output_size)
            output_rect.translate(self.rect().center() - output_rect.center())
            self.svgRenderer.render(painter, output_rect)

        self.setMinimumSize(output_size)
Esempio n. 29
0
    def paintEvent(self, event):
        """
        Paint the widget.
        """
        super(WaTorWidget, self).paintEvent(event)

        painter = QPainter(self)

        for y in range(self._size.height()):
            for x in range(self._size.width()):
                pos = QPoint(x, y) * self._scale
                painter.drawPixmap(pos, self._water.pixmap)

        for pos, mob in self._world.mobs.items():
            painter.drawPixmap(pos * self._scale, mob.pixmap)

        painter.end()
Esempio n. 30
0
    def DrawWidget(self, Painter: QtGui.QPainter, Option, Index):
        state = Option.state

        if state & self._style.State_Enabled and state & self._style.State_Selected:
            # Selected
            color = QtGui.QColor(self._theme.get("ui-02"))
            border = QtGui.QColor(self._theme.get("ui-01"))

        elif state & self._style.State_Enabled and state & self._style.State_Active:
            # Normal
            color = QtGui.QColor(self._theme.get("ui-01"))
            border = QtGui.QColor(self._theme.get("ui-02"))

        elif state & self._style.State_Enabled:
            # Inactive
            color = QtGui.QColor(self._theme.get("ui-01"))
            border = QtGui.QColor(self._theme.get("ui-02"))

        else:
            # Disabled
            color = QtGui.QColor(self._theme.get("disabled-02"))
            border = QtGui.QColor(self._theme.get("disabled-02"))

        Painter.setPen(color)
        self._style.drawPrimitive(self._style.PE_PanelItemViewItem, Option, Painter, Option.widget)
        Painter.fillRect(Option.rect, (color))

        Painter.setPen(QtGui.QColor(self._theme.get("text-02")))
        items = self.getData(Index)
        self.DrawCover(Painter, Option)
        self.DrawTop(Painter, Option, items[0])
        self.DrawMid(Painter, Option, items[1])
        self.DrawBottom(Painter, Option, [items[2], items[3], items[4]])

        Painter.setPen(border)
        Painter.drawLine(QPoint(0, Option.rect.y() + 63), QPoint(Option.rect.width(), Option.rect.y() + 63))