def draw_cursor(self, event_x, event_y, drawing_tool_radius, new_circle=False): """ Draws a blue circle where the user clicked. :param event_x: QGraphicsScene event attribute: event.scenePos().x() :param event_y: QGraphicsScene event attribute: event.scenePos().y() :param drawing_tool_radius: the current radius of the drawing tool :param new_circle: True when the circle object is being created rather than updated. """ self.draw_tool_radius = drawing_tool_radius self.current_cursor_x = event_x - self.draw_tool_radius self.current_cursor_y = event_y - self.draw_tool_radius if new_circle: self.cursor = QGraphicsEllipseItem(self.current_cursor_x, self.current_cursor_y, self.draw_tool_radius * 2, self.draw_tool_radius * 2) pen = QPen(QColor("blue")) pen.setWidth(0) self.cursor.setPen(pen) self.cursor.setZValue(1) self.addItem(self.cursor) elif self.cursor is not None: self.cursor.setRect(self.current_cursor_x, self.current_cursor_y, self.draw_tool_radius * 2, self.draw_tool_radius * 2)
def paintmap(self, surface): ww = surface.window().width() wh = surface.window().height() self.vb.setMaximum(self.qimg.height() - (wh // self.line.height)) self.line.x_map = ww - 32 r = QRect(self.line.x_map, 2, 32, wh - 4) surface.drawImage(r, self.qimg) factor = wh / self.qimg.height() pen = surface.pen() p = QPen(Qt.white) p.setCapStyle(Qt.RoundCap) p.setWidth(2) surface.setPen(p) l0 = self.vb.value() * factor l1 = l0 + (wh // self.line.height) * factor pad = 4 p1 = QPointF(self.line.x_map - pad, l0) p2 = QPointF(self.line.x_map - pad, l1) if l1 - l0 > 4: p.setWidth(2) surface.drawLine(p1, p2) surface.drawLine(p1, QPointF(self.line.x_map, l0)) surface.drawLine(p2, QPointF(self.line.x_map, l1)) else: p.setWidth(4) surface.drawLine(p1, p2) surface.setPen(pen)
def paintlines(self, surface, first, count, l0): "draws the data out of the model onto the qpainter surface" self.model.cur = first N = self.model.linesize h = self.line.height ww = surface.window().width() y = (first - l0) * h c0, c1 = brushes.xv_bg, brushes.xv_bg_alt pen = surface.pen() for address, data, txt in self.model.iterlines(count): # background rect (alternate) r = QRect(0, y, ww, h) surface.fillRect(r, c0) # address column: r.setWidth(self.line.x_hex) surface.drawText(r, Qt.AlignHCenter | Qt.AlignVCenter, "%08x" % address) # hex column: w = self.line.xb.width r.setWidth(w) r.translate(self.line.x_hex + self.line.pxpad, 0) C = self.highlight.get(address, [None] * N) for i, c in enumerate(C): try: s = "%02x" % (data[i]) except IndexError: break flg = Qt.AlignHCenter | Qt.AlignVCenter if c: surface.fillRect(r, c) surface.setPen(QPen(Qt.white)) surface.drawText(r, flg, s) surface.setPen(pen) r.translate(w, 0) # ascii column: w = self.line.xb.cw r.setX(self.line.x_txt + self.line.pxpad) r.setWidth(w) for i, c in enumerate(C): try: s = txt[i] except IndexError: break flg = Qt.AlignHCenter | Qt.AlignVCenter if c: surface.fillRect(r, c) surface.setPen(QPen(Qt.white)) surface.drawText(r, flg, s) surface.setPen(pen) r.translate(w, 0) # clear background endline: r.setX(self.line.x_end) r.setWidth(ww - self.line.x_end) surface.fillRect(r, brushes.xv_bg_alt) y += h c0, c1 = c1, c0
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 particle_pen(self, index: int): pen = QPen() colors = self.settings.list_value(default_settings.particle_color) colors = [QColor(c) for c in colors] pen.setColor(colors[index % len(colors)]) pen.setStyle(Qt.SolidLine) pen.setWidth(0) return pen
def drawValue(self, p: QPainter, baseRect: QRectF, value: float, delta: float): if value == self.m_min: return if self.m_barStyle == self.BarStyle.EXPAND: p.setBrush(self.palette().highlight()) p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth)) radius = (baseRect.height() / 2) / delta p.drawEllipse(baseRect.center(), radius, radius) return elif self.m_barStyle == self.BarStyle.LINE: p.setPen( QPen(self.palette().highlight().color(), self.m_dataPenWidth)) p.setBrush(Qt.NoBrush) if value == self.m_max: p.drawEllipse( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2)) else: arcLength = 360 / delta p.drawArc( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2), int(self.m_nullPosition * 16), int(-arcLength * 16)) return dataPath = QPainterPath() dataPath.setFillRule(Qt.WindingFill) if value == self.m_max: dataPath.addEllipse(baseRect) else: arcLength = 360 / delta dataPath.moveTo(baseRect.center()) dataPath.arcTo(baseRect, self.m_nullPosition, -arcLength) dataPath.lineTo(baseRect.center()) p.setBrush(self.palette().highlight()) p.setPen(QPen(self.palette().shadow().color(), self.m_dataPenWidth)) p.drawPath(dataPath)
def __init__(self): QMainWindow.__init__(self) self.series = QPieSeries() self.series.append('Jane', 1) self.series.append('Joe', 2) self.series.append('Andy', 3) self.series.append('Barbara', 4) self.series.append('Axel', 5) self.slice = self.series.slices()[1] self.slice.setExploded() self.slice.setLabelVisible() self.slice.setPen(QPen(Qt.darkGreen, 2)) self.slice.setBrush(Qt.green) self.chart = QChart() self.chart.addSeries(self.series) self.chart.setTitle('Simple piechart example') self.chart.legend().hide() self.chartView = QChartView(self.chart) self.chartView.setRenderHint(QPainter.Antialiasing) self.setCentralWidget(self.chartView)
def test_piece_hover_enter(pixmap_differ: PixmapDiffer): size = 240 with pixmap_differ.create_painters( size, size, 'tictactoe_piece_hover_enter') as (actual, expected): draw_square_grid(expected) expected.setBrush(TicTacToeDisplay.player1_colour) expected.drawEllipse(10, 10, 60, 60) colour = QColor(TicTacToeDisplay.player2_colour) expected.setBrush(colour) colour.setAlpha(127) expected.setBrush(colour) colour.setRgb(0, 0, 0, 127) pen = QPen(colour) expected.setPen(pen) expected.drawEllipse(90, 10, 60, 60) display = TicTacToeDisplay() board = TicTacToeState('''\ X.. ... ... ''') display.resize(324, 264) display.ui.game_display.grab() display.update_board(board) display.on_hover_enter(display.spaces[0][1]) render_display(display, actual)
def test_clicked(pixmap_differ: PixmapDiffer): actual: QPainter expected: QPainter with pixmap_differ.create_painters(280, 240, 'connect4_clicked') as (actual, expected): draw_grid(expected) expected.setBrush(Connect4Display.player1_colour) expected.drawEllipse(5, 205, 30, 30) colour = QColor(Connect4Display.player2_colour) colour.setAlpha(127) expected.setBrush(colour) colour.setRgb(0, 0, 0, 127) pen = QPen(colour) expected.setPen(pen) expected.drawEllipse(5, 45, 30, 30) display = Connect4Display() display.resize(372, 264) display.grab() # Force layout to recalculate. space = display.spaces[1][0] display.on_click(space) render_display(display, actual)
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)
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): 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 __init__(self, sug=None): super().__init__() p = QPen() p.setColor(QColor("red")) self.addLine(-5, 0, 5, 0, p) self.addLine(0, -5, 0, 5, p) self.sug = sug if self.sug: from grandalf.routing import route_with_lines self.sug.route_edge = route_with_lines self.sug.dx, self.sug.dy = 5, 5 self.sug.dirvh = 0 for n in self.sug.g.sV: self.connect_add(n.view) for e in self.sug.g.sE: e.view = Edge_basic(e.v[0].view.obj, e.v[1].view.obj) self.addItem(e.view)
def paint(self, painter, option, widget=None): """ Paint the node in the graphic view. """ painter.setPen(QPen(QColor(128, 128, 128), 1.0, Qt.SolidLine)) for cell_rect in self.cell_rects(): painter.drawRect(cell_rect) if self.isSelected(): painter.setRenderHint(QPainter.Antialiasing) painter.setBrush(QBrush(QColor(255, 255, 255, 255))) painter.setPen( QPen(QColor(0, 0, 0, 255), 1.0, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin) ) for handle, rect in self.handles.items(): if self.selected_handle is None or handle == self.selected_handle: painter.drawEllipse(rect)
def paint(self, painter, option, widget=None): qgp = self.getqgp() pen = QPen() pen.setWidth(2) qgp.setPen(pen) qgp.setBrush(QBrush(Qt.NoBrush)) painter.setClipRect(option.exposedRect) qgp.paint(painter, option, widget) lastp = self.points[-1] angle = radians(qgp.path().angleAtPercent(1.0)) angle = angle + pi p = lastp + QPointF( cos(angle - pi / 6.0) * 10, -sin(angle - pi / 6.0) * 10) q = lastp + QPointF( cos(angle + pi / 6.0) * 10, -sin(angle + pi / 6.0) * 10) painter.setBrush(QBrush(QColor("black"))) self.head = QPolygonF([lastp, p, q]) painter.drawPolygon(self.head)
def penChanged(self): width = self.penWidthSpinBox.value() style = Qt.PenStyle(self.penStyleComboBox.itemData( self.penStyleComboBox.currentIndex(), IdRole)) cap = Qt.PenCapStyle(self.penCapComboBox.itemData( self.penCapComboBox.currentIndex(), IdRole)) join = Qt.PenJoinStyle(self.penJoinComboBox.itemData( self.penJoinComboBox.currentIndex(), IdRole)) self.renderArea.setPen(QPen(Qt.blue, width, style, cap, join))
def drawBase(self, p: QPainter, baseRect: QRectF): if self.m_barStyle == self.BarStyle.DONUT: p.setPen( QPen(self.palette().shadow().color(), self.m_outlinePenWidth)) p.setBrush(self.palette().base()) p.drawEllipse(baseRect) elif self.m_barStyle == self.BarStyle.LINE: p.setPen( QPen(self.palette().base().color(), self.m_outlinePenWidth)) p.setBrush(Qt.NoBrush) p.drawEllipse( baseRect.adjusted(self.m_outlinePenWidth / 2, self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2, -self.m_outlinePenWidth / 2)) elif self.m_barStyle in (self.BarStyle.PIE, self.BarStyle.EXPAND): p.setPen( QPen(self.palette().base().color(), self.m_outlinePenWidth)) p.setBrush(self.palette().base()) p.drawEllipse(baseRect)
def input_to_shape_item(self, input_stream: QDataStream, item: QAbstractGraphicsShapeItem): self.input_to_graphics_item(input_stream, item) # Type pen = QPen() brush = QBrush() # Read input_stream >> pen input_stream >> brush # Set item.setPen(pen) item.setBrush(brush)
def input_to_line_item(self, input_stream: QDataStream, item: QGraphicsLineItem): self.input_to_graphics_item(input_stream, item) # Type line = QLineF() pen = QPen() # Read input_stream >> line input_stream >> pen # Set item.setLine(line) item.setPen(pen)
def __init__(self, parent: QWidget): # , scroll_bar: QScrollBar, statusBar: QLabel super().__init__(parent=parent) self.line_height = 18 self.byte_width = 25 self.bytes_per_line = settings.get_bytes_per_line() self.label_offset_x = 5 self.label_length = 100 self.is_dragging_to_select = False self.display_data: List[DisplayByte] = [] self.display_labels: List[str] = [] # TODO make configurable self.font = QFont('DejaVu Sans Mono, Courier, Monospace', 12) self.label_color = QColor(128, 128, 128) self.byte_color = QColor(210, 210, 210) self.selection_color = QPen(QColor(97, 175, 239)) self.selection_color.setWidth(2) self.annotation_pen = QPen(QColor(0, 0, 0), 2) self.enabled_constraint_pen = QPen(QColor(255, 80, 0), 2) self.disabled_constraint_pen = QPen(QColor(130, 40, 0), 2) # Make this widget focussable on click, so that we can reduce the context of the shortcut, so that multiple shortcuts are possible in the same window self.setFocusPolicy(Qt.FocusPolicy.ClickFocus)
def __init__(self, scene: QGraphicsScene, parent: QMainWindow): QGraphicsView.__init__(self, scene, parent) self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0)) self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect)) self.setParent(parent) self.app = self.parent() self.crop_btn = self.parent().crop_button self.mouse_down = False self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern)) self.mouse_pos = QPoint(0, 0) self.adjustment = '' self.annotation = False
def __init__(self, parent=None): super(RenderArea, self).__init__(parent) self.pen = QPen() self.brush = QBrush() self.pixmap = QPixmap() self.shape = RenderArea.Polygon self.antialiased = False self.transformed = False self.pixmap.load(':/images/qt-logo.png') self.setBackgroundRole(QPalette.Base) self.setAutoFillBackground(True)
def mousePressEvent(self, event: QMouseEvent): # pylint: disable=invalid-name """Mouse event handler; begins a crop action""" self.mouse_down = True self.mouse_pos = self.mapToScene(event.pos()).toPoint() if self.crop_btn.isChecked() or self.annotation: self.crop_rect.setTopLeft(self.mapToScene(event.pos()).toPoint()) self.scene().addItem(self.g_rect) if self.annotation: self.g_rect.setPen(QPen(Qt.magenta, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.magenta, Qt.Dense4Pattern)) elif self.hasMouseTracking() and self.g_rect.isUnderMouse: self.adjustment = self.edge(event.pos)[1] else: QGraphicsView.mousePressEvent(self, event)
def toggle_attached(self): legend = self.chart.legend() if legend.isAttachedToChart(): legend.detachFromChart() legend.setBackgroundVisible(True) legend.setBrush(QBrush(QColor(128, 128, 128, 128))) legend.setPen(QPen(QColor(192, 192, 192, 192))) self.show_legend_spinbox() self.update_legend_layout() else: legend.attachToChart() legend.setBackgroundVisible(False) self.hideLegendSpinbox() self.update()
def reset(self): self.crop_rect = QRect(QPoint(0, 0), QSize(0, 0)) self.g_rect = QGraphicsRectItem(QRectF(self.crop_rect)) self.g_rect.setPen(QPen(Qt.red, 1, Qt.SolidLine)) self.g_rect.setBrush(QBrush(Qt.red, Qt.Dense6Pattern)) self.setMouseTracking(False) self.unsetCursor() self.mouse_pos = QPoint(0, 0) self.adjustment = '' self.mouse_down = False if self.crop_btn.isChecked(): self.app.reload() self.setCursor(Qt.CrossCursor) if self.annotation: self.setCursor(Qt.CrossCursor)
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 _create_hover_line(self, chart: QtCharts.QChart) -> tp.Any: scene = chart.scene() result = QGraphicsLineItem() result.setPen(QPen(Qt.black, 0.0, Qt.DashLine)) def move_hover_line(new_value: QPointF) -> None: x = new_value.x() plot_area = chart.plotArea() x_min = plot_area.left() x_max = plot_area.right() result.setVisible(x_min <= x <= x_max) result.setLine(x, plot_area.bottom(), x, plot_area.top()) self.chart_hover_pos.connect(move_hover_line) scene.addItem(result) return result
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, scene, central_widget, gim): super(CustomQGraphicsView, self).__init__(scene, central_widget) # Ustawienia na potrzeby poprawnego rysowania: self.actual_selection: Enum = self.Selection.SELECT self.drawing: bool = False self.preparing: bool = False self.prepare_points: list[QPointF] = [] self.previous_point: QPoint = QPoint(0, 0) # Obiekty na potrzeby sposobu rysowania self.actual_pen: QPen = QPen(QBrush( Qt.black), 1) # QPen: kolor i szerokosc linii + dodatki self.actual_brush: QBrush = QBrush(Qt.darkGreen) # kolor wypełnienia # Model dla itemów sceny self.gim: GraphicItemModel = gim
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))