def paintEvent(self, e): qp = QPainter() qp.begin(self) qp.setRenderHint(QPainter.RenderHints.Antialiasing) self.drawBezierCurve(qp) qp.end()
def paintEvent(self, a0: QPaintEvent) -> None: # Initialise a painter to paint on this widget self.__painter = QPainter(self) # only draw the agent if the solverState is bound # if self.__solverState is not None: # it is a bound variable so draw it if self.__solverState is not None: agent = self.__drawAgent(self.__solverState) self.__painter.drawPath(agent) mazePath = self.__createMazePath() self.__painter.drawPath(mazePath) self.__painter.end()
def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setBrush(FILLBRUSH) qp.drawRect(self.rect()) # Show question if self.parent().alex: anheight = ANSWERHEIGHT * self.size().height() qp.drawLine( 0, (1 - ANSWERHEIGHT) * self.size().height(), self.size().width(), (1 - ANSWERHEIGHT) * self.size().height(), )
def paintEvent(self, event): """paints all shapes of the game""" painter = QPainter(self) rect = self.contentsRect() boardTop = rect.bottom() - Board.BoardHeight * self.squareHeight() for i in range(Board.BoardHeight): for j in range(Board.BoardWidth): shape = self.shapeAt(j, Board.BoardHeight - i - 1) if shape != Tetrominoe.NoShape: self.drawSquare(painter, rect.left() + j * self.squareWidth(), boardTop + i * self.squareHeight(), shape) if self.curPiece.shape() != Tetrominoe.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 + (Board.BoardHeight - y - 1) * self.squareHeight(), self.curPiece.shape())
def paintEvent(self, e): """Override QLabel::paintEvent to draw elided text.""" if self._elidemode == Qt.TextElideMode.ElideNone: super().paintEvent(e) else: e.accept() painter = QPainter(self) geom = self.geometry() painter.drawText( 0, 0, geom.width(), geom.height(), int(self.alignment()), self._elided_text, )
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) try: self.paint_background(painter) except Exception: pass finally: painter.end() QWidget.paintEvent(self, ev)
def paintEvent(self, ev): if not self.static_text or not self.static_text.text(): return p = QPainter(self) p.setRenderHint(QPainter.RenderHint.TextAntialiasing) # If text is too long too fit, fade it out at the end self.static_text.setTextWidth(self.rect().width()) sz = self.static_text.size() r = self.rect() p.drawStaticText(0, int(r.height() - sz.height()) // 2, self.static_text) if sz.width() > r.width(): g = QLinearGradient(QPointF(self.rect().topLeft()), QPointF(self.rect().topRight())) c = QColor(self.sb_background) c.setAlpha(0) g.setColorAt(0, c) g.setColorAt(0.8, c) g.setColorAt(1.0, self.sb_background) p.fillRect(self.rect(), QBrush(g)) p.end()
def paintEvent(self, ev): p = QPainter(self) c = color('tab tree background', None) if c: p.fillRect(ev.rect(), QColor(c)) p.end() QWidget.paintEvent(self, ev)
def paintEvent(self, event): QDialog.paintEvent(self, event) if not self.line.isNull(): painter = QPainter(self) pen = QPen(Qt.GlobalColor.red, 3) painter.setPen(pen) painter.drawLine(self.line)
def mouseMoveEvent(self, event): if self.xCache == None: self.xCache = event.position().x() self.yCache = event.position().y() else: painter = QPainter(self.canvas) pen = painter.pen() pen.setWidth(self.strokeWidth) pen.setColor(QColor(*self.color)) pen.setStyle(self.strokeStyle) painter.setPen(pen) painter.drawLine(self.xCache, self.yCache, event.position().x(), event.position().y()) painter.end() self.setPixmap(self.canvas) self.xCache = event.position().x() self.yCache = event.position().y()
def draw_round_arrow(center: Tuple[int, int], width: int, painter: QPainter, start_angle: int = -150, end_angle: int = 150, fix_arrow_head: bool = False, arrow_head_fix_width: int = 4, arrow_head_rel_width: float = 0.2, arrow_head_angle: float = 45, arrow_head_rotation: float = 10, filled_arrow_head: bool = False): painter.drawArc(round(center[0] - width / 2), round(center[1] - width / 2), width, width, start_angle * 16, (end_angle - start_angle) * 16) end = complex(*center) + rect(width / 2, -end_angle * pi / 180) if fix_arrow_head: arrow_head_width = arrow_head_fix_width else: arrow_head_width = arrow_head_rel_width * width direction = (end_angle - start_angle) direction /= abs(direction) arrow_head1 = end - direction * rect( arrow_head_width, -(end_angle - direction * arrow_head_rotation + 90 + arrow_head_angle) * pi / 180) arrow_head2 = end - direction * rect( arrow_head_width, -(end_angle - direction * arrow_head_rotation + 90 - arrow_head_angle) * pi / 180) end = complex_to_tuple_rounded(end) arrow_head1 = complex_to_tuple_rounded(arrow_head1) arrow_head2 = complex_to_tuple_rounded(arrow_head2) draw_arrow_p(end, end, arrow_head1, arrow_head2, painter, filled_arrow_head)
def missing_icon(): global _missing_icon if _missing_icon is None: p = QPixmap(ICON_SIZE, ICON_SIZE) p.fill(Qt.GlobalColor.transparent) painter = QPainter(p) pal = QApplication.instance().palette() painter.setPen( QPen(pal.color(QPalette.ColorRole.Text), 0, Qt.PenStyle.DashLine)) margin = 3 r = p.rect().adjusted(margin, margin, -margin, -margin) painter.drawRect(r) painter.end() _missing_icon = QIcon(p) return _missing_icon
def test_sanity(tmp_path): # Segfault test app = QApplication([]) ex = Example() assert app # Silence warning assert ex # Silence warning for mode in ("1", "RGB", "RGBA", "L", "P"): # to QPixmap im = hopper(mode) data = ImageQt.toqpixmap(im) assert isinstance(data, QPixmap) assert not data.isNull() # Test saving the file tempfile = str(tmp_path / f"temp_{mode}.png") data.save(tempfile) # Render the image qimage = ImageQt.ImageQt(im) data = QPixmap.fromImage(qimage) qt_format = QImage.Format if ImageQt.qt_version == "6" else QImage qimage = QImage(128, 128, qt_format.Format_ARGB32) painter = QPainter(qimage) image_label = QLabel() image_label.setPixmap(data) image_label.render(painter, QPoint(0, 0), QRegion(0, 0, 128, 128)) painter.end() rendered_tempfile = str(tmp_path / f"temp_rendered_{mode}.png") qimage.save(rendered_tempfile) assert_image_equal_tofile(im.convert("RGBA"), rendered_tempfile) # from QPixmap roundtrip(hopper(mode)) app.quit() app = None
def paintEvent(self, ev): r = self.rect() painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True) icon = get_icon('busy.svg' if self.running else DOWNLOAD_ICON_NAME) pmap = icon.pixmap(r.width(), r.height()) x = (r.width() - int(pmap.width() / pmap.devicePixelRatio())) // 2 y = (r.height() - int(pmap.height() / pmap.devicePixelRatio())) // 2 + 1 painter.drawPixmap(x, y, pmap)
def draw_arrow_p(start: Tuple[int, int], end: Tuple[int, int], arrow_head1: Tuple[int, int], arrow_head2: Tuple[int, int], painter: QPainter, filled_arrow_head: bool = False): # painter.setPen(color) painter.drawLine(*start, *end) if not filled_arrow_head: painter.drawLine(*end, *arrow_head1) painter.drawLine(*end, *arrow_head2) else: # brush0 = painter.pen().brush() # painter.setBrush(painter.pen().color()) path = QPainterPath() path.moveTo(*end) path.lineTo(*arrow_head1) path.lineTo(*arrow_head2) path.lineTo(*end) painter.drawPath(path)
def paintEvent(self, event): qp = QPainter() qp.begin(self) qp.setBrush(FILLBRUSH) parent = self.parent() pheight = parent.geometry().height() height = pheight * (1 - SCOREHEIGHT) width = height / CELLRATIO if not self.board.final: # Normal board for x in range(self.board.size[0]): for y in range(-1, self.board.size[1]): rel_pos = ( x * self.cellsize[0] + BORDERWIDTH / 2, (y + 1) * self.cellsize[1], ) cell = (x, y) qp.setPen(BORDERPEN) qp.setBrush(FILLBRUSH) cell_rect = QRectF(*rel_pos, *self.cellsize) text_rect = QRectF(cell_rect) text_rect.setX(cell_rect.x() + TEXTPADDING) text_rect.setWidth(cell_rect.width() - 2 * TEXTPADDING) qp.drawRect(cell_rect) if y == -1: # Categories qp.setPen(CATPEN) qp.setFont(CATFONT) qp.drawText( text_rect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, self.board.categories[x], ) else: # Questions q = self.board.get_question(*cell) if not q in self.game.completed_questions: qp.setPen(MONPEN) qp.setFont(MONFONT) if not self.board.dj: monies = gp.money1 else: monies = gp.money2 qp.drawText( text_rect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, "$" + str(q.value), ) else: # Final jeopardy qp.setBrush(FILLBRUSH) qp.drawRect(self.rect()) qp.setPen(CATPEN) qp.setFont(QUFONT) qurect = self.rect().adjusted(QUMARGIN, QUMARGIN, -2 * QUMARGIN, -2 * QUMARGIN) qp.drawText( qurect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, self.board.categories[0], )
def paint(self, painter: QPainter) -> None: pixel_ratio = Application.getInstance().getMainWindow( ).effectiveDevicePixelRatio() painter.scale(1 / pixel_ratio, 1 / pixel_ratio) if self._renderer: self._renderer.render(painter)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setOpacity(self.pixmap_opacity) painter.drawPixmap(0, 0, self.old_pixmap) painter.end()
def paintEvent(self, event): if (not self.m_displayedWhenStopped) and (not self.isAnimated()): return width = min(self.width(), self.height()) painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.Antialiasing) outerRadius = (width - 1) * 0.5 innerRadius = (width - 1) * 0.5 * 0.4375 capsuleHeight = outerRadius - innerRadius capsuleWidth = width * 3 / 32 capsuleRadius = capsuleWidth / 2 for i in range(0, 12): color = QtGui.QColor(self.m_color) if self.isAnimated(): color.setAlphaF(1.0 - (i / 12.0)) else: color.setAlphaF(0.2) painter.setPen(Qt.PenStyle.NoPen) painter.setBrush(color) painter.save() painter.translate(self.rect().center()) painter.rotate(self.m_angle - (i * 30.0)) width = -1 * capsuleWidth / 2 height = -1 * (innerRadius + capsuleHeight) painter.drawRoundedRect( round(width), round(height), round(capsuleWidth), round(capsuleHeight), capsuleRadius, capsuleRadius, ) painter.restore()
def paintEvent(self, event): h = self.geometry().height() w = self.geometry().width() qp = QPainter() qp.begin(self) qp.setBrush(FILLBRUSH) qp.drawRect(self.rect()) p = self.game.answering_player margin = self.__margin qp.setPen(SCOREPEN) qp.setFont(SCOREFONT) if self.winner: winnerrect = QRectF(0, NAMEHEIGHT + 2 * margin, w, 2 * NAMEHEIGHT) qp.drawText( winnerrect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, f"{self.winner.name} is the winner!", ) return namerect = QRectF(0, margin, w, NAMEHEIGHT) qp.drawText(namerect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, p.name) if self.info_level > 0: answerrect = QRectF(0, NAMEHEIGHT + 2 * margin, w, 2 * NAMEHEIGHT) finalanswer = (p.finalanswer if len(p.finalanswer.replace(" ", "")) > 0 else "_________") qp.drawText( answerrect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, finalanswer, ) if self.info_level > 1: wagerrect = QRectF(0, h - NAMEHEIGHT - margin, w, NAMEHEIGHT) qp.drawText( wagerrect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, f"{p.wager:,}", )
def rotated_by(self, pixmap, angle): ans = pixmap.copy() ans.fill(Qt.GlobalColor.transparent) p = QPainter(ans) p.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform) p.setRenderHint(QPainter.RenderHint.Antialiasing) sz = ans.size().width() / ans.devicePixelRatio() p.translate(sz // 2, sz // 2) p.rotate(angle) p.translate(-sz // 2, -sz // 2) p.drawPixmap(0, 0, pixmap) p.end() return ans
def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawWidget(qp) qp.end()
class MazeView(QWidget): __painter: QPainter __maze: MazeProtocol __keepAspectRatio: bool __solverState: Optional[MazeSolverState] = None onMazeSolverAgentUpdate = pyqtSignal(MazeSolverState) def __init__( self, minimumSize: QSize, maze: MazeProtocol, parent: Optional[QWidget] = None, keepAspectRatio: bool = True, *args: Tuple[Any, Any], **kwargs: Tuple[Any, Any], ): super().__init__(parent=parent, *args, **kwargs) self.__keepAspectRatio = keepAspectRatio self.__maze = maze self.setContentsMargins(0, 0, 0, 0) self.setMinimumSize(minimumSize) # connect the onMazeSolverAgentUpdate signal with our internal method self.onMazeSolverAgentUpdate.connect(self.__onMazeSolverAgentUpdate) def __onMazeSolverAgentUpdate(self, newState: MazeSolverState) -> None: self.__solverState = newState self.update() # self.__drawAgent(self.__solverState) def resizeEvent(self, a0: QResizeEvent) -> None: if self.__keepAspectRatio: # Force the widget to rezise with a 1:1 aspect ratio # first calculate the smallest size axis: smallestAxisSize = min(a0.size().width(), a0.size().height()) # set a newSize var with this as both the axes sizes newSize = QSize(smallestAxisSize, smallestAxisSize) # resize with this new 1:1 size self.resize(newSize) # force resizeEvent of super with implicitly modified resize return super().resizeEvent(a0) def paintEvent(self, a0: QPaintEvent) -> None: # Initialise a painter to paint on this widget self.__painter = QPainter(self) # only draw the agent if the solverState is bound # if self.__solverState is not None: # it is a bound variable so draw it if self.__solverState is not None: agent = self.__drawAgent(self.__solverState) self.__painter.drawPath(agent) mazePath = self.__createMazePath() self.__painter.drawPath(mazePath) self.__painter.end() def __drawAgent( self, solverState: MazeSolverState, ) -> QPainterPath: # solverAgentPainter = QPainter(self) # Calculate size of each cell to be able to draw to proper scale cellSize = ( self.width() / self.__maze.size.x, self.height() / self.__maze.size.y, ) solverAgent = QPainterPath() # draw the agent shape currentPosition = ( solverState.currentCell.x * cellSize[0], solverState.currentCell.y * cellSize[1], ) solverAgent.addEllipse( currentPosition[0], currentPosition[1], cellSize[0], cellSize[1], ) ### ### Draw the direction arrow of the solver ### # get the facing direction of the solver direction = solverState.facingDirection # calculte middle of agent solver sprite to draw from middleOfCircle = ( currentPosition[0] + cellSize[0] * 0.5, currentPosition[1] + cellSize[1] * 0.5, ) # calculate the XY of the edge of the circle that we want to move to (to the facing direction) # start by getting the middle of the circle and then changing it accordingly edgeOfCircle = [ middleOfCircle[0], middleOfCircle[1], ] if direction == AbsoluteDirection.north: # north, so take away half the circle size in the Y direction edgeOfCircle[1] -= cellSize[1] * 0.5 elif direction == AbsoluteDirection.south: # south, so add half the circle size in the Y direction edgeOfCircle[1] += cellSize[1] * 0.5 elif direction == AbsoluteDirection.west: # west, so take away half the circle size in the X direction edgeOfCircle[0] -= cellSize[0] * 0.5 elif direction == AbsoluteDirection.east: # east, so add half the circle size in the X direction edgeOfCircle[0] += cellSize[0] * 0.5 # move to the center of the circle solverAgent.moveTo( middleOfCircle[0], middleOfCircle[1], ) # draw a line from the center of the circle to the facing direction edge of the circle solverAgent.lineTo( edgeOfCircle[0], edgeOfCircle[1], ) return solverAgent def __createMazePath(self) -> QPainterPath: cellSize = ( self.width() / self.__maze.size.x, self.height() / self.__maze.size.y, ) path = QPainterPath(QPointF(0, 0)) # draw outline of maze path.addRect( 0, 0, self.width() - 1, self.height() - 1, ) for y in range(self.__maze.size.y): currentY = y * cellSize[1] for x in range(self.__maze.size.x): currentX = x * cellSize[0] # get the list of walls surrounding this cell thisCellsWalls: Set[ AbsoluteDirection] = self.__maze.getWallsOfCellAtCoordinate( XY(x, y)) # draw north and west walls only, because the next iterations will draw the south and east walls for us (don't wanna waste paint /s) if AbsoluteDirection.west in thisCellsWalls: path.moveTo(currentX, currentY) path.lineTo(currentX, currentY + cellSize[1]) if AbsoluteDirection.north in thisCellsWalls: path.moveTo(currentX, currentY) path.lineTo(currentX + cellSize[0], currentY) return path
def paintEvent(self, event): h = self.geometry().height() w = self.geometry().width() qp = QPainter() qp.begin(self) qp.setBrush(FILLBRUSH) qp.drawRect(QRectF(0, DIVIDERWIDTH, w, h)) qp.setBrush(DIVIDERBRUSH) dividerrect = QRectF(0, 0, w, DIVIDERWIDTH) qp.drawRect(dividerrect) # Light dividers num_lights = 9 light_width = w // num_lights light_padding = 3 ungrouped_rects = [ QRect( light_width * i + light_padding, light_padding, light_width - 2 * light_padding, DIVIDERWIDTH - 2 * light_padding, ) for i in range(num_lights) ] grouped_rects = [[ rect for j, rect in enumerate(ungrouped_rects) if abs(num_lights // 2 - j) == i ] for i in range(5)] qp.setBrush(LIGHTBRUSH) qp.setPen(LIGHTPEN) for i, rects in enumerate(grouped_rects): if i < self.__light_level: for rect in rects: qp.drawRect(rect) margin = 50 players = self.game.players sw = w // len(players) if self.game.current_round.final: highlighted_players = [ p for p in players if p not in self.game.wagered ] else: highlighted_players = [] ap = self.game.answering_player if ap: highlighted_players.append(ap) for i, p in enumerate(players): if p.score < 0: qp.setPen(HOLEPEN) else: qp.setPen(SCOREPEN) qp.setFont(SCOREFONT) qp.drawText( self.__scorerect(i), Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, f"{p.score:,}", ) namerect = QRectF(sw * i, h - NAMEHEIGHT, sw, NAMEHEIGHT) qp.setFont(NAMEFONT) qp.setPen(NAMEPEN) if p in highlighted_players: qp.setBrush(HIGHLIGHTBRUSH) qp.drawRect(namerect) qp.setPen(HIGHLIGHTPEN) qp.drawText( namerect, Qt.TextFlag.TextWordWrap | Qt.AlignmentFlag.AlignCenter, p.name, )
def get_masked_image(path, size=64, overlay_text=""): """ Returns a pixmap from an image file masked with a smooth circle. The returned pixmap will have a size of *size* × *size* pixels. :param str path: Path to image file. :param int size: Target size. Will be the diameter of the masked image. :param str overlay_text: Overlay text. This will be shown in white sans-serif on top of the image. :return: Masked image with overlay text. :rtype: QPixmap """ with open(path, "rb") as f: imgdata = f.read() imgtype = path.split(".")[-1] # Load image and convert to 32-bit ARGB (adds an alpha channel): image = QImage.fromData(imgdata, imgtype) image.convertToFormat(QImage.Format.Format_ARGB32) # Crop image to a square: imgsize = min(image.width(), image.height()) width = (image.width() - imgsize) / 2 height = (image.height() - imgsize) / 2 rect = QRect( round(width), round(height), imgsize, imgsize, ) image = image.copy(rect) # Create the output image with the same dimensions and an alpha channel # and make it completely transparent: out_img = QImage(imgsize, imgsize, QImage.Format.Format_ARGB32) out_img.fill(Qt.GlobalColor.transparent) # Create a texture brush and paint a circle with the original image onto # the output image: brush = QBrush(image) # Create texture brush painter = QPainter(out_img) # Paint the output image painter.setBrush(brush) # Use the image texture brush painter.setPen(Qt.PenStyle.NoPen) # Don't draw an outline painter.setRenderHint(QPainter.RenderHint.Antialiasing, True) # Use AA painter.drawEllipse(0, 0, imgsize, imgsize) # Actually draw the circle if overlay_text: # draw text font = QtGui.QFont("Arial Rounded MT Bold") font.setPointSize(imgsize * 0.4) painter.setFont(font) painter.setPen(Qt.GlobalColor.white) painter.drawText(QRect(0, 0, imgsize, imgsize), Qt.AlignmentFlag.AlignCenter, overlay_text) painter.end() # We are done (segfault if you forget this) # Convert the image to a pixmap and rescale it. Take pixel ratio into # account to get a sharp image on retina displays: pr = QtWidgets.QApplication.instance().devicePixelRatio() pm = QPixmap.fromImage(out_img) pm.setDevicePixelRatio(pr) size = int(pr * size) pm = pm.scaled( size, size, Qt.AspectRatioMode.KeepAspectRatio, Qt.TransformationMode.SmoothTransformation, ) return pm
def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawRectangles(qp) qp.end()
def paintEvent(self, event): qp = QPainter() qp.begin(self) self.drawText(event, qp) qp.end()
def paintEvent(self, event): qp = QPainter() qp.begin(self) if self.lit: qp.setBrush(HIGHLIGHTBRUSH) qp.drawRect(self.__answerbarrect) if self.arrowhints and self.parent().alex: qp.setBrush(CORRECTBRUSH) qp.drawRect(self.__correctrect) qp.setBrush(INCORRECTBRUSH) qp.drawRect(self.__incorrectrect) qp.setBrush(HIGHLIGHTBRUSH) qp.drawPixmap(self.__leftarrowrect, self.__leftarrowimage) qp.drawPixmap(self.__rightarrowrect, self.__rightarrowimage) if self.spacehints and self.parent().alex: qp.setBrush(HIGHLIGHTBRUSH) qp.drawPixmap(self.__leftarrowrect, self.__spaceimage) qp.drawPixmap(self.__rightarrowrect, self.__spaceimage)
def paintEvent(self, e): qp = QPainter() qp.begin(self) self.drawLines(qp) qp.end()
def paintEvent(self, ev): painter = QPainter(self) painter.setRenderHint(QPainter.RenderHint.TextAntialiasing) f = painter.font() f.setBold(True) f.setPixelSize(self.height() - 1) painter.setFont(f) painter.setPen(QColor('red' if self.is_enabled else 'green')) painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, 'Z') painter.end()