def paintEvent(self, event: QPaintEvent): outerRadius = min(self.width(), self.height()) baseRect = QRectF(1, 1, outerRadius - 2, outerRadius - 2) buffer = QImage(outerRadius, outerRadius, QImage.Format_ARGB32_Premultiplied) p = QPainter(buffer) p.setRenderHint(QPainter.Antialiasing) self.rebuildDataBrushIfNeeded() self.drawBackground(p, buffer.rect()) self.drawBase(p, baseRect) if self.m_value > 0: delta = (self.m_max - self.m_min) / (self.m_value - self.m_min) else: delta = 0 self.drawValue(p, baseRect, self.m_value, delta) innerRect, innerRadius = self.calculateInnerRect(outerRadius) self.drawInnerBackground(p, innerRect) self.drawText(p, innerRect, innerRadius, self.m_value) p.end() painter = QPainter(self) painter.fillRect(baseRect, self.palette().window()) painter.drawImage(0, 0, buffer)
def assert_equal(self): __tracebackhide__ = True self.end() self.different_pixels = 0 actual_image: QImage = self.actual.device().toImage() expected_image: QImage = self.expected.device().toImage() diff_pixmap = QPixmap(actual_image.width(), actual_image.height()) diff = QPainter(diff_pixmap) try: white = QColor('white') diff.fillRect(0, 0, actual_image.width(), actual_image.height(), white) for x in range(actual_image.width()): for y in range(actual_image.height()): actual_colour = actual_image.pixelColor(x, y) expected_colour = expected_image.pixelColor(x, y) diff.setPen( self.diff_colour(actual_colour, expected_colour, x, y)) diff.drawPoint(x, y) finally: diff.end() diff_image: QImage = diff.device().toImage() display_diff(actual_image, diff_image, expected_image, self.different_pixels) if self.different_pixels == 0: return actual_image.save(str(self.work_dir / (self.name + '_actual.png'))) expected_image.save(str(self.work_dir / (self.name + '_expected.png'))) diff_path = self.work_dir / (self.name + '_diff.png') is_saved = diff_image.save(str(diff_path)) diff_width = self.diff_max_x - self.diff_min_x + 1 diff_height = self.diff_max_y - self.diff_min_y + 1 diff_section = QImage(diff_width, diff_height, QImage.Format_RGB32) diff_section_painter = QPainter(diff_section) try: diff_section_painter.drawPixmap(0, 0, diff_width, diff_height, QPixmap.fromImage(diff_image), self.diff_min_x, self.diff_min_y, diff_width, diff_height) finally: diff_section_painter.end() # To see an image dumped in the Travis CI log, copy the text from the # log, and paste it in test_pixmap_differ.test_decode_image. print(f'Encoded image of differing section ' f'({self.diff_min_x}, {self.diff_min_y}) - ' f'({self.diff_max_x}, {self.diff_max_y}):') print(encode_image(diff_section)) message = f'Found {self.different_pixels} different pixels, ' message += f'see' if is_saved else 'could not write' message += f' {diff_path.relative_to(Path(__file__).parent.parent)}.' assert self.different_pixels == 0, message
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))
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)
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)
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()
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())
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()
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())
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) center = QPointF(self.width() / 2, self.height() / 2) radius = self.radius() ellipse_line_width = self.radius() * 60 / 512 # big ellipse pen = QPen() pen.setWidth(ellipse_line_width) pen.setColor(self.color) painter.setPen(pen) painter.drawEllipse(center, radius - pen.width() / 2, radius - pen.width() / 2) # dots pen = QPen() pen.setColor(QColor(0, 0, 0, 0)) painter.setPen(pen) brush = QBrush() brush.setStyle(Qt.SolidPattern) dot_size = radius * 200 / 1024 color = copy.copy(self.color) self._change_color(painter, brush, color, 0) painter.drawEllipse( QPointF((self.width() - radius - ellipse_line_width / 2) / 2, self.height() / 2), dot_size, dot_size) self._change_color(painter, brush, color, 15) painter.drawEllipse(center, dot_size, dot_size) self._change_color(painter, brush, color, 30) painter.drawEllipse( QPointF((self.width() + radius + ellipse_line_width / 2) / 2, self.height() / 2), dot_size, dot_size)
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)
def assert_equal(self): __tracebackhide__ = True self.end() self.different_pixels = 0 actual_image: QImage = self.actual.device().toImage() expected_image: QImage = self.expected.device().toImage() diff_pixmap = QPixmap(actual_image.width(), actual_image.height()) diff = QPainter(diff_pixmap) try: white = QColor('white') diff.fillRect(0, 0, actual_image.width(), actual_image.height(), white) for x in range(actual_image.width()): for y in range(actual_image.height()): actual_colour = actual_image.pixelColor(x, y) expected_colour = expected_image.pixelColor(x, y) diff.setPen( self.diff_colour(actual_colour, expected_colour, x, y)) diff.drawPoint(x, y) finally: diff.end() diff_image: QImage = diff.device().toImage() display_diff(actual_image, diff_image, expected_image, self.different_pixels) if self.different_pixels == 0: return actual_image.save(str(self.work_dir / (self.name + '_actual.png'))) expected_image.save(str(self.work_dir / (self.name + '_expected.png'))) diff_path = self.work_dir / (self.name + '_diff.png') is_saved = diff_image.save(str(diff_path)) diff_width = self.diff_max_x - self.diff_min_x + 1 diff_height = self.diff_max_y - self.diff_min_y + 1 diff_section = QImage(diff_width, diff_height, QImage.Format_RGB32) diff_section_painter = QPainter(diff_section) try: diff_section_painter.drawPixmap(0, 0, diff_width, diff_height, QPixmap.fromImage(diff_image), self.diff_min_x, self.diff_min_y, diff_width, diff_height) finally: diff_section_painter.end() message = f'Found {self.different_pixels} different pixels.' assert self.different_pixels == 0, message
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
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()
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 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)
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()
def paintEvent(self, event): size = self.size() # draw background painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QColor(255, 255, 255, 255)) painter.setBrush(self.fill_color) painter.drawRect(0, 0, size.width(), size.height()) painter.end()
def paintEvent(self, event): super(Profile, self).paintEvent(event) # DRAW BACKGROUND IMAGE p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) image = QPixmap() image.load("res/img/back.jpg") image = image.scaled(self.width(), self.height(), Qt.IgnoreAspectRatio, Qt.SmoothTransformation) p.drawPixmap(self.rect(), image)
def setIcons(self) -> None: settings = QSettings() colored = str(settings.value('iconColors', 'True')) == 'True' self._icons: Dict[str, QIcon] = {} pixmap = QPixmap(str(getRuntimePath('resources/icons/dia.ico'))) painter = QPainter(pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(pixmap.rect(), QColor('#427aa1') if colored else QColor('#333333')) painter.end() self._icons['mod'] = QIcon(pixmap) pixmap = QPixmap(str(getRuntimePath('resources/icons/puzzle.ico'))) painter = QPainter(pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(pixmap.rect(), QColor('#aad576') if colored else QColor('#333333')) painter.end() self._icons['dlc'] = QIcon(pixmap) pixmap = QPixmap(str(getRuntimePath('resources/icons/folder.ico'))) painter = QPainter(pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(pixmap.rect(), QColor('#E55934') if colored else QColor('#333333')) painter.end() self._icons['bin'] = QIcon(pixmap) pixmap = QPixmap(str(getRuntimePath('resources/icons/patch.ico'))) painter = QPainter(pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(pixmap.rect(), QColor('#b08968') if colored else QColor('#333333')) painter.end() self._icons['pat'] = QIcon(pixmap) pixmap = QPixmap(str(getRuntimePath('resources/icons/question.ico'))) painter = QPainter(pixmap) painter.setCompositionMode(QPainter.CompositionMode_SourceIn) painter.fillRect(pixmap.rect(), QColor('#ffcf40') if colored else QColor('#333333')) painter.end() self._icons['udf'] = QIcon(pixmap)
def export_arr(self, frame_index: int): self.scene.update_frame(frame_index) img = QImage(self.video_data.width, self.video_data.height, QImage.Format_ARGB32) painter = QPainter() painter.begin(img) self.scene.render(painter) painter.end() shape = (img.height(), img.bytesPerLine() * 8 // img.depth(), 4) ptr = img.bits() arr = np.array(ptr, dtype=np.uint8).reshape(shape) arr = arr[..., :3] return arr
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 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
def show_synced(self, is_sync: bool) -> None: p1 = QPixmap(self.icon().pixmap(self.icon().actualSize(QSize(1024, 1024)))) p2 = self.get_icon(is_sync) mode = QPainter.CompositionMode_SourceOver s = p1.size().expandedTo(p2.size()) result = QPixmap(s) result.fill(Qt.transparent) painter = QPainter(result) painter.setRenderHint(QPainter.Antialiasing) painter.drawPixmap(QPoint(), p1) painter.setCompositionMode(mode) painter.drawPixmap(result.rect(), p2, p2.rect()) painter.end() self.setIcon(QIcon(result))
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)
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()
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)
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")
def main(): parser = parse_args() pov_file: Path = parser.pov_file stem = pov_file.stem shadow_stem = re.sub(r'-(\d+)$', r'-shadow-\1', stem) temp_file = pov_file.parent / (stem + '-temp.png') temp_shadow_file = pov_file.parent / (shadow_stem + '-temp.png') png_file = pov_file.parent / (shadow_stem + '.png') current_images = Path(__file__).parent.parent / 'shibumi_images' current_file = current_images / png_file.name if current_file.exists(): png_file = current_file args = ['povray', '-D', f'+I{pov_file}', '+V', '-W640', '-H480', '+ua', f'+O{temp_file}'] run(args, check=True) app = QApplication() images_path = Path(__file__).parent shadow_file = images_path / 'ball-r-shadow-1.png' shadow = QPixmap(str(shadow_file)) rendered = QPixmap(str(temp_file)) cropped = rendered.copy(120, 20, 400, 400) scaled = cropped.scaled(98, 102, Qt.KeepAspectRatio, Qt.SmoothTransformation) painter = QPainter(shadow) try: painter.drawPixmap(7, 2, scaled) finally: painter.end() assert app shadow.save(str(temp_shadow_file), 'png') temp_file.unlink() temp_shadow_file.rename(png_file) print(f'Generated {png_file} from {pov_file}.')
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, self.antialiased) painter.translate(self.width() / 2, self.height() / 2) for diameter in range(0, 256, 9): delta = abs((self.frameNo % 128) - diameter / 2) alpha = 255 - (delta * delta) / 4 - diameter if alpha > 0: painter.setPen(QPen(QColor(0, diameter / 2, 127, alpha), 3)) if self.floatBased: painter.drawEllipse( QRectF(-diameter / 2.0, -diameter / 2.0, diameter, diameter)) else: painter.drawEllipse( QRect(-diameter / 2, -diameter / 2, diameter, diameter))