def star(self): x1 = self.get_cord('Координата x', 'Координата верхней точки по x', 0, 2000) # Координата верхней точки по x y1 = self.get_cord('Координата по y', 'Координата верхней точки по y', 0, 2000) # Координата верхней точки по y x2 = self.get_cord('Координата x', 'Координата левой точки по x', 0, 2000) # Координата левой точки по x y2 = self.get_cord('Координата по y', 'Координата левой точки по y', 0, 2000) # Координата левой точки по y x3 = self.get_cord('Координата x', 'Координата левой нижней точки по x', 0, 2000) # Координата левой нижней точки по x y3 = self.get_cord('Координата по y', 'Координата левой нижней точки по y', 0, 2000) # Координата левой нижней точки по y cP = QPainter(self.image) cP.setPen(self.brushColor) # Цвет границ cP.setBrush(self.brushColor) # Цвет фигуры points = QPolygon([ QPoint(x2, y2), QPoint(x1 + x1 - x2, y2), QPoint(x3, y3), QPoint(x1, y1), QPoint(x1 + x1 - x3, y3) ]) self.lastImage() # Добавление изображения cP.drawPolygon(points) # Нарисовать полигон
def paintEvent(self, QPaintEvent): points = [ QPoint(140, 80), QPoint(150, 10), QPoint(210, 30), QPoint(220, 70) ] rect = QRect(10, 20, 80, 60) painter = QPainter(self) #linearGradient = QLinearGradient(0, 0, 100, 100); #linearGradient.setColorAt(0.0, Qt.white); #linearGradient.setColorAt(0.2, Qt.green); #linearGradient.setColorAt(1.0, Qt.black); #painter.setBrush(linearGradient); painter.setBrush(QColor(Qt.white)) painter.setPen(QPen(Qt.white, 1.0)) painter.drawRect(self.rect()) painter.setBrush(QColor(Qt.blue)) painter.setPen(QPen(Qt.blue, 1.0)) painter.drawPolygon(QPolygon(points), 4)
def paintEvent(self, event): qp = QPainter() pen = QPen() qp.begin(self) qp.setRenderHint(QPainter.Antialiasing) for path in self.paths: pen.setColor(path[1]) pen.setWidth(path[2]) qp.setPen(pen) qp.drawPolyline(path[0]) pen.setColor(self.color) pen.setWidth(self.width) qp.setPen(pen) qp.drawPolyline(self.current) pen.setColor(QColor("orange")) qp.setPen(pen) for path in self.selected_poly: qp.drawPolyline(path[0]) pen.setStyle(Qt.DashDotLine) pen.setColor(QColor("black")) pen.setWidth(2) qp.setPen(pen) qp.drawPolygon(self.select) qp.end()
def draw_something(self, pixmap): painter = QPainter(pixmap) painter.setPen(QPen(Qt.black, 5, Qt.SolidLine)) painter.setBrush(QBrush(Qt.red, Qt.VerPattern)) points = QPolygon([QPoint(*i) for i in self.roi]) painter.drawPolygon(points) return pixmap
def paintEvent(self, event): logger.debug("paintEvent: {0} - {1}".format(self, event.rect())) qp = QPainter() qp.begin(self) width = self.size().width() - 1 height = self.size().height() - 1 #draw border qp.setPen(self.border_color) qp.drawRect(0,0, width, height) #draw plot width -= 1 height -= 1 if len(self.data): max_val = max(map(lambda x: x[-1], self.data)) plots = [list() for _ in range(self.num_data_points) ] for index in range(len(self.data)-1, 1, -1): for inner_index in range(self.num_data_points): plots[inner_index].append(QPoint((width / self.data.maxlen * index), height - (height / max_val * self.data[index][inner_index]))) for x in range(len(plots)-1, -1, -1): qp.setPen(self.plot_colors[x]) qp.setBrush(self.plot_colors[x]) points = plots[x] points.append(QPoint(1, height)) points.append(QPoint(width, height)) qp.drawPolygon(*points) qp.end() logger.debug("paintEvent End: {0}".format(self))
def paintEvent(self, event): logger.debug("paintEvent: {0} - {1}".format(self, event.rect())) qp = QPainter() qp.begin(self) width = self.size().width() - 1 height = self.size().height() - 1 #draw border qp.setPen(self.border_color) qp.drawLine(0, 0, width, 0) qp.drawLine(0, 0, 0, height) qp.drawLine(width, 0, width, height) qp.drawLine(0, height, width, height) #draw plot width -= 1 height -= 1 if len(self.data): qp.setPen(self.plot_color) max_val = max(self.data) points = list(); for index in range(len(self.data)-1, 1, -1): points.append(QPoint((width / 100 * index), height - (height / max_val * self.data[index]))) points.append(QPoint(1, height)) points.append(QPoint(width, height)) qp.setBrush(self.plot_color) qp.drawPolygon(*points) qp.end() logger.debug("paintEvent End: {0}".format(self))
def _draw(self, painter: QPainter, width: int, height: int): painter.setPen(QPen(Qt.NoPen)) painter.setBrush(QBrush(Color.green)) offset = self.base_height(height * 0.3 * smoothen_curve(self.get_age_coefficient())) second_offset = (self.green_height(height) - self.second_green_height(height)) * smoothen_curve( self.get_age_coefficient()) painter.drawPolygon( QPointF( -self.second_green_width(width) * smoothen_curve(self.get_age_coefficient())**2, offset + second_offset), QPointF( self.second_green_width(width) * smoothen_curve(self.get_age_coefficient())**2, offset + second_offset), QPointF( 0, min( self.second_green_height(height) * smoothen_curve(self.get_age_coefficient()) + offset + second_offset, height * 0.95))) super()._draw(painter, width, height)
def paint_event_bar_vertical(qp: QPainter, index_rect: QRect, back_ground: QColor, align: int): if align == ALIGN_RIGHT: rect = index_rect rect.setLeft(rect.left() + 10) arrow_points = [ QPoint(rect.left() - 10, rect.center().y()), rect.topLeft(), rect.topRight(), rect.bottomRight(), rect.bottomLeft() ] else: rect = index_rect rect.setRight(rect.right() - 10) arrow_points = [ QPoint(rect.right() + 10, rect.center().y()), rect.bottomRight(), rect.bottomLeft(), rect.topLeft(), rect.topRight() ] qp.setBrush(back_ground) qp.drawPolygon(QPolygon(arrow_points))
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) # INIT THE LINE p1 = QPointF(((kwargs['w'] - 54) / 2), kwargs['h'] / 2) p2 = QPointF(((kwargs['w'] - 54) / 2) + 54 - 2, kwargs['h'] / 2) line = QLineF(p1, p2) # CLACULATE HEAD COORDS angle = line.angle() p1 = QPointF(line.p2().x() + 2, line.p2().y()) p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8) p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8) # INITIALIZE HEAD head = QPolygonF([p1, p2, p3]) # DRAW EDGE LINE painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) # DRAW EDGE HEAD painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QColor(0, 0, 0)) painter.drawPolygon(head) return pixmap
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, "PyQt by\nRiverbank Computing") 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 paintEvent(self, event): painter = QPainter(self) if self.direction is not "off": painter.drawPolygon( self.pointsDown ) if self.direction == "down" else painter.drawPolygon( self.pointsUp)
def mouseReleaseEvent(self, event): self.curPoint = event.pos() if self.brush == 'rectangle': painter = QPainter(self.image) painter.setPen(QPen(self.brushColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QBrush(self.brushColor, Qt.SolidPattern)) points = QPolygon([ self.lastPoint, QPoint(event.x(), self.lastPoint.y()), event.pos(), QPoint(self.lastPoint.x(), event.y()) ] ) painter.drawPolygon(points) self.firstPoint = False elif self.brush == 'ellipse': painter = QPainter(self.image) painter.setPen(QPen(self.brushColor, 8, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QBrush(self.brushColor, Qt.SolidPattern)) painter.drawEllipse(self.lastPoint.x(), self.lastPoint.y(), event.x() - self.lastPoint.x(), event.y() - self.lastPoint.y()) self.firstPoint = False self.update()
def paintEvent(self, QPaintEvent): painter = QPainter() painter.begin(self) painter.setPen(Qt.blue) #绘制弧 #左上角位置,宽度,高度 rect = QRect(0, 10, 100, 100) #alen:1 alen=1/16度 45*16=720 painter.drawArc(rect, 0, 50 * 16) #绘制圆 painter.setPen(Qt.red) painter.drawArc(120, 10, 100, 100, 0, 360 * 16) #绘制带弦的弧 painter.drawChord(10, 120, 100, 100, 12, 130 * 16) #绘制扇形 painter.drawPie(10, 240, 100, 100, 12, 130 * 16) #绘制椭圆 painter.drawEllipse(120, 120, 150, 100) #5边形 point1 = QPoint(140, 380) point2 = QPoint(270, 420) point3 = QPoint(219, 512) point4 = QPoint(290, 588) point5 = QPoint(120, 533) polygon = QPolygon([point1, point2, point3, point4, point5]) painter.drawPolygon(polygon) #绘制图像 image = QImage('./school.jpg') rect = QRect(300, 200, image.width() / 2, image.height() / 2) painter.drawImage(rect, image) # image.save('./school1.png') painter.end()
def selectpoly_copy(self): """ Copy a polygon region from the current image, returning it. Create a mask for the selected area, and use it to blank out non-selected regions. Then get the bounding rect of the selection and crop to produce the smallest possible image. :return: QPixmap of the copied region. """ self.timer_cleanup() pixmap = self.pixmap().copy() bitmap = QBitmap(*CANVAS_DIMENSIONS) bitmap.clear() # Starts with random data visible. p = QPainter(bitmap) # Construct a mask where the user selected area will be kept, # the rest removed from the image is transparent. userpoly = QPolygon(self.history_pos + [self.current_pos]) p.setPen(QPen(Qt.color1)) p.setBrush(QBrush(Qt.color1)) # Solid color, Qt.color1 == bit on. p.drawPolygon(userpoly) p.end() # Set our created mask on the image. pixmap.setMask(bitmap) # Calculate the bounding rect and return a copy of that region. return pixmap.copy(userpoly.boundingRect())
def draw_polygons(self, event): if self.polygons: painter = QPainter(self) # painter.drawEllipse(0, 0, self.width()/2, self.width()/2) for (pa, pb, pc), color in self.polygons: a = QPoint(pa.x, pa.y) b = QPoint(pb.x, pb.y) c = QPoint(pc.x, pc.y) pen = QPen() if color: pen.setColor(color) else: pen.setColor(QColor(0, 0, 0)) painter.setPen(pen) polygon = QPolygonF([a, b, c]) painter.drawPolygon(polygon) if color: path = QPainterPath() path.addPolygon(polygon) # painter.setBrush(QBrush(color)) painter.fillPath(path, QBrush(color))
def drawGaugeAnnulus(self, outlinePenWith=0): if not self.gaugeColors == None: gaugeAnnulus = QPainter(self) gaugeAnnulus.setRenderHint(QPainter.Antialiasing) gaugeAnnulus.translate(self.width() / 2, self.height() / 2) gaugeAnnulus.setPen(Qt.NoPen) self.pen.setWidth(outlinePenWith) if outlinePenWith > 0: gaugeAnnulus.setPen(self.pen) coloredScalePolygon = self.drawGauge( ((self.widgetDiameter / 2) - (self.pen.width() / 2)) * self.gaugeOuterRadius, (((self.widgetDiameter / 2) - (self.pen.width() / 2)) * self.gaugeInnerRadius), self.gaugeRotation, self.gaugeArcAngle) gradient = QConicalGradient( QPointF(0, 0), -self.gaugeArcAngle - self.gaugeRotation + -1) for eachcolor in self.gaugeColors: gradient.setColorAt(eachcolor[0], eachcolor[1]) gaugeAnnulus.setBrush(gradient) gaugeAnnulus.drawPolygon(coloredScalePolygon)
def draw(self, painter: QPainter): painter.save() brush = QBrush(Qt.SolidPattern) pen = QPen() brush.setColor(self.color) pen.setColor(self.color) painter.setBrush(brush) painter.setPen(pen) painter.drawEllipse(self.origin, self.base_radius, self.base_radius) painter.drawPolygon( QPoint( self.origin.x() + self.base_radius * cos(radians(self.angle - 90)), self.origin.y() + self.base_radius * sin(radians(self.angle - 90))), QPoint( self.origin.x() + self.base_radius * cos(radians(self.angle + 90)), self.origin.y() + self.base_radius * sin(radians(self.angle + 90))), QPoint( self.origin.x() + self.needle_length * cos(radians(self.angle)), self.origin.y() + self.needle_length * sin(radians(self.angle)))) painter.restore()
def draw(self, painter: QPainter): painter.save() brush = QBrush() pen = QPen() brush.setColor(self.fillColor) brush.setStyle(Qt.SolidPattern) pen.setColor(self.lineColor) painter.setBrush(brush) painter.setPen(pen) # Delta values delta_x = (self.width / 2) * cos(radians(self.angle - 90)) delta_y = (self.width / 2) * sin(radians(self.angle - 90)) # Building up the polygon bottom_x = self.radius_one * cos(radians(self.angle)) + self.origin.x() bottom_y = self.radius_one * sin(radians(self.angle)) + self.origin.y() top_x = self.radius_two * cos(radians(self.angle)) + self.origin.x() top_y = self.radius_two * sin(radians(self.angle)) + self.origin.y() painter.drawPolygon(QPoint(bottom_x - delta_x, bottom_y - delta_y), QPoint(bottom_x + delta_x, bottom_y + delta_y), QPoint(top_x + delta_x, top_y + delta_y), QPoint(top_x - delta_x, top_y - delta_y)) painter.restore()
def paintEvent(self, event): if self.display_status: super().paintEvent(event) painter = QPainter(self) painter_path = QPainterPath() qt_pen_1 = QPen(Qt.red, 2, Qt.SolidLine) qt_pen_2 = QPen(Qt.green, 10, Qt.SolidLine) qt_pen_3 = QPen(Qt.red, 2, Qt.DotLine) painter.setPen(qt_pen_1) painter.drawPolygon(QPolygon(self.roi_rect), Qt.WindingFill) painter_path.addPolygon(QPolygonF(self.roi_rect)) painter_path.closeSubpath() # qt_brush = QBrush(Qt.green) qt_brush = QBrush(QColor(0, 255, 0, 64)) painter.setBrush(qt_brush) painter.drawPath(painter_path) # painter.drawPoint(self.tmp_center_pt) painter.setPen(qt_pen_3) painter.drawLine(self.roi_rect[0], self.roi_rect[2]) painter.drawLine(self.roi_rect[1], self.roi_rect[3]) painter.setPen(qt_pen_2) for elem in self.roi_rect: painter.drawPoint(elem) # for elem in self.img_rect: # painter.drawPoint(elem) if self.default_rect: self.update()
def paint(self, QPainter, QStyleOptionGraphicsItem, QWidget_widget=None): # setPen pen = QPen() pen.setWidth(2) pen.setJoinStyle(Qt.MiterJoin) QPainter.setPen(pen) # setBrush brush = QBrush() brush.setColor(Qt.black) brush.setStyle(Qt.SolidPattern) QPainter.setBrush(brush) v = self.line.unitVector() v.setLength(10) v.translate(QPointF(self.line.dx(), self.line.dy())) n = v.normalVector() n.setLength(n.length() * 0.5) n2 = n.normalVector().normalVector() p1 = v.p2() p2 = n.p2() p3 = n2.p2() QPainter.drawLine(self.line) QPainter.drawPolygon(p1, p2, p3)
def drawMeasurements(self, erase_bkg=False): if not self.renderMeasurements or not self._nucboundaries: return if erase_bkg: self._repaintImages() angle_delta = 2 * np.pi / self.nlines nim, width, height = self._images.shape w, h = self.wh for i, n in enumerate(self._nucboundaries): if not n: continue painter = QPainter() painter.begin(self.images[i].pixmap()) painter.setRenderHint(QPainter.Antialiasing) nuc_pen = QPen(QBrush(QColor('white')), 1.1) nuc_pen.setStyle(QtCore.Qt.DotLine) painter.setPen(nuc_pen) dl2 = self.line_length * self._meas.pix_per_um / 2 try: # get nuclei external and internal boundaries as a polygons for d in [dl2, -dl2]: nucb_qpoints = [ Qt.QPoint(x, y) for x, y in n.buffer(d).exterior.coords ] painter.drawPolygon(Qt.QPolygon(nucb_qpoints)) except Exception as e: self.log.error(e) if self.selectedLineId is not None: alpha = angle_delta * self.selectedLineId x, y = int(width / 2), int(height / 2) a = int(width / 2) pt1 = Qt.QPoint(x, y) pt2 = Qt.QPoint(a * np.cos(alpha) + x, a * np.sin(alpha) + y) painter.drawLine(pt1, pt2) for ix, me in self._meas.lines().iterrows(): if self.selectedLineId is not None and me[ 'li'] == self.selectedLineId: painter.setPen( QPen(QBrush(QColor(me['c'])), 1 * self._meas.pix_per_um)) else: painter.setPen( QPen(QBrush(QColor('gray')), 0.1 * self._meas.pix_per_um)) pts = [ Qt.QPoint(_x - x + h / 2, _y - y + w / 2) for _x, _y in [me['ls0'], me['ls1']] ] painter.drawLine(pts[0], pts[1]) painter.end() self.grphtimer.start(1000) self.update()
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setPen(Qt.blue) # 绘制弧:参数表示 x、y坐标和宽高 rect = QRect(0, 10, 200, 200) # 单位alen:等于1/16度 painter.drawArc(rect, 0, 50 * 16) # 通过弧长绘制圆 painter.setPen(Qt.red) painter.drawArc(220, 10, 100, 100, 0, 360 * 16) # 绘制带弦的弧 painter.drawChord(10, 120, 100, 100, 13, 130 * 16) # 绘制扇形 painter.drawPie(10, 240, 100, 100, 13, 130 * 16) # 绘制五边形 point1 = QPoint(140, 380) point2 = QPoint(270, 420) point3 = QPoint(290, 512) point4 = QPoint(290, 588) point5 = QPoint(200, 533) painter.drawPolygon(QPolygon([point1, point2, point3, point4, point5])) # 绘制图形 image = QImage('./images/color.png') painter.drawImage(QRect(400, 400, image.width(), image.height()), image) painter.end()
def paintEvent(self, a0: QtGui.QPaintEvent): painter = QPainter(self) pen = painter.pen() pen.setColor(Qt.black) pen.setWidth(2) painter.setPen(pen) board_x, board_y, board_width, board_height = self.boardSize for i in range(8): lx = board_x + i * 80 painter.drawLine(lx, board_y, lx, board_y + board_height) for j in range(7): ly = board_y + j * 80 painter.drawLine(board_x, ly, board_x + board_width, ly) brush = painter.brush() brush.setColor(Qt.green) brush.setStyle(Qt.SolidPattern) painter.setBrush(brush) if 0 <= self.mousePos <= 6: tr_y = board_y - 20 tr_x = board_x + self.mousePos * 80 + 40 painter.drawPolygon(QPoint(tr_x - 20, tr_y - 20), QPoint(tr_x, tr_y), QPoint(tr_x + 20, tr_y - 20)) for col in range(7): for row in range(5, -1, -1): piece = self.controller.gameModel[row][col] if piece == -1: break if piece == 0: brush.setColor(QColor("#db0000")) else: brush.setColor(QColor("#00468b")) painter.setBrush(brush) painter.drawEllipse(QPoint(board_x + col * 80 + 40, board_y + row * 80 + 40), 35, 35)
class Window(QWidget): class Polygon(): def __init__(self, n, pos, size): self.n = n self.pos = pos self.size = size self.polygon = self.createPolygon(n, pos, size) def createPolygon(self, n: int, pos: QPoint, size: int): polygon = [] delt = 2 * pi / n for i in range(n): i *= delt polygon.append( QPoint(pos.x() + int(sin(i) * size), pos.y() + int(cos(i) * size))) return QPolygon(polygon) def addAngle(self): self.n += 1 self.polygon = self.createPolygon(self.n, self.pos, self.size) def __init__(self): super().__init__() self.setWindowTitle('5.2') self.show() self.polygons = [] def deletePolygons(self): self.polygons.clear() def keyPressEvent(self, event): if event.key() == Qt.Key_Delete: self.deletePolygons() self.update() def findPolygon(self, pos): for i in range(len(self.polygons)): if self.polygons[i].polygon.containsPoint(pos, Qt.OddEvenFill): return i return -1 def mousePressEvent(self, event): x, y = event.pos().x(), event.pos().y() index = self.findPolygon(QPoint(x, y)) if index == -1: self.polygons.append(self.Polygon(3, QPoint(x, y), 50)) else: self.polygons[index].addAngle() self.update() def paintEvent(self, event): self.painter = QPainter(self) self.painter.begin(self) self.drawPolygons() self.painter.end() def drawPolygons(self): for polygon in self.polygons: self.painter.drawPolygon(polygon.polygon)
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) # INITIALIZE EDGE LINE pp1 = QPointF(((kwargs['w'] - 52) / 2), kwargs['h'] / 2) pp2 = QPointF(((kwargs['w'] - 52) / 2) + 52 - 2, kwargs['h'] / 2) line = QLineF(pp1, pp2) # CALCULATE HEAD COORDINATES angle = radians(line.angle()) p1 = QPointF(line.p2().x() + 2, line.p2().y()) p2 = p1 - QPointF(sin(angle + M_PI / 3.0) * 8, cos(angle + M_PI / 3.0) * 8) p3 = p1 - QPointF(sin(angle + M_PI - M_PI / 3.0) * 8, cos(angle + M_PI - M_PI / 3.0) * 8) # INITIALIZE EDGE HEAD head = QPolygonF([p1, p2, p3]) # DRAW THE POLYGON painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) # DRAW HEAD painter.setPen(QPen(QColor(0, 0, 0), 1.1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.setBrush(QColor(0, 0, 0)) painter.drawPolygon(head) # DRAW THE TEXT ON TOP OF THE EDGE space = 2 if Platform.identify() is Platform.Darwin else 0 painter.setFont(Font('Arial', 9, Font.Light)) painter.drawText(pp1.x() + space, (kwargs['h'] / 2) - 4, 'instanceOf') return pixmap
def _drawIcon(self, color=Qt.black): self.setForeground(QBrush(color)) if self.isRootNode: pixmap = QPixmap(20, 20) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) pen = QPen(color) pen.setWidth(1) painter.setPen(pen) painter.setBrush(color) painter.setRenderHint(QPainter.Antialiasing) if not self.isExpanded: arrowRightPolygon = [ QPoint(6, 6), QPoint(6, 14), QPoint(14, 10) ] painter.drawPolygon(QPolygon(arrowRightPolygon)) else: arrowDownPolygon = [ QPoint(6, 6), QPoint(15, 6), QPoint(10, 14) ] painter.drawPolygon(QPolygon(arrowDownPolygon)) painter.end() self.setIcon(QIcon(pixmap))
def __grabRegion(self): """ Private method to grab the selected region (i.e. do the snapshot). """ pol = QPolygon(self.__selection) if not pol.isEmpty(): self.__grabbing = True xOffset = self.__pixmap.rect().x() - pol.boundingRect().x() yOffset = self.__pixmap.rect().y() - pol.boundingRect().y() translatedPol = pol.translated(xOffset, yOffset) pixmap2 = QPixmap(pol.boundingRect().size()) pixmap2.fill(Qt.transparent) pt = QPainter() pt.begin(pixmap2) if pt.paintEngine().hasFeature(QPaintEngine.PorterDuff): pt.setRenderHints( QPainter.Antialiasing | QPainter.HighQualityAntialiasing | QPainter.SmoothPixmapTransform, True) pt.setBrush(Qt.black) pt.setPen(QPen(QBrush(Qt.black), 0.5)) pt.drawPolygon(translatedPol) pt.setCompositionMode(QPainter.CompositionMode_SourceIn) else: pt.setClipRegion(QRegion(translatedPol)) pt.setCompositionMode(QPainter.CompositionMode_Source) pt.drawPixmap(pixmap2.rect(), self.__pixmap, pol.boundingRect()) pt.end() self.grabbed.emit(pixmap2)
def paint(self, painter: QPainter, option: QStyleOptionGraphicsItem, widget=None): if not self.source or not self.dest: return line = QLineF(self.source_point, self.dest_point) if line.length() == 0.0: return color = self.get_color() width = SupremeSettings()['edge_width'] if option.state & QStyle.State_Sunken: color, width = Qt.red, 2 painter.setPen(QPen(Qt.black, 2, Qt.DashLine)) painter.drawPolygon(self.getSelectionPolygon()) elif option.state & QStyle.State_MouseOver: color, width = Qt.blue, 2 painter.setPen( QPen(color, width, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) painter.drawLine(line) angle = math.acos(line.dx() / line.length()) if line.dy() >= 0: angle = math.pi * 2 - angle if self.arrow_size > 0: dest_arrow_p1 = self.dest_point + QPointF( math.sin(angle - math.pi / 3) * self.arrow_size, math.cos(angle - math.pi / 3) * self.arrow_size) dest_arrow_p2 = self.dest_point + QPointF( math.sin(angle - math.pi + math.pi / 3) * self.arrow_size, math.cos(angle - math.pi + math.pi / 3) * self.arrow_size) painter.setBrush(color) painter.drawPolygon( QPolygonF([line.p2(), dest_arrow_p1, dest_arrow_p2])) self.draw_animated_objects()
def warningAreaBrush(size=32): """Return a checker board brush""" tmpPixmap = QPixmap(size, size) tmpPixmap.fill(QColor(255, 255, 255, 32)) brush = QBrush(QColor(0, 0, 0, 32)) canvas = QPainter() canvas.begin(tmpPixmap) canvas.setPen(Qt.NoPen) canvas.setBrush(brush) s1 = size >> 1 s2 = size - s1 canvas.setRenderHint(QPainter.Antialiasing, True) canvas.drawPolygon( QPolygon( [QPoint(s1, 0), QPoint(size, 0), QPoint(0, size), QPoint(0, s1)])) canvas.drawPolygon( QPolygon([QPoint(size, s1), QPoint(size, size), QPoint(s1, size)])) canvas.end() return QBrush(tmpPixmap)
def drawShape(self, points, color=Qt.blue): qpts = [QPoint(p.x, p.y) for p in points] p = QPainter(self.pixmap()) p.setPen(QPen(Qt.NoPen)) p.setBrush(QBrush(color, Qt.SolidPattern)) p.drawPolygon(*qpts)
def update_slider(self): ''' Update the slider to a gradient between the two colors. The painting of the slider comes from the program Krita. The original code can be accessed at the following URL. https://github.com/KDE/krita/blob/master/plugins/dockers/advancedcolorselector/kis_shade_selector_line.cpp ''' if self.need_redraw: patch_count = self.width() base_hsva = list(self.docker.managedcolor_to_qcolor(self.left_color).getHsvF()) dest_hsva = list(self.docker.managedcolor_to_qcolor(self.right_color).getHsvF()) diff_hsva = [(dest_hsva[i] - base_hsva[i]) for i in range(4)] if dest_hsva[0] == -1.0: diff_hsva[0] = 0 elif base_hsva[0] == -1.0: diff_hsva[0] = 0 base_hsva[0] = dest_hsva[0] elif diff_hsva[0] > 0.5: # make sure the sliding goes through a minor arc diff_hsva[0] = diff_hsva[0] - 1.0 elif diff_hsva[0] < -0.5: diff_hsva[0] = diff_hsva[0] + 1.0 step_hsva = [x / patch_count for x in diff_hsva] self.slider_pixmap = QPixmap(self.width(), self.height()) painter = QPainter(self.slider_pixmap) for i in range(patch_count): hue = base_hsva[0] + i * step_hsva[0] while hue < 0.0: hue += 1.0 while hue > 1.0: hue -= 1.0 saturation = base_hsva[1] + i * step_hsva[1] value = base_hsva[2] + i * step_hsva[2] cur_color = QColor.fromHsvF(hue, saturation, value) painter.fillRect(i, 0, 1, self.height(), cur_color) painter.end() self.need_redraw = False widget_painter = QPainter(self) self.rendered_image = self.slider_pixmap.toImage() widget_painter.drawImage(0, 0, self.rendered_image) if self.value_x is not None: start_x = self.value_x start_y = self.height() / 2 delta_x = self.height() / 3 delta_y = self.height() / 3 points = [QPoint(start_x, start_y), QPoint(start_x - delta_x, start_y + delta_y), QPoint(start_x + delta_x, start_y + delta_y)] widget_painter.setBrush(QBrush(self.cursor_fill_color)) widget_painter.setPen(self.cursor_outline_color) widget_painter.drawPolygon(QPolygon(points))
class Mooving_Pyramid(QMainWindow): def __init__(self): super().__init__() self.pyro = [] self.initUI() def initUI(self): self.setGeometry(0, 0, 1000, 1000) self.pbrushes = ((QBrush(Qt.white, Qt.SolidPattern), QPen(Qt.white, 0)), (QBrush(Qt.yellow, Qt.SolidPattern), QPen(Qt.black, 2, Qt.SolidLine))) self.painter = QPainter(self) self.show() def paintEvent(self, event): # self.painter = QPainter(self) # self.painter.setBrush(self.pbrushes[0][0]) # self.painter.setPen(self.pbrushes[0][1]) self.painter.begin(self) # self.painter.drawRect(0, 0, self.width(), self.height()) self.painter.setBrush(self.pbrushes[1][0]) self.painter.setPen(self.pbrushes[1][1]) for point in self.pyro: self.painter.drawPolygon(*point) self.painter.end() self.pyro = []
def renderImage(self, remove_useless_background=False): if not self.Image: return paintedImage = QImage(self.Image.size(), QImage.Format_ARGB32) paintedImage.fill(Qt.transparent) painter = QPainter(paintedImage) if self.cropPolygon: painterPath = QPainterPath() painterPath.addPolygon(self.cropPolygon) painter.setClipPath(painterPath) painter.drawImage(QPoint(), self.Image) # draw polygon pen = QPen(self.PolygonEdgeColor, 5) painter.setPen(pen) if len(self.polygonList): for polygon in self.polygonList: # pp = QPolygonF([QPointF(point[0], point[1]) for point in polygon['geo']]) if polygon['selected']: painter.setBrush(self.PolygonSelectedColor) else: painter.setBrush(self.PolygonColor) painter.drawPolygon(polygon['geo']) painter.end() if remove_useless_background and self.cropPolygon: return paintedImage.copy(painterPath.boundingRect().toRect()) else: return paintedImage
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) polygon = cls.createPolygon(48, 30) # ITEM SHAPE painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine)) painter.setBrush(QColor(0, 0, 0)) painter.translate(kwargs['w'] / 2, kwargs['h'] / 2) painter.drawPolygon(polygon) return pixmap
def paintEvent(self, event): qp = QPainter(self) qp.setRenderHint(QPainter.Antialiasing) # <- Set anti-aliasing See https://wiki.python.org/moin/PyQt/Painting%20and%20clipping%20demonstration qp.setPen(QPen(Qt.black, 5, Qt.SolidLine)) qp.setBrush(QBrush(Qt.red, Qt.SolidPattern)) #qp.setBrush(QBrush(Qt.red, Qt.DiagCrossPattern)) points = QPolygon([ QPoint(10, 10), QPoint(20, 100), QPoint(100, 50), QPoint(150, 10), QPoint(100, 100) ]) qp.drawPolygon(points)
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) polygon = cls.createPolygon(48, 30) # ITEM SHAPE painter.setRenderHint(QPainter.Antialiasing) painter.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine)) painter.setBrush(QColor(252, 252, 252)) painter.translate(kwargs['w'] / 2, kwargs['h'] / 2) painter.drawPolygon(polygon) # TEXT WITHIN THE SHAPE painter.setFont(Font('Arial', 11, Font.Light)) painter.drawText(polygon.boundingRect(), Qt.AlignCenter, 'oneOf') return pixmap
def _drawIcon(self, color=Qt.black): self.setForeground(QBrush(color)) if self.isRootNode: pixmap = QPixmap(20, 20) pixmap.fill(Qt.transparent) painter = QPainter() painter.begin(pixmap) pen = QPen(color) pen.setWidth(1) painter.setPen(pen) painter.setBrush(color) painter.setRenderHint(QPainter.Antialiasing) if not self.isExpanded: arrowRightPolygon = [QPoint(6, 6), QPoint(6, 14), QPoint(14, 10)] painter.drawPolygon(QPolygon(arrowRightPolygon)) else: arrowDownPolygon = [QPoint(6, 6), QPoint(15, 6), QPoint(10, 14)] painter.drawPolygon(QPolygon(arrowDownPolygon)) painter.end() self.setIcon(QIcon(pixmap))
def paintEvent(self, e): p = QPainter(self) p.translate(20, 20) scale_coef = 1.6 p.scale(30 * scale_coef, 30 * scale_coef) p.setPen(QPen(Qt.black, 0)) for pin in chain(cpu_pins, mem_pins): p.drawEllipse(QPointF(pin.x, pin.y), PIN_RADIUS, PIN_RADIUS) for conn_ind, conn in enumerate(connections): if conn_ind in max_tail: p.setPen(QPen(Qt.red, 0)) else: p.setPen(QPen(Qt.black, 0)) pin0 = cpu_pins[conn.cpu_pin_idx] pin1 = mem_pins[conn.mem_pin_idx] p.drawLine(QPointF(pin0.x, pin0.y), QPointF(pin1.x, pin1.y)) for poly, layer in polygons: if layer == 1: color = Qt.black elif layer == 2: color = Qt.red elif layer == 2: color = Qt.blue else: assert 0 color = QColor(color) color.setAlpha(180) p.setBrush(QBrush(color)) p.drawPolygon(poly) color = QColor(Qt.darkGreen) color.setAlpha(180) brush = QBrush(color) p.setBrush(brush) for x, y in jumps: # NB jump doesnt have a radius p.drawEllipse(QPointF(x, y), PIN_RADIUS, PIN_RADIUS) # pass p.end()
def image(cls, **kwargs): """ Returns an image suitable for the palette. :rtype: QPixmap """ # INITIALIZATION pixmap = QPixmap(kwargs['w'], kwargs['h']) pixmap.fill(Qt.transparent) painter = QPainter(pixmap) polygon = QPolygonF([ QPointF(+27 - 10, -17), # 0 QPointF(-27, -17), # 1 QPointF(-27, +17), # 2 QPointF(+27, +17), # 3 QPointF(+27, -17 + 10), # 4 QPointF(+27 - 10, -17), # 5 ]) fold = QPolygonF([ QPointF(polygon[cls.indexTR].x(), polygon[cls.indexTR].y()), QPointF(polygon[cls.indexTR].x(), polygon[cls.indexTR].y() + 10), QPointF(polygon[cls.indexRT].x(), polygon[cls.indexRT].y()), QPointF(polygon[cls.indexTR].x(), polygon[cls.indexTR].y()), ]) # ITEM SHAPE painter.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine)) painter.setBrush(QColor(252, 252, 252)) painter.translate(kwargs['w'] / 2, kwargs['h'] / 2) painter.drawPolygon(polygon) painter.drawPolygon(fold) # TEXT WITHIN THE SHAPE painter.setFont(Font('Arial', 10, Font.Light)) painter.drawText(polygon.boundingRect(), Qt.AlignCenter, 'value\nrestriction') return pixmap
class Window(QWidget): def __init__(self): self.black = QColor(0, 0, 0) self.colors = [QColor(255, 0, 0), QColor(0, 255, 0), QColor(0 ,0, 255),\ QColor(128, 0, 128), QColor(128, 128, 0)] super().__init__() self.setGeometry(100, 100, 900,500) self.setFixedSize(1000, 500) self.flag_rects = True self.pen = False hbox = QHBoxLayout() hbox.addStretch(1) self.b_stop_entering = QPushButton("Закончить ввод", self) self.b_stop_entering.clicked[bool].connect(self.stop_entering) hbox.addWidget(self.b_stop_entering) vbox = QVBoxLayout() vbox.addStretch(1) vbox.addLayout(hbox) self.setLayout(vbox) self.setWindowTitle("Map") self.qp = QPainter() self.vertexes = [] self.edges = [] self.previous_point = QPoint() self.countries = [] self.points_for_country = [] def stop_entering(self): """Обработчик кнопки""" if len(self.points_for_country): QMessageBox.question(self, "Misstake", "Закончите вводить страну", QMessageBox.Ok, QMessageBox.Ok) self.b_stop_entering.setText("Закончить ввод") return self.flag_rects = not self.flag_rects if not self.flag_rects: self.b_stop_entering.setText("Продолжить ввод") if logic.is_there_intersection(self.edges): QMessageBox.question(self, "Misstake", "Отрезки не должны пересекаться", QMessageBox.Ok, QMessageBox.Ok) self.countries.clear() self.edges.clear() self.points_for_country.clear() self.vertexes.clear() self.flag_rects = True self.pen = False self.update() self.b_stop_entering.setText("Закончить ввод") return for country1 in self.countries: for country2 in self.countries: if country1 == country2: continue else: intersect = country1.intersected(country2) if intersect: QMessageBox.question(self, "Misstake", "Страны не должны накладываться друг на друга", QMessageBox.Ok, QMessageBox.Ok) self.countries.clear() self.edges.clear() self.points_for_country.clear() self.vertexes.clear() self.flag_rects = True self.pen = False self.update() self.b_stop_entering.setText("Закончить ввод") return logic.get_neighbours(self.countries) logic.paint_graph(self.countries) else: self.b_stop_entering.setText("Закончить ввод") for country in self.countries: country.num_of_color = -1 country.neighbours = [] country.variants_of_color = [0, 1, 2, 3] self.update() def mousePressEvent(self, event): """Обработчик кликов""" if self.flag_rects: x = event.x() y = event.y() flag = True for vertex in self.vertexes: if vertex.x()-10<x<vertex.x()+10 and vertex.y()-10<y<vertex.y()+10: x = vertex.x() y = vertex.y() flag = False break point = QPoint(x, y) if len(self.points_for_country)>2: if point == self.points_for_country[0]: self.edges.append(((self.previous_point.x(), self.previous_point.y()), (x, y))) self.countries.append(logic.Country(self.points_for_country)) self.points_for_country.clear() self.pen = False self.update() return if point in self.points_for_country: return if flag: self.vertexes.append(point) if not self.pen: self.points_for_country.append(point) self.previous_point = point self.update() self.pen = True return else: self.edges.append(((self.previous_point.x(), self.previous_point.y()),(x, y))) self.points_for_country.append(point) self.previous_point = point self.update() def paintEvent(self, event): """Рисовальщик""" self.qp.begin(self) self.qp.setPen(QColor(0, 0, 0)) if self.flag_rects: for point in self.vertexes: if point in self.points_for_country: if point in self.points_for_country: self.qp.setPen(QColor(0, 0, 255)) if point == self.points_for_country[0]: self.qp.setPen(QColor(255, 0, 0)) if point == self.points_for_country[-1]: self.qp.setPen(QColor(0, 255, 0)) self.qp.drawRect(point.x()-10, point.y()-10, 20, 20) self.qp.setPen(QColor(0, 0, 0)) else: self.qp.setRenderHint(QPainter.Antialiasing) for country in self.countries: self.qp.setBrush(self.colors[country.num_of_color]) self.qp.drawPolygon(country) for edge in self.edges: self.qp.drawLine(edge[0][0], edge[0][1], edge[1][0], edge[1][1]) self.qp.end()
def paintEvent(self, evt): """ Protected method handling paint events. @param evt paint event (QPaintEvent) """ if self.__grabbing: # grabWindow() should just get the background return painter = QPainter(self) pal = QPalette(QToolTip.palette()) font = QToolTip.font() handleColor = pal.color(QPalette.Active, QPalette.Highlight) handleColor.setAlpha(160) overlayColor = QColor(0, 0, 0, 160) textColor = pal.color(QPalette.Active, QPalette.Text) textBackgroundColor = pal.color(QPalette.Active, QPalette.Base) painter.drawPixmap(0, 0, self.__pixmap) painter.setFont(font) pol = QPolygon(self.__selection) if not self.__selection.boundingRect().isNull(): # Draw outline around selection. # Important: the 1px-wide outline is *also* part of the # captured free-region pen = QPen(handleColor, 1, Qt.SolidLine, Qt.SquareCap, Qt.BevelJoin) painter.setPen(pen) painter.drawPolygon(pol) # Draw the grey area around the selection. grey = QRegion(self.rect()) grey = grey - QRegion(pol) painter.setClipRegion(grey) painter.setPen(Qt.NoPen) painter.setBrush(overlayColor) painter.drawRect(self.rect()) painter.setClipRect(self.rect()) drawPolygon(painter, pol, handleColor) if self.__showHelp: painter.setPen(textColor) painter.setBrush(textBackgroundColor) self.__helpTextRect = painter.boundingRect( self.rect().adjusted(2, 2, -2, -2), Qt.TextWordWrap, self.__helpText).translated( -self.__desktop.x(), -self.__desktop.y()) self.__helpTextRect.adjust(-2, -2, 4, 2) drawPolygon(painter, self.__helpTextRect, textColor, textBackgroundColor) painter.drawText( self.__helpTextRect.adjusted(3, 3, -3, -3), Qt.TextWordWrap, self.__helpText) if self.__selection.isEmpty(): return # The grabbed region is everything which is covered by the drawn # rectangles (border included). This means that there is no 0px # selection, since a 0px wide rectangle will always be drawn as a line. boundingRect = self.__selection.boundingRect() txt = "{0}, {1} ({2} x {3})".format( self.__locale.toString(boundingRect.x()), self.__locale.toString(boundingRect.y()), self.__locale.toString(boundingRect.width()), self.__locale.toString(boundingRect.height()) ) textRect = painter.boundingRect(self.rect(), Qt.AlignLeft, txt) boundingRect = textRect.adjusted(-4, 0, 0, 0) polBoundingRect = pol.boundingRect() if (textRect.width() < polBoundingRect.width() - 2 * self.__handleSize) and \ (textRect.height() < polBoundingRect.height() - 2 * self.__handleSize) and \ polBoundingRect.width() > 100 and \ polBoundingRect.height() > 100: # center, unsuitable for small selections boundingRect.moveCenter(polBoundingRect.center()) textRect.moveCenter(polBoundingRect.center()) elif polBoundingRect.y() - 3 > textRect.height() and \ polBoundingRect.x() + textRect.width() < self.rect().width(): # on top, left aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.x(), polBoundingRect.y() - 3)) textRect.moveBottomLeft( QPoint(polBoundingRect.x() + 2, polBoundingRect.y() - 3)) elif polBoundingRect.x() - 3 > textRect.width(): # left, top aligned boundingRect.moveTopRight( QPoint(polBoundingRect.x() - 3, polBoundingRect.y())) textRect.moveTopRight( QPoint(polBoundingRect.x() - 5, polBoundingRect.y())) elif (polBoundingRect.bottom() + 3 + textRect.height() < self.rect().bottom()) and \ polBoundingRect.right() > textRect.width(): # at bottom, right aligned boundingRect.moveTopRight( QPoint(polBoundingRect.right(), polBoundingRect.bottom() + 3)) textRect.moveTopRight( QPoint(polBoundingRect.right() - 2, polBoundingRect.bottom() + 3)) elif polBoundingRect.right() + textRect.width() + 3 < \ self.rect().width(): # right, bottom aligned boundingRect.moveBottomLeft( QPoint(polBoundingRect.right() + 3, polBoundingRect.bottom())) textRect.moveBottomLeft( QPoint(polBoundingRect.right() + 5, polBoundingRect.bottom())) # If the above didn't catch it, you are running on a very # tiny screen... drawPolygon(painter, boundingRect, textColor, textBackgroundColor) painter.drawText(textRect, Qt.AlignHCenter, txt) if (polBoundingRect.height() > self.__handleSize * 2 and polBoundingRect.width() > self.__handleSize * 2) or \ not self.__mouseDown: painter.setBrush(Qt.transparent) painter.setClipRegion(QRegion(pol)) painter.drawPolygon(QPolygon(self.rect()))
class Renderer: def __init__(self, width, height, ownWindow=False): self.width = width self.height = height self.img = QImage(width, height, QImage.Format_RGB888) self.painter = QPainter() self.window = None if ownWindow: self.app = QApplication([]) self.window = Window() def close(self): """ Deallocate resources used """ pass def beginFrame(self): self.painter.begin(self.img) self.painter.setRenderHint(QPainter.Antialiasing, False) # Clear the background self.painter.setBrush(QColor(0, 0, 0)) self.painter.drawRect(0, 0, self.width - 1, self.height - 1) def endFrame(self): self.painter.end() if self.window: if self.window.closed: self.window = None else: self.window.setPixmap(self.getPixmap()) self.app.processEvents() def getPixmap(self): return QPixmap.fromImage(self.img) def getArray(self): """ Get a numpy array of RGB pixel values. The size argument should be (3,w,h) """ width = self.width height = self.height shape = (width, height, 3) numBytes = self.width * self.height * 3 buf = self.img.bits().asstring(numBytes) output = np.frombuffer(buf, dtype='uint8') output = output.reshape(shape) return output def push(self): self.painter.save() def pop(self): self.painter.restore() def rotate(self, degrees): self.painter.rotate(degrees) def translate(self, x, y): self.painter.translate(x, y) def scale(self, x, y): self.painter.scale(x, y) def setLineColor(self, r, g, b, a=255): self.painter.setPen(QColor(r, g, b, a)) def setColor(self, r, g, b, a=255): self.painter.setBrush(QColor(r, g, b, a)) def setLineWidth(self, width): pen = self.painter.pen() pen.setWidthF(width) self.painter.setPen(pen) def drawLine(self, x0, y0, x1, y1): self.painter.drawLine(x0, y0, x1, y1) def drawCircle(self, x, y, r): center = QPoint(x, y) self.painter.drawEllipse(center, r, r) def drawPolygon(self, points): """Takes a list of points (tuples) as input""" points = map(lambda p: QPoint(p[0], p[1]), points) self.painter.drawPolygon(QPolygon(points)) def fillRect(self, x, y, width, height, r, g, b, a=255): self.painter.fillRect(QRect(x, y, width, height), QColor(r, g, b, a))
def paintEvent(self, event): painter = QPainter(self) painter.setPen(self.pen) painter.setBrush(self.brush) if self.antialiased: painter.setRenderHint(QPainter.Antialiasing) angle_step = 360 / self.n_states painter.save() #Save_1. Save the state of the system (push matrix) painter.translate(self.dist_center.x(), self.dist_center.y()) # go to the center of the render area painter.rotate(-180) #to start painting from the left side of the circle (clockwise) #center of the circumference where through we are going to paint our states x = self.dist_radius * math.cos(0) y = self.dist_radius * math.sin(0) for h in range(self.n_states): rot = angle_step * h # each state is equidistant from the others. We paint them in circles painter.save() #Save_2 painter.rotate(rot) #now our system is pointing to the next state to be drawn painter.translate(x,y) #now our origin is in the center of the next state to be drawn #if the state is active, fill it green if self.machine.getState(h).isActive(): painter.setBrush(self.greenGradientBrush) painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius) #draw the new state #global position of transformed coordinates (before any transformation, origin at top-left corner) gx = painter.worldTransform().map(QPoint(0,0)).x() gy = painter.worldTransform().map(QPoint(0,0)).y() self.machine.getState(h).setPos(gx, gy) #store the center of the state without any transformation applied # text transformation. Our origin is still in the center of the current state painter.save() #Save_3 painter.rotate(180) #making the text go vertical painter.rotate(-rot) #undoing the rotation made for painting the state. No the text is horizontal font = painter.font(); font.setPixelSize(self.state_radius*.4); painter.setFont(font); rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2) painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName()); painter.restore() #Restore_3 #end text transformation painter.restore() #Restore_2 painter.restore() #Restore_1. Restore the state of the system (pop matrix) #drawing transitions. Line between states painter.save() # Save_4 pptv = QTransform() #Define a new transformation. Needed to rotate the system along other axis than Z pptv.translate(0, self.height()) #We are now at the bottom-left corner of the screen pptv.rotate(-180, Qt.XAxis) #Rotate along the X-axis so now we are in a typical cartesian system. painter.setTransform(pptv) #Apply the transformation states = self.machine.getStates() for state in states: transitions = state.getTransitions() for transition in transitions: #get the center of the origin and destination states in our current system state orig = QPoint(state.getPos()[0], state.getPos()[1]) end = QPoint(self.machine.getState(transition.getStateEnd()).getPos()[0], self.machine.getState(transition.getStateEnd()).getPos()[1]) # get those coordinates without transformation orig2 = QPoint(painter.worldTransform().map(orig)) end2 = QPoint(painter.worldTransform().map(end)) #get the angle between states centers and the horizon angle = math.atan2(end2.y() - orig2.y(), end2.x() - orig2.x()) #get the coordinates of the starting point of the transition (it starts in the bound of the state, not in the center) newX = self.state_radius * math.cos(angle) + orig2.x() newY = self.state_radius * math.sin(angle) + orig2.y() #now the transition starts at the border, not in the center orig2.setX(newX) orig2.setY(newY) #same for the destination state angle2 = math.atan2(orig2.y() - end2.y(), orig2.x() - end2.x()) newX2 = self.state_radius * math.cos(angle2) + end2.x() newY2 = self.state_radius * math.sin(angle2) + end2.y() end2.setX(newX2) end2.setY(newY2) #draw the line between the origin and destination states painter.drawLine(orig2, end2) #get the start and the end of the transition untransformed init = QPoint(painter.worldTransform().map(orig2)) end = QPoint(painter.worldTransform().map(end2)) #store that info transition.setOrig(init.x(), init.y()) transition.setDest(end.x(), end.y()) transition.setAngle(angle) painter.restore() #Restore_4 #Appliying style to the transitions painter.setPen(QPen(QColor(Qt.gray), 3)) for state in self.machine.getStates(): for transition in state.getTransitions(): #get the start and end coordinates of the transition i = QPoint(transition.getOrig()[0], transition.getOrig()[1]) o = QPoint(transition.getDest()[0], transition.getDest()[1]) painter.drawPolyline(i, o) #Drawing the arrow at the end of the transition painter.save() #Save_5 painter.setPen(QPen(QColor(Qt.gray), 2)) painter.translate(transition.getDest()[0],transition.getDest()[1]) #Go to the end of the transition painter.rotate(90 - transition.getAngle()*180/math.pi) #Rotate to point in the direction of the transition #coordinates of the arrow (triangle) a = QPoint(0,0) b = QPoint(-5,10) c = QPoint(5,10) #coordinates of the arrow untransformed a1 = painter.worldTransform().map(a) b1 = painter.worldTransform().map(b) c1 = painter.worldTransform().map(c) #Drawin the actual arrow pointer = QPolygon([a,b,c]) painter.drawPolygon(pointer) painter.restore() #Restore_5 #For the animation of the transition painter.save() #Save_6 if transition.isActive(): #if the current transition is the active one the wave function will be running, so it's updating the canvas painter.setPen(QPen(QColor(Qt.green), 3)) painter.drawPolyline(i,o) painter.setPen(QPen(QColor(Qt.gray), 3)) painter.drawPolyline(self.poly(self.pts)) #Draw the arrow in the active state (red arrow) painter.setBrush(QBrush(QColor(255, 0, 0))) painter.setPen(QPen(QColor(Qt.red), 2)) pointer = QPolygon([a1,b1,c1]) painter.drawPolygon(pointer) #Ball that follows the line animation for x, y in self.pts: painter.drawEllipse(QRectF(self.pts[0][0] - 4, self.pts[0][1] - 4, 8, 8)) painter.restore() #Restore_6 #Painting the text of the transition painter.save() #Save_7 pptv = QTransform() painter.setPen(QPen(QColor(Qt.black), 3)) #get the middle point of the transition middleX = (transition.getOrig()[0] + transition.getDest()[0]) /2 middleY = (transition.getOrig()[1] + transition.getDest()[1]) /2 pptv.translate(middleX, middleY) #translate to that point painter.setTransform(pptv) #apply the transformation font = painter.font(); font.setPixelSize(self.state_radius*.2); painter.setFont(font); rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2) name = str(transition.getId())+ '. ' + transition.getName() painter.drawText(rect, Qt.AlignCenter, name) painter.restore() #Restore_7 #paint the actual canvas painter.setPen(self.palette().dark().color()) painter.setBrush(Qt.NoBrush) painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))
def paintEvent(self, event): page_bottom = self.edit.viewport().height() font_metrics = QFontMetrics(self.edit.document().defaultFont()) current_block = self.edit.document().findBlock( self.edit.textCursor().position()) pattern = self.pat if self.edit.lang == "python" else self.patNotPython painter = QPainter(self) background = resources.CUSTOM_SCHEME.get('sidebar-background', resources.COLOR_SCHEME['sidebar-background']) foreground = resources.CUSTOM_SCHEME.get('sidebar-foreground', resources.COLOR_SCHEME['sidebar-foreground']) pep8color = resources.CUSTOM_SCHEME.get('pep8-underline', resources.COLOR_SCHEME['pep8-underline']) errorcolor = resources.CUSTOM_SCHEME.get('error-underline', resources.COLOR_SCHEME['error-underline']) migrationcolor = resources.CUSTOM_SCHEME.get('migration-underline', resources.COLOR_SCHEME['migration-underline']) painter.fillRect(self.rect(), QColor(background)) block = self.edit.firstVisibleBlock() viewport_offset = self.edit.contentOffset() line_count = block.blockNumber() painter.setFont(self.edit.document().defaultFont()) while block.isValid(): line_count += 1 # The top left position of the block in the document position = self.edit.blockBoundingGeometry(block).topLeft() + \ viewport_offset # Check if the position of the block is outside of the visible area if position.y() > page_bottom: break # Set the Painter Pen depending on special lines error = False if settings.CHECK_STYLE and \ ((line_count - 1) in self._pep8Lines): painter.setPen(QColor(pep8color)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.FIND_ERRORS and \ ((line_count - 1) in self._errorsLines): painter.setPen(QColor(errorcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True elif settings.SHOW_MIGRATION_TIPS and \ ((line_count - 1) in self._migrationLines): painter.setPen(QColor(migrationcolor)) font = painter.font() font.setItalic(True) font.setUnderline(True) painter.setFont(font) error = True else: painter.setPen(QColor(foreground)) # We want the line number for the selected line to be bold. bold = False if block == current_block: bold = True font = painter.font() font.setBold(True) painter.setFont(font) # Draw the line number right justified at the y position of the # line. 3 is a magic padding number. drawText(x, y, text). if block.isVisible(): painter.drawText(self.width() - self.foldArea - font_metrics.width(str(line_count)) - 3, round(position.y()) + font_metrics.ascent() + font_metrics.descent() - 1, str(line_count)) # Remove the bold style if it was set previously. if bold: font = painter.font() font.setBold(False) painter.setFont(font) if error: font = painter.font() font.setItalic(False) font.setUnderline(False) painter.setFont(font) block = block.next() self.highest_line = line_count #Code Folding xofs = self.width() - self.foldArea painter.fillRect(xofs, 0, self.foldArea, self.height(), QColor(resources.CUSTOM_SCHEME.get('fold-area', resources.COLOR_SCHEME['fold-area']))) if self.foldArea != self.rightArrowIcon.width(): polygon = QPolygonF() self.rightArrowIcon = QPixmap(self.foldArea, self.foldArea) self.rightArrowIcon.fill(Qt.transparent) self.downArrowIcon = QPixmap(self.foldArea, self.foldArea) self.downArrowIcon.fill(Qt.transparent) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.25)) polygon.append(QPointF(self.foldArea * 0.4, self.foldArea * 0.75)) polygon.append(QPointF(self.foldArea * 0.8, self.foldArea * 0.5)) iconPainter = QPainter(self.rightArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) polygon.clear() polygon.append(QPointF(self.foldArea * 0.25, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.75, self.foldArea * 0.4)) polygon.append(QPointF(self.foldArea * 0.5, self.foldArea * 0.8)) iconPainter = QPainter(self.downArrowIcon) iconPainter.setRenderHint(QPainter.Antialiasing) iconPainter.setPen(Qt.NoPen) iconPainter.setBrush(QColor( resources.CUSTOM_SCHEME.get('fold-arrow', resources.COLOR_SCHEME['fold-arrow']))) iconPainter.drawPolygon(polygon) block = self.edit.firstVisibleBlock() while block.isValid(): position = self.edit.blockBoundingGeometry( block).topLeft() + viewport_offset #Check if the position of the block is outside of the visible area if position.y() > page_bottom: break if pattern.match(block.text()) and block.isVisible(): if block.blockNumber() in self._foldedBlocks: painter.drawPixmap(xofs, round(position.y()), self.rightArrowIcon) else: painter.drawPixmap(xofs, round(position.y()), self.downArrowIcon) #Add Bookmarks and Breakpoint elif block.blockNumber() in self._breakpoints: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(255, 11, 11)) linear_gradient.setColorAt(1, QColor(147, 9, 9)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawEllipse( xofs + 1, round(position.y()) + 6, self.foldArea - 1, self.foldArea - 1) elif block.blockNumber() in self._bookmarks: linear_gradient = QLinearGradient( xofs, round(position.y()), xofs + self.foldArea, round(position.y()) + self.foldArea) linear_gradient.setColorAt(0, QColor(13, 62, 243)) linear_gradient.setColorAt(1, QColor(5, 27, 106)) painter.setRenderHints(QPainter.Antialiasing, True) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(linear_gradient)) painter.drawRoundedRect( xofs + 1, round(position.y()) + 6, self.foldArea - 2, self.foldArea - 1, 3, 3) block = block.next()# block = next(block) painter.end() super(SidebarWidget, self).paintEvent(event)
def paintEvent(self, ev): "Paints the arrow" # setup rect = self.rect() x, y, w, h = rect.getRect() if self._orientation == Qt.Vertical: x = w//4 w = w*0.4 else: y = h//4 h = h*0.4 painter = QPainter(self) painter.setRenderHint(painter.Antialiasing) penColor = QColor(0,0,0) painter.setPen(QPen(penColor)) painter.setBrush(QBrush(self._brushColor)) # figure out the arrow points. arrowPoints = [] if self._direction == Direction.Backward: if self._orientation == Qt.Horizontal: arrowPoints.extend( [QPoint(x + w, y), #QPoint(x + w - self._thickness, y), QPoint(x, y + h // 2), #QPoint(x + w - self._thickness, y + h), QPoint(x + w, y + h), QPoint(x + self._thickness, y + h // 2), QPoint(x + w, y)]) else: arrowPoints.extend( [QPoint(x, y + h), QPoint(x + w // 2, y), QPoint(x + w, y + h), #QPoint(x + w - self._thickness, y + h), QPoint(x + w // 2, y + self._thickness), #QPoint(x + self._thickness, y + h), QPoint(x, y + h)]) else: if self._orientation == Qt.Horizontal: arrowPoints.extend( [QPoint(x, y), #QPoint(x + self._thickness, y), QPoint(x + w, y + h // 2), #QPoint(x + self._thickness, y + h), QPoint(x, y + h), QPoint(x + w - self._thickness, y + h // 2), QPoint(x, y)]) else: arrowPoints.extend( [QPoint(x, y), #QPoint(x + self._thickness, y), QPoint(x + w//2, y + h - self._thickness), #QPoint(x + w - self._thickness, y), QPoint(x + w, y), QPoint(x + w//2, y + h), QPoint(x, y)]) # now draw! painter.drawPolygon(QPolygon(arrowPoints))
def paintEvent(self, _event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) width = self.width() height = self.height() if self.dynamic_resize: knob_radius = self.dynamic_knob_radius else: knob_radius = self.knob_radius # ensure that the center point is in the middle of a pixel to ensure # that exact vertial and horizantal ticks are drawn exactly 1px wide x = math.floor(width / 2.0) + 0.5 y = math.floor(height / 2.0) + 0.5 if DEBUG: painter.fillRect(0, 0, width, height, Qt.yellow) painter.translate(x, y) if self.knob_style == KnobWidget.STYLE_NEEDLE: r = min(x, y) - 1 painter.setPen(Qt.white) painter.setBrush(Qt.white) painter.drawEllipse(QPoint(0, 0), r, r) angle = self.value_factor * self.total_angle - (self.total_angle / 2.0) # draw base knob or needle spike if self.knob_style == KnobWidget.STYLE_ROUND: painter.setPen(self.border_color) if self.pressed: gradient = QRadialGradient(0, 0, knob_radius) gradient.setColorAt(0, self.base_color_pressed) gradient.setColorAt(0.85, self.base_color) gradient.setColorAt(1, self.base_color) painter.setBrush(gradient) else: painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), knob_radius, knob_radius) elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.save() painter.rotate(angle) painter.setPen(self.needle_color) painter.setBrush(self.needle_color) needle = QPolygonF() needle.append(QPointF(self.needle_base_radius * 0.6, 0)) needle.append(QPointF(0, -knob_radius)) needle.append(QPointF(-self.needle_base_radius * 0.6, 0)) painter.drawPolygon(needle) painter.restore() # draw knob mark or needle base if self.knob_style == KnobWidget.STYLE_ROUND: painter.save() painter.rotate(angle) painter.setPen(QPen(self.mark_color, 2)) painter.drawLine(0, -knob_radius * 0.4, 0, -knob_radius * 0.8) painter.restore() elif self.knob_style == KnobWidget.STYLE_NEEDLE: painter.setPen(self.border_color) painter.setBrush(self.base_color) painter.drawEllipse(QPoint(0, 0), self.needle_base_radius, self.needle_base_radius) if self.scale_visible: painter.setPen(Qt.black) # draw scale arc if self.scale_arc_visible: painter.drawArc(-knob_radius - self.knob_to_scale, -knob_radius - self.knob_to_scale, knob_radius * 2 + self.knob_to_scale * 2, knob_radius * 2 + self.knob_to_scale * 2, (90 + self.total_angle / 2) * 16, -self.total_angle * 16) # draw scale ticks def value_to_angle(value): return (float(value - self.minimum_value) / self.value_range) * self.total_angle - (self.total_angle / 2.0) value = self.minimum_value while value <= self.maximum_value: angle = value_to_angle(value) painter.save() painter.rotate(value_to_angle(value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_large) if self.scale_text_visible: p = painter.worldTransform().map(QPoint(0, -knob_radius - \ self.knob_to_scale - \ self.tick_size_large - \ self.tick_to_text - \ self.text_radius)) painter.restore() if self.scale_text_visible: if DEBUG: painter.save() painter.setPen(QColor(255, 0, 0, 50)) painter.setBrush(QColor(255, 0, 0, 50)) painter.drawEllipse(QPoint(p.x() - x, p.y() - y), self.text_radius, self.text_radius) painter.restore() painter.drawText(p.x() - x - 30, p.y() - y - 30, 60, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, str(value)) for i in range(1, self.scale_step_divisions): sub_value = value + (float(self.scale_step_size) * i) / self.scale_step_divisions if sub_value > self.maximum_value: break painter.save() painter.rotate(value_to_angle(sub_value)) painter.drawLine(0, -knob_radius - self.knob_to_scale, 0, -knob_radius - self.knob_to_scale - self.tick_size_small) painter.restore() value += self.scale_step_size if self.title_text != None: painter.drawText(-knob_radius, knob_radius - 30, knob_radius * 2, 60, Qt.TextDontClip | Qt.AlignHCenter | Qt.AlignVCenter, self.title_text)
def paintEvent(self, event): painter=QPainter(self) #设置渲染:开启抗锯齿,老机器很占cpu! painter.setRenderHint(QPainter.Antialiasing) #第一次使用,就使用一次,用来检测打开播放器时,读取上次关闭时的记录 ==> if self.homeAction.playObj.bufferStatus()==100 and self.homeAction.isInitPlay:#判断载入歌曲是否100% ,并且是第一打开播放器 self.homeAction.isInitPlay=0 self.homeAction.playObj.setPosition(self.homeAction.pastTime) if self.homeAction.playStat=="False": self.homeAction.playObj.pause() #第一次使用,用来检测打开播放器时,读取上次关闭时的记录<<== #当前歌曲信息及播放完毕后的事件==>> #当前歌曲(总长) totalDuration = int(self.homeAction.playObj.duration()) #当前歌曲(已播放时间) pastTime = int(self.homeAction.playObj.position()) #当前歌曲(剩余时长) laveTime = totalDuration - pastTime # if pastTime>=totalDuration: if self.homeAction.playObj.mediaStatus()==7: #print("zhe::::") if self.homeAction.isLoop==1:#是否单循环 self.homeAction.playObj.setPosition(0) self.homeAction.playObj.play() else: self.homeAction.nextPlay() self.tracksList.setCurrentRow(self.homeAction.soundID) #当前歌曲信息及播放完毕后的事件结束<<== #记录播放信息==>> colors.CONFIGFILE.set("Save","soundID",str(self.homeAction.soundID)) if self.homeAction.playObj.state()==1: playStat="True" else: playStat="False" colors.CONFIGFILE.set("Save","playStat",playStat) colors.CONFIGFILE.set("Save","pastTime",str(pastTime)) colors.CONFIGFILE.set("Save","volume",str(self.homeAction.currentVolume)) colors.CONFIGFILE.set("Save","isRandom",str(self.homeAction.isRandom)) colors.CONFIGFILE.set("Save","isLoop",str(self.homeAction.isLoop)) colors.CONFIGFILE.write(open('config.ini', "w")) #记录播放信息结束<<== #播放轨道条==>> painter.setPen(QPen(Qt.NoPen))#设置样式 painter.setBrush(QColor(230,230,219,120))#设置颜色 #画播放轨道背景 painter.drawRoundedRect(QRectF(40,257,450,42),5.0, 5.0) #画播放轨道(未播放状态) painter.setPen(QPen(Qt.white,0.1)) painter.setBrush(Qt.NoBrush) painter.drawRect(QRectF(50,272,410,10)) #画播放轨道(计算并画已播放状态) painter.setPen(QPen(Qt.NoPen)) painter.setBrush(QColor(0,173,239,255)) self.section = 408*10 / (totalDuration*10) past = pastTime* self.section currentPosition = past if currentPosition > 408: currentPosition=408 #画出已播放状态) painter.drawRect(QRectF(51,273,currentPosition,8)) #播放轨道条结束<<=== #播放轨道条右侧的播放/暂停的小图标,小三角或两竖<<=== if self.homeAction.playObj.state()==1: #画播放状态标(三角形) points = [QPointF(476.0, 277.0),QPointF(468.0, 273.0),QPointF(468.0, 281.0)] painter.drawPolygon(QPolygonF(points))#三角形 else: #画暂停状态标(两竖) painter.drawRect(QRectF(468,273,3,8))#暂停第一竖 painter.drawRect(QRectF(473,273,3,8))#暂停第二竖 #播放轨道条右侧的播放/暂停的小图标,小三角或两竖结束<<=== #画轨道条上面的照片背景==> painter.setBrush(Qt.white) painter.setPen(QPen(QColor(176,178,177,255),1)) painter.drawRect(QRect(270,105,160,160)) painter.drawImage(QRectF(275,110,150,150), QImage("%simg/music/nonePhoto.png" % (colors.SYSPATH)), QRectF(0.0, 0.0, 150.0, 150.0))#测试照片 if self.homeAction.currentImg!="": photos = QImage() photos.loadFromData(self.homeAction.currentImg, "JPG") newImg = photos.scaled(150,150) painter.drawImage(QRectF(275,110,150,150),newImg, QRectF(0.0, 0.0, 150.0, 150.0))#测试照片 #画轨道条上面的照片背景END<<== #添加艺术家图标和歌曲标题图标==> painter.drawImage(QRectF(40,150,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(0.0, 0.0, 20.0, 20.0))#艺术家 painter.drawImage(QRectF(40,175,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(0.0, 20.0, 20.0, 20.0))#歌曲标题一 painter.drawImage(QRectF(40,200,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(0.0, 40.0, 20.0, 20.0))#歌曲标题二 painter.drawImage(QRectF(40,225,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(0.0, 60.0, 20.0, 20.0))#时间进度 #添加艺术家图标和歌曲标题图标END<<== #当前播放歌曲的信息==>> #<--剩余时间 painter.setFont(QFont("Verdana",8)) painter.setPen(QColor(0,173,239,255)) painter.drawText(QPointF(425,281),str(time.strftime("%M:%S", time.localtime(laveTime/1000))))#剩余时间 #剩余时间--> painter.setFont(QFont("Verdana",12)) painter.drawText(QPointF(70,243),str(time.strftime("%M:%S", time.localtime(totalDuration/1000))) + " /")#总时长 painter.drawText(QPointF(135,243),str(time.strftime("%M:%S", time.localtime(pastTime/1000))))#已播放时间 painter.drawText(QPointF(110,217),"%d/%d" %(self.homeAction.soundID,len(self.homeAction.randomList)-1))#曲目 x/x painter.setFont(QFont("微软雅黑",12)) painter.drawText(QPointF(70,166),self.homeAction.playObj.metaData(QMediaMetaData.Author))#艺术家 painter.drawText(QPointF(70,190),self.homeAction.playObj.metaData(QMediaMetaData.Title))#曲目名 painter.drawText(QPointF(70,216),"曲目")#曲目 #当前播放歌曲的信息END<<== #画试听、随机、循环按钮背景==>> painter.setPen(Qt.NoPen) painter.setBrush(QColor(70,72,76,220)) painter.drawRect(QRect(531,1,75,39))#循环 painter.drawRect(QRect(607,1,75,39))#随机 painter.drawRect(QRect(683,1,74,39))#预览 painter.drawRect(QRect(531,334,75,39))#清空列表 painter.drawRect(QRect(607,334,75,39))#增加文件夹 painter.drawRect(QRect(683,334,74,39))#增加文件 #画试听、随机、循环按钮背景END<<== #按扭文字 循环 随机 预览 清空列表 增加文件夹 增加文件 ==>> painter.setPen(Qt.white) painter.setFont(QFont("微软雅黑",10)) painter.drawText(QPointF(715,25),"循环")#循环 painter.drawText(QPointF(640,25),"随机")#随机 painter.drawText(QPointF(565,25),"预览")#预览 painter.drawText(QPointF(715,358),"打开")#循环 painter.drawText(QPointF(640,358),"添加")#随机 painter.drawText(QPointF(565,358),"清空")#随机 #按扭文字 循环 随机 预览 清空列表 增加文件夹 增加文件 END<<== #歌词==> painter.setFont(QFont("微软雅黑",20)) #print(self.homeAction.songText) for key,v in enumerate(self.homeAction.songTextKey): if int(v) > int(pastTime/1000): strKey = self.homeAction.songTextKey[key-1] painter.drawText(QPointF(40,340),self.homeAction.songText[str(strKey)])#当前歌词 break #歌词<<== #画右侧列表背景 ==> painter.setPen(QPen(Qt.NoPen)) painter.setBrush(QColor(230,230,219,120)) painter.drawRect(QRect(531,41,226,292)) #画右侧列表背景END<<== #画右侧列表滚动条背景 ==>> painter.setBrush(QColor(71,73,76,255)) painter.drawRect(QRect(758,1,42,372)) painter.setBrush(QColor(43,46,49,255)) painter.drawRoundedRect(QRectF(770,1,18,372),20.0, 20.0) #画右侧列表滚动条背景 END<<== #列表向上 向下 按钮 ==>> painter.drawImage(QRectF(770,1,18,27), QImage("%simg/music/up.png" % (colors.SYSPATH)), QRectF(0.0, 0.0, 18.0, 27.0))#列表向上 painter.drawImage(QRectF(770,345,18,27), QImage("%simg/music/down.png" % (colors.SYSPATH)), QRectF(0.0, 0.0, 18.0, 27.0))#列表向下 #列表向上 向下 按钮 END<<== #滚动条位置(顶端:24,底端:298,可移动范围:300)===>> try: if self.tracksList.count()>5: #pp = 274*1000/self.tracksList.count() pp = 300*1000/self.tracksList.count() oo = int(self.tracksList.verticalScrollBar().value()*pp/1000)+24 if oo>298: oo=298 painter.drawImage(QRectF(770,oo,18,53), QImage("%simg/music/scroll.png" % (colors.SYSPATH)), QRectF(0.0, 0.0, 18.0, 53.0)) except : pass #滚动条位置(顶端:24,底端:298,可移动范围:274)END<<=== #画按钮的图标 循环 随机 预览 清空列表 增加文件夹 增加文件 ==>> #画试听图标 if self.homeAction.isPreview: if pastTime >10*1000: self.homeAction.nextPlay() if int(pastTime)%2 == 0: #print("偶数",int(pastTime)%2) painter.setPen(Qt.red) painter.setFont(QFont("微软雅黑",10)) painter.drawText(QPointF(565,25),"预览")#随机 painter.drawImage(QRectF(540,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(40.0, 40.0, 20.0, 20.0))#画预览图标 else: painter.drawImage(QRectF(540,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(20.0, 40.0, 20.0, 20.0))#画预览图标 else: painter.drawImage(QRectF(540,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(20.0, 40.0, 20.0, 20.0))#画预览图标 #画随机图标 if self.homeAction.isRandom == 1: painter.drawImage(QRectF(615,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(40.0, 20.0, 20.0, 20.0))#画随机图标 else: painter.drawImage(QRectF(615,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(20.0, 20.0, 20.0, 20.0))#画随机图标 #画循环图标 if self.homeAction.isLoop == 1: painter.drawImage(QRectF(690,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(40.0, 00.0, 20.0, 20.0))#画循环图标 else: painter.drawImage(QRectF(690,9.5,20,20), QImage("%simg/music/icon.png" % (colors.SYSPATH)), QRectF(20.0, 00.0, 20.0, 20.0))#画循环图标 #清空列表图标 painter.drawImage(QRectF(540,342,20,20), QImage("%smusic/icon.png" % (colors.SYSPATH)), QRectF(60.0, 00.0, 20.0, 20.0))#清空列表图标 painter.drawImage(QRectF(615,344,20,20), QImage("%smusic/icon.png" % (colors.SYSPATH)), QRectF(60.0, 20.0, 20.0, 20.0))#增加文件 painter.drawImage(QRectF(690,342.5,20,20), QImage("%smusic/icon.png" % (colors.SYSPATH)), QRectF(60.0, 40.0, 20.0, 20.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) angle_step = 360 / self.n_states painter.save() painter.translate(self.dist_center.x(), self.dist_center.y()) #painter.drawRect(- self.dist_radius, - self.dist_radius, self.dist_radius *2,self.dist_radius*2) #painter.drawEllipse(QPoint(0, 0), self.dist_radius , self.dist_radius) painter.rotate(-180) #to start painting from the left side of the circle x = self.dist_radius * math.cos(0) y = self.dist_radius * math.sin(0) for h in range(self.n_states): rot = angle_step * h painter.save() painter.rotate(rot) painter.translate(x,y) if self.machine.getState(h).isActive(): painter.setBrush(self.greenGradientBrush) painter.drawEllipse(QPoint(0,0), self.state_radius, self.state_radius) #global position of transformed coordinates gx = painter.worldTransform().map(QPoint(0,0)).x() gy = painter.worldTransform().map(QPoint(0,0)).y() self.machine.getState(h).setPos(gx, gy) # text transformation painter.save() painter.rotate(180) painter.rotate(-rot) font = painter.font(); font.setPixelSize(self.state_radius*.4); painter.setFont(font); rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2) painter.drawText(rect, Qt.AlignCenter, self.machine.getState(h).getName()); painter.restore() #end text transformation painter.restore() painter.restore() #drawing transitions. painter.save() pptv = QTransform() pptv.translate(0, self.height()) pptv.rotate(-180, Qt.XAxis) painter.setTransform(pptv) s = self.machine.getStates() for j in s: t = j.getTransitions() for i in t: #get the points in the canvas init = QPoint(j.getPos()[0], j.getPos()[1]) end = QPoint(self.machine.getState(i.getStateEnd()).getPos()[0], self.machine.getState(i.getStateEnd()).getPos()[1]) # get the transformed ponts init2 = QPoint(painter.worldTransform().map(init)) end2 = QPoint(painter.worldTransform().map(end)) #get the angle between states centers angle = math.atan2(end2.y() - init2.y(), end2.x() - init2.x()) #get the coordinates of the starting point of the transition (it starts in the bound, not in the center) newX = self.state_radius * math.cos(angle) + init2.x() newY = self.state_radius * math.sin(angle) + init2.y() init2.setX(newX) init2.setY(newY) #same for the end of the transition angle2 = math.atan2(init2.y() - end2.y(), init2.x() - end2.x()) newX2 = self.state_radius * math.cos(angle2) + end2.x() newY2 = self.state_radius * math.sin(angle2) + end2.y() end2.setX(newX2) end2.setY(newY2) #painter.drawLine(init, end) painter.drawLine(init2, end2) init = QPoint(painter.worldTransform().map(init2)) end = QPoint(painter.worldTransform().map(end2)) i.setOrig(init.x(), init.y()) i.setDest(end.x(), end.y()) i.setAngle(angle) #painter.draw painter.restore() painter.setPen(QPen(QColor(Qt.gray), 3)) for i in machine.getStates(): for j in i.getTransitions(): i = QPoint(j.getOrig()[0], j.getOrig()[1]) o = QPoint(j.getDest()[0], j.getDest()[1]) painter.drawPolyline(i, o) painter.save() painter.setPen(QPen(QColor(Qt.gray), 2)) painter.translate(j.getDest()[0],j.getDest()[1]) painter.rotate(90 - j.getAngle()*180/math.pi) a = QPoint(0,0) b = QPoint(-5,10) c = QPoint(5,10) a1 = painter.worldTransform().map(a) b1 = painter.worldTransform().map(b) c1 = painter.worldTransform().map(c) pointer = QPolygon([a,b,c]) painter.drawPolygon(pointer) painter.restore() painter.save() if j.isActive(): t = self.machine.getTransition(self.t_active) init = QPoint(t.getOrig()[0], t.getOrig()[1]) end = QPoint(t.getDest()[0], t.getDest()[1]) painter.setPen(QPen(QColor(Qt.green), 3)) painter.drawPolyline(init, end) painter.setPen(QPen(QColor(Qt.gray), 3)) painter.drawPolyline(self.poly(self.pts)) painter.setBrush(QBrush(QColor(255, 0, 0))) painter.setPen(QPen(QColor(Qt.red), 2)) pointer = QPolygon([a1,b1,c1]) painter.drawPolygon(pointer) painter.setBrush(QBrush(QColor(255, 0, 0))) painter.setPen(QPen(QColor(Qt.black), 1)) painter.restore() #Ball that follows the line #for x, y in self.pts: #painter.drawEllipse(QRectF(x - 4, y - 4, 8, 8)) painter.save() pptv = QTransform() painter.setPen(QPen(QColor(Qt.black), 3)) middleX = (j.getOrig()[0] + j.getDest()[0]) /2 middleY = (j.getOrig()[1] + j.getDest()[1]) /2 pptv.translate(middleX, middleY) #pptv.rotate(-j.getAngle()*180/math.pi) painter.setTransform(pptv) font = painter.font(); font.setPixelSize(self.state_radius*.3); painter.setFont(font); rect = QRect(-self.state_radius, -self.state_radius, self.state_radius*2, self.state_radius*2) name = str(j.getId())+ '. ' + j.getName() painter.drawText(rect, Qt.AlignCenter, name) painter.restore() painter.setPen(self.palette().dark().color()) painter.setBrush(Qt.NoBrush) painter.drawRect(QRect(0, 0, self.width() - 1, self.height() - 1))