from . import slicestyles as styles PXI_PP_ITEM_WIDTH = IW = 2.0 # 1.5 TRIANGLE = QPolygonF() TRIANGLE.append(QPointF(0, 0)) TRIANGLE.append(QPointF(0.75 * IW, 0.5 * IW)) TRIANGLE.append(QPointF(0, IW)) TRIANGLE.append(QPointF(0, 0)) # TRIANGLE.translate(-0.75*IW, -0.5*IW) TRIANGLE.translate(-0.25 * IW, -0.5 * IW) PXI_RECT = QRectF(0, 0, IW, IW) T90, T270 = QTransform(), QTransform() T90.rotate(90) T270.rotate(270) FWDPXI_PP, REVPXI_PP = QPainterPath(), QPainterPath() FWDPXI_PP.addPolygon(T90.map(TRIANGLE)) REVPXI_PP.addPolygon(T270.map(TRIANGLE)) # FWDPXI_PP.moveTo(-0.5*IW, 0.7*IW) # FWDPXI_PP.lineTo(0., -0.2*IW) # FWDPXI_PP.lineTo(0.5*IW, 0.7*IW) # extra1 = QPainterPath() # extra1.addEllipse(-0.5*IW, 0.5*IW, IW, 0.4*IW) # extra2 = QPainterPath() # extra2.addEllipse(-0.35*IW, 0.5*IW, 0.7*IW, 0.3*IW) # FWDPXI_PP += extra1 # FWDPXI_PP -= extra2 # REVPXI_PP.moveTo(-0.5*IW, -0.7*IW) # REVPXI_PP.lineTo(0., 0.2*IW)
def __init__(self, parent=None): QWidget.__init__(self, parent) self.path = QPainterPath()
def paintEvent(self, event): painter = QPainter(self) painter.setPen(Qt.black) painter.drawLine(0, 50, 700, 50) # dividing line painter.drawLine(30, 720, 670, 720) # Ox axis painter.drawLine(30, 720, 30, 80) # Oy axis painter.drawLine(670, 720, 665, 715) # arrow Ox painter.drawLine(670, 720, 665, 725) # arrow Ox painter.drawLine(30, 80, 25, 85) # arrow Oy painter.drawLine(30, 80, 35, 85) # arrow Oy if self.points != None: for p in self.points: pen = QPen() pen.setColor(Qt.red) pen.setWidth(5) painter.setPen(pen) painter.drawPoint(30 + p[0], 720 - p[1]) if self.contour != None: pen = QPen() pen.setColor(Qt.black) painter.setPen(pen) for i in range(-1, len(self.contour) - 1): painter.drawLine(30 + self.point_dict[self.contour[i]][0], 720 - self.point_dict[self.contour[i]][1], 30 + self.point_dict[self.contour[i + 1]][0], 720 - self.point_dict[self.contour[i + 1]][1]) path = QPainterPath() path.moveTo(30 + self.point_dict[self.contour[-1]][0], 720 - self.point_dict[self.contour[-1]][1]) for i in range(len(self.contour)): path.lineTo(30 + self.point_dict[self.contour[i]][0], 720 - self.point_dict[self.contour[i]][1]) path.closeSubpath() painter.fillPath(path, QColor(0, 0, 255)) if self.figure != None: for contour in self.figure: for i in range(-1, len(contour) - 1): painter.drawLine(30 + contour[i][0], 720 - contour[i][1], 30 + contour[i + 1][0], 720 - contour[i + 1][1]) if self.triangulation != None: for triangle in self.triangulation: Ax, Ay, Bx, By, Cx, Cy = triangle painter.setPen(Qt.red) painter.drawPoint(30 + Ax, 720 - Ay) painter.drawPoint(30 + Bx, 720 - By) painter.drawPoint(30 + Cx, 720 - Cy) painter.setPen(Qt.black) painter.drawLine(30 + Ax, 720 - Ay, 30 + Bx, 720 - By) painter.drawLine(30 + Bx, 720 - By, 30 + Cx, 720 - Cy) painter.drawLine(30 + Cx, 720 - Cy, 30 + Ax, 720 - Ay) if self.cells != None: pen = QPen() max_value = max(self.cells, key=lambda x: x[-1])[-1] # print(max_value) for cell in self.cells: pen.setColor(Qt.blue) pen.setWidth(5) painter.setPen(pen) painter.drawPoint(30 + cell[0], 720 - cell[1]) value = cell[-1] cell = cell[2:-1] # pen.setColor(Qt.red) # pen.setWidth(1) # painter.setPen(pen) path = QPainterPath() path.moveTo(30 + cell[-2], 720 - cell[-1]) for i in range(0, len(cell), 2): path.lineTo(30 + cell[i], 720 - cell[i + 1]) path.closeSubpath() painter.fillPath( path, QColor(min(255, int(4 * 255 * value / max_value)), 0, 255 - min(255, int(1 * 255 * value / max_value)))) pen.setColor(Qt.black) pen.setWidth(1) painter.setPen(pen) painter.drawPath(path) # for i in range(-2, len(cell) - 2, 2): # painter.drawLine(30 + cell[i], 720 - cell[i + 1], 30 + cell[i + 2], 720 - cell[i + 3]) pen.setColor(Qt.green) pen.setWidth(5) painter.setPen(pen) for i in range(0, len(cell), 2): painter.drawPoint(30 + cell[i], 720 - cell[i + 1])
def drawCurve(self, e, p): path = QPainterPath() path.moveTo(30, 30) path.cubicTo(30, 30, 200, 350, 350, 30) p.drawPath(path)
def clear_peak(self): self.peak = [] if self.peak_item: self.peak_item.setPath(QPainterPath())
def overlay_marks(self, img, is_cseed=False, calibration_sheet=False): border_color = Qt.white base_img = QImage(self.f_size.width(), self.f_size.height(), QImage.Format_ARGB32) base_img.fill(border_color) img = QImage(img) painter = QPainter() painter.begin(base_img) total_distance_h = round(base_img.width() / self.abstand_v) dist_v = round(total_distance_h) / 2 dist_h = round(total_distance_h) / 2 img = img.scaledToWidth(base_img.width() - (2 * (total_distance_h))) painter.drawImage(total_distance_h, total_distance_h, img) #frame around image pen = QPen(Qt.black, 2) painter.setPen(pen) #horz painter.drawLine(0, total_distance_h, base_img.width(), total_distance_h) painter.drawLine(0, base_img.height() - (total_distance_h), base_img.width(), base_img.height() - (total_distance_h)) #vert painter.drawLine(total_distance_h, 0, total_distance_h, base_img.height()) painter.drawLine(base_img.width() - (total_distance_h), 0, base_img.width() - (total_distance_h), base_img.height()) #border around img border_thick = 6 Rpath = QPainterPath() Rpath.addRect( QRectF((total_distance_h) + (border_thick / 2), (total_distance_h) + (border_thick / 2), base_img.width() - ((total_distance_h) * 2) - ((border_thick) - 1), (base_img.height() - ((total_distance_h)) * 2) - ((border_thick) - 1))) pen = QPen(Qt.black, border_thick) pen.setJoinStyle(Qt.MiterJoin) painter.setPen(pen) painter.drawPath(Rpath) Bpath = QPainterPath() Bpath.addRect( QRectF((total_distance_h), (total_distance_h), base_img.width() - ((total_distance_h) * 2), (base_img.height() - ((total_distance_h)) * 2))) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawPath(Bpath) pen = QPen(Qt.black, 1) painter.setPen(pen) painter.drawLine(0, base_img.height() / 2, total_distance_h, base_img.height() / 2) painter.drawLine(base_img.width() / 2, 0, base_img.width() / 2, total_distance_h) painter.drawLine(base_img.width() - total_distance_h, base_img.height() / 2, base_img.width(), base_img.height() / 2) painter.drawLine(base_img.width() / 2, base_img.height(), base_img.width() / 2, base_img.height() - total_distance_h) #print code f_size = 37 QFontDatabase.addApplicationFont( os.path.join(os.path.dirname(__file__), 'DejaVuSansMono-Bold.ttf')) font = QFont("DejaVu Sans Mono", f_size - 11, QFont.Bold) font.setPixelSize(35) painter.setFont(font) if not calibration_sheet: if is_cseed: #its a secret painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.drawImage( ((total_distance_h)) + 11, ((total_distance_h)) + 11, QImage(icon_path('electrumb.png')).scaledToWidth( 2.1 * (total_distance_h), Qt.SmoothTransformation)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2 - 77, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 11, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.version + '_' + self.versioned_seed.checksum) painter.end() else: # revealer painter.setPen(QPen(border_color, 17)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) painter.setPen(QPen(Qt.black, 2)) painter.drawLine(0, dist_v, base_img.width(), dist_v) painter.drawLine(dist_h, 0, dist_h, base_img.height()) painter.drawLine(0, base_img.height() - dist_v, base_img.width(), base_img.height() - (dist_v)) painter.drawLine(base_img.width() - (dist_h), 0, base_img.width() - (dist_h), base_img.height()) logo = QImage(icon_path('revealer_c.png')).scaledToWidth( 1.3 * (total_distance_h)) painter.drawImage((total_distance_h) + (border_thick), ((total_distance_h)) + (border_thick), logo, Qt.SmoothTransformation) #frame around logo painter.setPen(QPen(Qt.black, border_thick)) painter.drawLine( total_distance_h + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2), total_distance_h + logo.width() + border_thick, total_distance_h + logo.height() + 3 * (border_thick / 2)) painter.drawLine( logo.width() + total_distance_h + 3 * (border_thick / 2), total_distance_h + (border_thick), total_distance_h + logo.width() + 3 * (border_thick / 2), total_distance_h + logo.height() + (border_thick)) #frame around code/qr qr_size = 179 painter.drawLine((base_img.width() - ((total_distance_h)) - (border_thick / 2) - 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2) painter.drawLine( (base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2) - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - (border_thick * 8) / 2 - qr_size, ((base_img.height() - ((total_distance_h))) - (border_thick / 2) - 2)) painter.setPen(QPen(Qt.white, border_thick * 8)) painter.drawLine( base_img.width() - ((total_distance_h)) - (border_thick * 8) / 2 - (border_thick / 2) - 2, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2, base_img.width() / 2 + (total_distance_h / 2) - border_thick - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8) / 2) - (border_thick / 2) - 2) painter.setPen(QColor(0, 0, 0, 255)) painter.drawText( QRect(((base_img.width() / 2) + 21) - qr_size, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 93, base_img.height() - total_distance_h - border_thick), Qt.AlignLeft, self.versioned_seed.get_ui_string_version_plus_seed()) painter.drawText( QRect( 0, base_img.height() - 107, base_img.width() - total_distance_h - border_thick - 3 - qr_size, base_img.height() - total_distance_h - border_thick), Qt.AlignRight, self.versioned_seed.checksum) # draw qr code qr_qt = self.paintQR( self.versioned_seed.get_ui_string_version_plus_seed() + self.versioned_seed.checksum) target = QRectF(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, qr_size, qr_size) painter.drawImage(target, qr_qt) painter.setPen(QPen(Qt.black, 4)) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65 - qr_size, (base_img.height() - ((total_distance_h))) - ((border_thick * 8)) - (border_thick / 2) - 4) painter.drawLine(base_img.width() - 65 - qr_size, base_img.height() - 65 - qr_size, base_img.width() - 65, base_img.height() - 65 - qr_size) painter.end() else: # calibration only painter.end() cal_img = QImage(self.f_size.width() + 100, self.f_size.height() + 100, QImage.Format_ARGB32) cal_img.fill(Qt.white) cal_painter = QPainter() cal_painter.begin(cal_img) cal_painter.drawImage(0, 0, base_img) #black lines in the middle of border top left only cal_painter.setPen(QPen(Qt.black, 1, Qt.DashDotDotLine)) cal_painter.drawLine(0, dist_v, base_img.width(), dist_v) cal_painter.drawLine(dist_h, 0, dist_h, base_img.height()) pen = QPen(Qt.black, 2, Qt.DashDotDotLine) cal_painter.setPen(pen) n = 15 cal_painter.setFont(QFont("DejaVu Sans Mono", 21, QFont.Bold)) for x in range(-n, n): #lines on bottom (vertical calibration) cal_painter.drawLine((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - 13, x + 2 + base_img.height() - (dist_v), (((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) + 13, x + 2 + base_img.height() - (dist_v)) num_pos = 9 if x > 9: num_pos = 17 if x < 0: num_pos = 20 if x < -9: num_pos = 27 cal_painter.drawText((((base_img.width()) / (n * 2)) * (x)) + (base_img.width() / 2) - num_pos, 50 + base_img.height() - (dist_v), str(x)) #lines on the right (horizontal calibrations) cal_painter.drawLine( x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) - 13, x + 2 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / n) + (base_img.height() / 2) + 13) cal_painter.drawText(30 + (base_img.width() - (dist_h)), ((base_img.height() / (2 * n)) * (x)) + (base_img.height() / 2) + 13, str(x)) cal_painter.end() base_img = cal_img return base_img
def point(self, x, y): path = QPainterPath() path.moveTo(x, y) path.lineTo(x + 0.1, y) self.renderPath(path)
def calc_path(self): self.type = EDGE_DIRECT path = QPainterPath(QPointF(self.pos_src[0], self.pos_src[1])) path.lineTo(self.pos_dst[0], self.pos_dst[1]) return path
Returns: TYPE: Description """ for match in re.finditer(RE_DNA_PATTERN, text): index = match.start() length = match.end() - index self.setFormat(index, length, self.format) self.setCurrentBlockState(0) _BW = styles.PATH_BASE_WIDTH _PEN = getPenObj(styles.BLUE_STROKE, 1, capstyle=Qt.FlatCap) _RECT = QRectF(0, 0, _BW, _BW) _PATH_ARROW_LEFT = QPainterPath() _L3_POLY = QPolygonF() _L3_POLY.append(QPointF(_BW, 0)) _L3_POLY.append(QPointF(0.25 * _BW, 0.5 * _BW)) _L3_POLY.append(QPointF(_BW, _BW)) _PATH_ARROW_LEFT.addPolygon(_L3_POLY) _PATH_ARROW_RIGHT = QPainterPath() _R3_POLY = QPolygonF() # right-hand 3' arr _R3_POLY.append(QPointF(0, 0)) _R3_POLY.append(QPointF(0.75 * _BW, 0.5 * _BW)) _R3_POLY.append(QPointF(0, _BW)) _PATH_ARROW_RIGHT.addPolygon(_R3_POLY) T180 = QTransform() T180.rotate(180)
def paintEvent(self, _event: QPaintEvent): if not self.crop or not self.resolution: return painter = QPainter(self) # Keep a backup of the transform and create a new one transform = painter.worldTransform() # Set scaling transform transform = transform.scale(self.width() / self.resolution.width(), self.height() / self.resolution.height()) # Compute the transform to flip the coordinate system on the x axis transform_flip = QTransform() if self.flip_x: transform_flip = transform_flip.translate( float(self.resolution.width()), 0.0) transform_flip = transform_flip.scale(-1.0, 1.0) # Small helper for tuple to QPoint def toqp(point): return QPoint(int(point[0]), int(point[1])) # Starting from here we care about AA painter.setRenderHint(QPainter.Antialiasing) # Draw the QR code finder overlay painter.setWorldTransform(transform_flip * transform, False) painter.setOpacity(self.QR_FINDER_OPACITY) qr_finder_size = self.crop.size() * self.QR_FINDER_SIZE tmp = (self.crop.size() - qr_finder_size) / 2 qr_finder_pos = QPoint(tmp.width(), tmp.height()) + self.crop.topLeft() qr_finder_rect = QRect(qr_finder_pos, qr_finder_size) self.qr_finder.render(painter, QRectF(qr_finder_rect)) painter.setOpacity(1.0) # Draw all the QR code results for res in self.results: painter.setWorldTransform(transform_flip * transform, False) # Draw lines between all of the QR code points pen = QPen(self.qr_outline_pen) if res in self.validator_results.result_colors: pen.setColor(self.validator_results.result_colors[res]) painter.setPen(pen) num_points = len(res.points) for i in range(0, num_points): i_n = i + 1 line_from = toqp(res.points[i]) line_from += self.crop.topLeft() line_to = toqp( res.points[i_n] if i_n < num_points else res.points[0]) line_to += self.crop.topLeft() painter.drawLine(line_from, line_to) # Draw the QR code data # Note that we reset the world transform to only the scaled transform # because otherwise the text could be flipped. We only use transform_flip # to map the center point of the result. painter.setWorldTransform(transform, False) font_metrics = painter.fontMetrics() data_metrics = QSize(font_metrics.horizontalAdvance(res.data), font_metrics.capHeight()) center_pos = toqp(res.center) center_pos += self.crop.topLeft() center_pos = transform_flip.map(center_pos) text_offset = QPoint(data_metrics.width(), data_metrics.height()) text_offset = text_offset / 2 text_offset.setX(-text_offset.x()) center_pos += text_offset padding = self.BG_RECT_PADDING bg_rect_pos = center_pos - QPoint(padding, data_metrics.height() + padding) bg_rect_size = data_metrics + (QSize(padding, padding) * 2) bg_rect = QRect(bg_rect_pos, bg_rect_size) bg_rect_path = QPainterPath() radius = self.BG_RECT_CORNER_RADIUS bg_rect_path.addRoundedRect(QRectF(bg_rect), radius, radius, Qt.AbsoluteSize) painter.setPen(self.bg_rect_pen) painter.fillPath(bg_rect_path, self.bg_rect_fill) painter.drawPath(bg_rect_path) painter.setPen(self.text_pen) painter.drawText(center_pos, res.data)
def handleShapeDescription(self, shape, list, textOnly=False): if (shape.type() != "KoSvgTextShapeID" and textOnly is True): return shapeDesc = {} shapeDesc["name"] = shape.name() rect = shape.boundingBox() listOfPoints = [ rect.topLeft(), rect.topRight(), rect.bottomRight(), rect.bottomLeft() ] shapeDoc = minidom.parseString(shape.toSvg()) docElem = shapeDoc.documentElement svgRegExp = re.compile('[MLCSQHVATmlzcqshva]\d+\.?\d* \d+\.?\d*') transform = docElem.getAttribute("transform") coord = [] adjust = QTransform() # TODO: If we get global transform api, use that instead of parsing manually. if "translate" in transform: transform = transform.replace('translate(', '') for c in transform[:-1].split(" "): coord.append(float(c)) if len(coord) < 2: coord.append(coord[0]) adjust = QTransform(1, 0, 0, 1, coord[0], coord[1]) if "matrix" in transform: transform = transform.replace('matrix(', '') for c in transform[:-1].split(" "): coord.append(float(c)) adjust = QTransform(coord[0], coord[1], coord[2], coord[3], coord[4], coord[5]) path = QPainterPath() if docElem.localName == "path": dVal = docElem.getAttribute("d") listOfSvgStrings = [" "] listOfSvgStrings = svgRegExp.findall(dVal) if listOfSvgStrings: listOfPoints = [] for l in listOfSvgStrings: line = l[1:] coordinates = line.split(" ") if len(coordinates) < 2: coordinates.append(coordinates[0]) x = float(coordinates[-2]) y = float(coordinates[-1]) offset = QPointF() if l.islower(): offset = listOfPoints[0] if l.lower().startswith("m"): path.moveTo(QPointF(x, y) + offset) elif l.lower().startswith("h"): y = listOfPoints[-1].y() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("v"): x = listOfPoints[-1].x() path.lineTo(QPointF(x, y) + offset) elif l.lower().startswith("c"): path.cubicTo(coordinates[0], coordinates[1], coordinates[2], coordinates[3], x, y) else: path.lineTo(QPointF(x, y) + offset) path.setFillRule(Qt.WindingFill) for polygon in path.simplified().toSubpathPolygons(adjust): for point in polygon: listOfPoints.append(point) elif docElem.localName == "rect": listOfPoints = [] if (docElem.hasAttribute("x")): x = float(docElem.getAttribute("x")) else: x = 0 if (docElem.hasAttribute("y")): y = float(docElem.getAttribute("y")) else: y = 0 w = float(docElem.getAttribute("width")) h = float(docElem.getAttribute("height")) path.addRect(QRectF(x, y, w, h)) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "ellipse": listOfPoints = [] if (docElem.hasAttribute("cx")): x = float(docElem.getAttribute("cx")) else: x = 0 if (docElem.hasAttribute("cy")): y = float(docElem.getAttribute("cy")) else: y = 0 ry = float(docElem.getAttribute("ry")) rx = float(docElem.getAttribute("rx")) path.addEllipse(QPointF(x, y), rx, ry) for point in path.toFillPolygon(adjust): listOfPoints.append(point) elif docElem.localName == "text": # NOTE: This only works for horizontal preformated text. Vertical text needs a different # ordering of the rects, and wraparound should try to take the shape it is wrapped in. family = "sans-serif" if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") size = "11" if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") multilineText = True for el in docElem.childNodes: if el.nodeType == minidom.Node.TEXT_NODE: multilineText = False if multilineText: listOfPoints = [] listOfRects = [] # First we collect all the possible line-rects. for el in docElem.childNodes: if docElem.hasAttribute("font-family"): family = docElem.getAttribute("font-family") if docElem.hasAttribute("font-size"): size = docElem.getAttribute("font-size") fontsize = int(size) font = QFont(family, fontsize) string = el.toxml() string = re.sub("\<.*?\>", " ", string) string = string.replace(" ", " ") width = min( QFontMetrics(font).width(string.strip()), rect.width()) height = QFontMetrics(font).height() anchor = "start" if docElem.hasAttribute("text-anchor"): anchor = docElem.getAttribute("text-anchor") top = rect.top() if len(listOfRects) > 0: top = listOfRects[-1].bottom() if anchor == "start": spanRect = QRectF(rect.left(), top, width, height) listOfRects.append(spanRect) elif anchor == "end": spanRect = QRectF(rect.right() - width, top, width, height) listOfRects.append(spanRect) else: # Middle spanRect = QRectF(rect.center().x() - (width * 0.5), top, width, height) listOfRects.append(spanRect) # Now we have all the rects, we can check each and draw a # polygon around them. heightAdjust = ( rect.height() - (listOfRects[-1].bottom() - rect.top())) / len(listOfRects) for i in range(len(listOfRects)): span = listOfRects[i] addtionalHeight = i * heightAdjust if i == 0: listOfPoints.append(span.topLeft()) listOfPoints.append(span.topRight()) else: if listOfRects[i - 1].width() < span.width(): listOfPoints.append( QPointF(span.right(), span.top() + addtionalHeight)) listOfPoints.insert( 0, QPointF(span.left(), span.top() + addtionalHeight)) else: bottom = listOfRects[i - 1].bottom( ) + addtionalHeight - heightAdjust listOfPoints.append( QPointF(listOfRects[i - 1].right(), bottom)) listOfPoints.insert( 0, QPointF(listOfRects[i - 1].left(), bottom)) listOfPoints.append(QPointF(span.right(), rect.bottom())) listOfPoints.insert(0, QPointF(span.left(), rect.bottom())) path = QPainterPath() path.moveTo(listOfPoints[0]) for p in range(1, len(listOfPoints)): path.lineTo(listOfPoints[p]) path.closeSubpath() listOfPoints = [] for point in path.toFillPolygon(adjust): listOfPoints.append(point) shapeDesc["boundingBox"] = listOfPoints if (shape.type() == "KoSvgTextShapeID" and textOnly is True): shapeDesc["text"] = shape.toSvg() list.append(shapeDesc)
def shape(self): path = QPainterPath() path.addEllipse(self.boundingRect()) return path
from math import floor from cadnano.gui.views.pathview import pathstyles as styles import cadnano.gui.views.pathview.pathselection as pathselection import cadnano.util as util from PyQt5.QtCore import QPointF, QRectF, Qt, QObject, pyqtSignal from PyQt5.QtGui import QBrush, QPen, QColor, QPainterPath, QPolygonF from PyQt5.QtWidgets import QGraphicsItem, QGraphicsPathItem, QGraphicsRectItem, QGraphicsEllipseItem _BASE_WIDTH = styles.PATH_BASE_WIDTH PP_L5 = QPainterPath() # Left 5' PainterPath PP_R5 = QPainterPath() # Right 5' PainterPath PP_L3 = QPainterPath() # Left 3' PainterPath PP_R3 = QPainterPath() # Right 3' PainterPath PP_53 = QPainterPath() # Left 5', Right 3' PainterPath PP_35 = QPainterPath() # Left 5', Right 3' PainterPath # set up PP_L5 (left 5' blue square) PP_L5.addRect(0.25 * _BASE_WIDTH, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_R5 (right 5' blue square) PP_R5.addRect(0, 0.125 * _BASE_WIDTH, 0.75 * _BASE_WIDTH, 0.75 * _BASE_WIDTH) # set up PP_L3 (left 3' blue triangle) L3_POLY = QPolygonF() L3_POLY.append(QPointF(_BASE_WIDTH, 0)) L3_POLY.append(QPointF(0.25 * _BASE_WIDTH, 0.5 * _BASE_WIDTH)) L3_POLY.append(QPointF(_BASE_WIDTH, _BASE_WIDTH))
def showWedge(self, angle, color, extended=False, rev_gradient=False, outline_only=False): """Summary Args: angle (TYPE): Description color (TYPE): Description extended (bool, optional): Description rev_gradient (bool, optional): Description outline_only (bool, optional): Description """ # Hack to keep wedge in front # self.setRotation(self.pre_xover_item_group.rotation()) self._last_params = (angle, color, extended, rev_gradient, outline_only) radius = self._radius span = self.pre_xover_item_group.partCrossoverSpanAngle() / 2 radius_adjusted = radius + (_WEDGE_RECT_GAIN / 2) tip = QPointF(radius_adjusted, radius_adjusted) EXT = 1.35 if extended else 1.0 # print("wtf", tip, pos) base_p2 = QPointF(1, 1) line0 = QLineF(tip, QPointF(base_p2)) line1 = QLineF(tip, QPointF(base_p2)) line2 = QLineF(tip, QPointF(base_p2)) quad_scale = 1 + (.22 * (span - 5) / 55) # lo+(hi-lo)*(val-min)/(max-min) line0.setLength(radius_adjusted * EXT * quad_scale) # for quadTo control point line1.setLength(radius_adjusted * EXT) line2.setLength(radius_adjusted * EXT) line0.setAngle(angle) line1.setAngle(angle - span) line2.setAngle(angle + span) path = QPainterPath() if outline_only: self.setPen(getPenObj(color, 0.5, alpha=128, capstyle=Qt.RoundCap)) path.moveTo(line1.p2()) path.quadTo(line0.p2(), line2.p2()) else: gradient = QRadialGradient(tip, radius_adjusted * EXT) color1 = getColorObj(color, alpha=80) color2 = getColorObj(color, alpha=0) if rev_gradient: color1, color2 = color2, color1 if extended: gradient.setColorAt(0, color1) gradient.setColorAt(radius_adjusted / (radius_adjusted * EXT), color1) gradient.setColorAt( radius_adjusted / (radius_adjusted * EXT) + 0.01, color2) gradient.setColorAt(1, color2) else: gradient.setColorAt(0, getColorObj(color, alpha=50)) brush = QBrush(gradient) self.setBrush(brush) path.moveTo(line1.p1()) path.lineTo(line1.p2()) path.quadTo(line0.p2(), line2.p2()) path.lineTo(line2.p1()) self.setPath(path) self.show()
def clear_path(self): self.path_item.setPath(QPainterPath())
def createSquareGrid(self, part_item: SliceNucleicAcidPartItemT, radius: float, bounds: RectT): """Instantiate an area of griditems arranged on a square lattice. Args: part_item: Description radius: Description bounds: Description """ doLattice = SquareDnaPart.latticeCoordToModelXY doPosition = SquareDnaPart.positionToLatticeCoordRound x_l, x_h, y_l, y_h = bounds x_l = x_l + SquareDnaPart.PAD_GRID_XL x_h = x_h + SquareDnaPart.PAD_GRID_XH y_h = y_h + SquareDnaPart.PAD_GRID_YL y_l = y_l + SquareDnaPart.PAD_GRID_YH dot_size, half_dot_size = self.dots sf = part_item.scale_factor points = self.points row_l, col_l = doPosition(radius, x_l, -y_l, scale_factor=sf) row_h, col_h = doPosition(radius, x_h, -y_h, scale_factor=sf) redo_neighbors = (row_l, col_l, row_h, col_h) != \ self.previous_grid_bounds or self.previous_grid_type != self.grid_type self.previous_grid_type = self.grid_type if redo_neighbors: neighbor_map = dict() path = QPainterPath() is_pen_down = False draw_lines = self.draw_lines for row in range(row_l, row_h + 1): for column in range(col_l, col_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if draw_lines: if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) """ +x is Left and +y is down origin of ellipse is Top Left corner so we subtract half in X and subtract in y """ pt = GridPoint(x - half_dot_size, -y - half_dot_size, dot_size, self, coord=(row, column)) if self._draw_gridpoint_coordinates: font = QFont(styles.THE_FONT) path.addText(x - 10, -y + 5, font, "%s,%s" % (-row, column)) pt.setPen( getPenObj(styles.GRAY_STROKE, styles.EMPTY_HELIX_STROKE_WIDTH)) # if x == 0 and y == 0: # pt.setBrush(getBrushObj(Qt.gray)) points.append(pt) self.points_dict[(-row, column)] = pt if redo_neighbors: self.previous_grid_bounds = (row_l, col_l, row_h, col_h) is_pen_down = False # pen up # DO VERTICAL LINES if draw_lines: for column in range(col_l, col_h + 1): for row in range(row_l, row_h + 1): x, y = doLattice(radius, row, column, scale_factor=sf) if is_pen_down: path.lineTo(x, -y) else: is_pen_down = True path.moveTo(x, -y) is_pen_down = False # pen up self._path.setPath(path)
def paint(self, painter, xxx, xxx2): pos = self.toCanvasCoordinates(self.map_pos) self.setPos(pos) if self.marker_mode: mode = self.config.csettings["canvas_marker_mode"] if mode == 'auto': self.set_size(20) transform = self.canvas.getCoordinateTransform() start_point = transform.toMapCoordinates(pos.x(), pos.y()) map_end_point_width = endpoint(start_point, self.width, 90 + math.degrees(self.heading)) map_end_point_length = endpoint(start_point, self.length, math.degrees(self.heading)) # to canvas coordinates canvas_end_point_width = self.toCanvasCoordinates(map_end_point_width) canvas_end_point_length = self.toCanvasCoordinates(map_end_point_length) width = magnitude(self.toCanvasCoordinates(start_point), QgsPointXY(canvas_end_point_width)) height = magnitude(self.toCanvasCoordinates(start_point), QgsPointXY(canvas_end_point_length)) if width < self.size and height < self.size: self.changing_scale = self.canvas.scale() else: self.changing_scale = self.canvas.scale() * 2 elif mode == 'manual': self.changing_scale = self.config.csettings["canvas_marker_scale"] else: self.changing_scale = 400 if self.svg is None or self.canvas.scale() >= self.changing_scale: self.set_size(20) half_size = self.size / 2.0 rect = QRectF(0 - half_size, 0 - half_size, self.size, self.size) painter.setRenderHint(QPainter.Antialiasing) self.pointpen.setColor(Qt.black) self.pointpen.setWidth(2) self.pointbrush.setColor(self.color) painter.setBrush(self.pointbrush) painter.setPen(self.pointpen) y = 0 - half_size x = rect.width() / 2 - half_size line = QLine(x, y, x, rect.height() - half_size) y = rect.height() / 2 - half_size x = 0 - half_size line2 = QLine(x, y, rect.width() - half_size, y) # Arrow p = QPolygonF() p.append(QPoint(0 - half_size, 0)) p.append(QPoint(0, -self.size)) x = rect.width() - half_size p.append(QPoint(x, 0)) p.append(QPoint(0, 0)) offsetp = QPolygonF() offsetp.append(QPoint(0 - half_size, 0)) offsetp.append(QPoint(0, -self.size)) x = rect.width() - half_size offsetp.append(QPoint(x, 0)) offsetp.append(QPoint(0, 0)) painter.save() painter.rotate(math.degrees(self.heading) + self.canvas.rotation()) if self.orientation: path = QPainterPath() path.addPolygon(p) painter.drawPath(path) painter.restore() painter.drawEllipse(rect) painter.drawLine(line) painter.drawLine(line2) # svg valid elif self.svg is not None and self.svg.isValid(): # get rotation rotation = self.canvas.rotation() painter.save() transform = self.canvas.getCoordinateTransform() start_point = transform.toMapCoordinates(pos.x(), pos.y()) map_end_point_width = endpoint(start_point, self.width, 90 + math.degrees(self.heading)) map_end_point_length = endpoint(start_point, self.length, math.degrees(self.heading)) # to canvas coordinates canvas_end_point_width = self.toCanvasCoordinates(map_end_point_width) canvas_end_point_length = self.toCanvasCoordinates(map_end_point_length) width = magnitude(self.toCanvasCoordinates(start_point), QgsPointXY(canvas_end_point_width)) height = magnitude(self.toCanvasCoordinates(start_point), QgsPointXY(canvas_end_point_length)) if width > height: self.set_size(width) else: self.set_size(height) if width != 0 and height != 0: center_x = width / 2.0 center_y = height / 2.0 # work out how to shift the image so that it rotates # properly about its center # ( x cos a + y sin a - x, -x sin a + y cos a - y) myradians = math.radians(rotation + math.degrees(self.heading)) xshift = int(((center_x * math.cos(myradians)) + (center_y * math.sin(myradians))) - center_x) yshift = int(((-center_x * math.sin(myradians)) + (center_y * math.cos(myradians))) - center_y) painter.translate(-width / 2, -height / 2) painter.rotate(math.degrees(self.heading) + self.canvas.rotation()) self.svg.render(painter, QRectF(xshift, yshift, width, height)) painter.restore()
def paint(self, painter, option, widget): self.stabilize() if self.m_sticks: painter.setPen(Qt.white) for n1, n2 in Bones: node1 = self.m_nodes[n1] node2 = self.m_nodes[n2] painter.drawLine(node1.pos(), node2.pos()) else: # First bone is neck and will be used for head. path = QPainterPath() path.moveTo(self.posFor(0)) path.lineTo(self.posFor(1)) # Right arm. path.lineTo(self.posFor(2)) path.lineTo(self.posFor(6)) path.lineTo(self.posFor(7)) # Left arm. path.moveTo(self.posFor(3)) path.lineTo(self.posFor(8)) path.lineTo(self.posFor(9)) # Body. path.moveTo(self.posFor(2)) path.lineTo(self.posFor(4)) path.lineTo(self.posFor(10)) path.lineTo(self.posFor(11)) path.lineTo(self.posFor(5)) path.lineTo(self.posFor(3)) path.lineTo(self.posFor(1)) # Right leg. path.moveTo(self.posFor(10)) path.lineTo(self.posFor(12)) path.lineTo(self.posFor(13)) # Left leg. path.moveTo(self.posFor(11)) path.lineTo(self.posFor(14)) path.lineTo(self.posFor(15)) painter.setPen( QPen(self.m_penColor, 5.0, Qt.SolidLine, Qt.RoundCap)) painter.drawPath(path) n1, n2 = Bones[0] node1 = self.m_nodes[n1] node2 = self.m_nodes[n2] dist = node2.pos() - node1.pos() sinAngle = dist.x() / math.hypot(dist.x(), dist.y()) angle = math.degrees(math.asin(sinAngle)) headPos = node1.pos() painter.translate(headPos) painter.rotate(-angle) painter.setBrush(self.m_fillColor) painter.drawEllipse(QPointF(0, 0), 50.0, 50.0) painter.setBrush(self.m_penColor) painter.setPen( QPen(self.m_penColor, 2.5, Qt.SolidLine, Qt.RoundCap)) # Eyes. if self.m_isDead: painter.drawLine(-30.0, -30.0, -20.0, -20.0) painter.drawLine(-20.0, -30.0, -30.0, -20.0) painter.drawLine(20.0, -30.0, 30.0, -20.0) painter.drawLine(30.0, -30.0, 20.0, -20.0) else: painter.drawChord(QRectF(-30.0, -30.0, 25.0, 70.0), 30.0 * 16, 120.0 * 16) painter.drawChord(QRectF(5.0, -30.0, 25.0, 70.0), 30.0 * 16, 120.0 * 16) # Mouth. if self.m_isDead: painter.drawLine(-28.0, 2.0, 29.0, 2.0) else: painter.setBrush(QColor(128, 0, 64)) painter.drawChord(QRectF(-28.0, 2.0 - 55.0 / 2.0, 57.0, 55.0), 0.0, -180.0 * 16) # Pupils. if not self.m_isDead: painter.setPen( QPen(self.m_fillColor, 1.0, Qt.SolidLine, Qt.RoundCap)) painter.setBrush(self.m_fillColor) painter.drawEllipse(QPointF(-12.0, -25.0), 5.0, 5.0) painter.drawEllipse(QPointF(22.0, -25.0), 5.0, 5.0)
def endShape(self, mode, vertices, isCurve, isBezier, isQuadratic, isContour, shapeKind): if len(vertices) == 0: return closeShape = mode == CLOSE if closeShape and not isContour: vertices.append(vertices[0]) if isCurve and (shapeKind == POLYGON or shapeKind == None): s = 1 - self.curveTightness path = QPainterPath() path.moveTo(vertices[1][0], vertices[1][1]) for i in range(1, len(vertices) - 2): v = vertices[i] b = [] b.append([v[0], v[1]]) b.append([ v[0] + (s * vertices[i + 1][0] - s * vertices[i - 1][0]) / 6, v[1] + (s * vertices[i + 1][1] - s * vertices[i - 1][1]) / 6 ]) b.append([ vertices[i + 1][0] + (s * vertices[i][0] - s * vertices[i + 2][0]) / 6, vertices[i + 1][1] + (s * vertices[i][1] - s * vertices[i + 2][1]) / 6 ]) b.append([vertices[i + 1][0], vertices[i + 1][1]]) path.cubicTo( b[1][0], b[1][1], b[2][0], b[2][1], b[3][0], b[3][1] ) if closeShape: path.lineTo(vertices[i + 1][0], vertices[i + 1][1]) self.renderPath(path) elif isBezier and (shapeKind == POLYGON or shapeKind == None): path = QPainterPath() path.moveTo(vertices[0][0], vertices[0][1]) for v in vertices: if len(v) == 2: path.lineTo(v[0], v[1]) else: path.cubicTo( v[0], v[1], v[2], v[3], v[4], v[5], ) self.renderPath(path) elif isQuadratic and (shapeKind == POLYGON or shapeKind == None): path = QPainterPath() path.moveTo(vertices[0][0], vertices[0][1]) for v in vertices: if len(v) == 2: path.lineTo(v[0], v[1]) else: path.quadTo( v[0], v[1], v[2], v[3], ) self.renderPath(path) else: if shapeKind == POINTS: for p in vertices: self.point(p[0], p[1]) elif shapeKind == LINES: for i in range(0, len(vertices) - 1, 2): self.line(vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1]) elif shapeKind == TRIANGLES: for i in range(0, len(vertices) - 2, 3): self.triangle(vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1], vertices[i + 2][0], vertices[i + 2][1]) elif shapeKind == TRIANGLE_STRIP: for i in range(len(vertices) - 2): self.triangle(vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1], vertices[i + 2][0], vertices[i + 2][1]) elif shapeKind == TRIANGLE_FAN: for i in range(1, len(vertices) - 1): self.triangle(vertices[0][0], vertices[0][1], vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1]) elif shapeKind == QUADS: for i in range(0, len(vertices) - 3, 4): self.quad(vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1], vertices[i + 2][0], vertices[i + 2][1], vertices[i + 3][0], vertices[i + 3][1]) elif shapeKind == QUAD_STRIP: for i in range(0, len(vertices) - 3, 2): self.quad(vertices[i][0], vertices[i][1], vertices[i + 1][0], vertices[i + 1][1], vertices[i + 2][0], vertices[i + 2][1], vertices[i + 3][0], vertices[i + 3][1]) else: path = QPainterPath() path.moveTo(vertices[0][0], vertices[0][1]) for p in vertices: path.lineTo(p[0], p[1]) self.renderPath(path) return
def GetLinePath(points: List[Tuple[int, int]]): """Returns a drawable line path representing. Points should be a list of tuples representing (x, y) pixel values.""" path = QPainterPath() path.moveTo(*points[0]) [path.lineTo(x, y) for x, y in points] return path
def line(self, x1, y1, x2, y2): path = QPainterPath() path.moveTo(x1, y1) path.lineTo(x2, y2) self.renderPath(path)
def _insertGen(path, start, c1, p1, c2): path.moveTo(start) path.quadTo(c1, p1) path.quadTo(c2, start) # end def _PATH_START = QPointF(_HBW, _HBW) _PATH_MID_UP = QPointF(_HBW, -_BW) _PATH_UP_UP_CTRL_PT = QPointF(-_HBW, -_BW) _PATH_UP_DOWN_CTRL_PT = QPointF(1.5 * _BW, -_BW) _PATH_MID_DOWN = QPointF(_HBW, 2 * _BW) _PATH_DOWN_DOWN_CTRL_PT = QPointF(-_HBW, 2 * _BW) _PATH_DOWN_UP_CTRL_PT = QPointF(1.5 * _BW, 2 * _BW) _INSERT_PATH_UP = QPainterPath() _insertGen(_INSERT_PATH_UP, _PATH_START, _PATH_UP_UP_CTRL_PT,\ _PATH_MID_UP, _PATH_UP_DOWN_CTRL_PT) _INSERT_PATH_UP.translate(_OFFSET1, 0) _INSERT_PATH_UP_RECT = _INSERT_PATH_UP.boundingRect() _INSERT_PATH_DOWN = QPainterPath() _insertGen(_INSERT_PATH_DOWN, _PATH_START, _PATH_DOWN_DOWN_CTRL_PT,\ _PATH_MID_DOWN, _PATH_DOWN_UP_CTRL_PT) _INSERT_PATH_DOWN.translate(_OFFSET1, 0) _INSERT_PATH_DOWNRect = _INSERT_PATH_DOWN.boundingRect() _BIG_RECT = _DEFAULT_RECT.united(_INSERT_PATH_UP_RECT) _BIG_RECT = _BIG_RECT.united(_INSERT_PATH_DOWNRect) _B_PEN2 = QPen(styles.BLUE_STROKE, 2) _OFFSET2 = _BW * 0.75 _FONT = QFont(styles.THE_FONT, 10, QFont.Bold)
def path(self): """Return the items path. """ return QPainterPath(self.__path)
def shape(self): path = QPainterPath() path.addPolygon(self.selection_polygon) return path
def createGraphics(self): """ Create the graphical representation of the FMU's inputs and outputs """ def variableColor(variable): if variable.type == 'Real': return QColor.fromRgb(0, 0, 127) elif variable.type in ['Integer', 'Enumeration']: return QColor.fromRgb(255, 127, 0) elif variable.type == 'Boolean': return QColor.fromRgb(255, 0, 255) elif variable.type == 'String': return QColor.fromRgb(0, 128, 0) else: return QColor.fromRgb(0, 0, 0) inputVariables = [] outputVariables = [] maxInputLabelWidth = 0 maxOutputLabelWidth = 0 textItem = QGraphicsTextItem() fontMetrics = QFontMetricsF(textItem.font()) for variable in self.modelDescription.modelVariables: if variable.causality == 'input': inputVariables.append(variable) elif variable.causality == 'output': outputVariables.append(variable) for variable in inputVariables: maxInputLabelWidth = max(maxInputLabelWidth, fontMetrics.width(variable.name)) for variable in outputVariables: maxOutputLabelWidth = max(maxOutputLabelWidth, fontMetrics.width(variable.name)) from math import floor scene = QGraphicsScene() self.ui.graphicsView.setScene(scene) group = QGraphicsItemGroup() scene.addItem(group) group.setPos(200.5, -50.5) lh = 15 # line height w = max(150., maxInputLabelWidth + maxOutputLabelWidth + 20) h = max(50., 10 + lh * max(len(inputVariables), len(outputVariables))) block = QGraphicsRectItem(0, 0, w, h, group) block.setPen(QColor.fromRgb(0, 0, 255)) pen = QPen() pen.setWidthF(1) font = QFont() font.setPixelSize(10) # inputs y = floor((h - len(inputVariables) * lh) / 2 - 2) for variable in inputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 255)) text.setFont(font) text.setX(3) text.setY(y) polygon = QPolygonF([ QPointF(-13.5, y + 4), QPointF(1, y + 11), QPointF(-13.5, y + 18) ]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) contour.setPen(QPen(Qt.NoPen)) contour.setBrush(variableColor(variable)) y += lh # outputs y = floor((h - len(outputVariables) * lh) / 2 - 2) for variable in outputVariables: text = QGraphicsTextItem(variable.name, group) text.setDefaultTextColor(QColor.fromRgb(0, 0, 255)) text.setFont(font) text.setX(w - 3 - text.boundingRect().width()) text.setY(y) polygon = QPolygonF([ QPointF(w, y + 0 + 7.5), QPointF(w + 7, y + 3.5 + 7.5), QPointF(w, y + 7 + 7.5) ]) path = QPainterPath() path.addPolygon(polygon) path.closeSubpath() contour = QGraphicsPathItem(path, group) pen = QPen() pen.setColor(variableColor(variable)) pen.setJoinStyle(Qt.MiterJoin) contour.setPen(pen) y += lh
def paintEvent(self, event): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) painter.setRenderHint(QPainter.TextAntialiasing) R = 100 Pi = 3.14159 deg = Pi * 72 / 180 points = [ QPoint(R, 0), QPoint(R * math.cos(deg), -R * math.sin(deg)), QPoint(R * math.cos(2 * deg), -R * math.sin(2 * deg)), QPoint(R * math.cos(3 * deg), -R * math.sin(3 * deg)), QPoint(R * math.cos(4 * deg), -R * math.sin(4 * deg)) ] font = painter.font() font.setPointSize(12) font.setBold(False) painter.setFont(font) pen = QPen() pen.setWidth(2) pen.setColor(Qt.blue) pen.setStyle(Qt.SolidLine) pen.setCapStyle(Qt.FlatCap) pen.setJoinStyle(Qt.BevelJoin) painter.setPen(pen) brush = QBrush() brush.setColor(Qt.yellow) brush.setStyle(Qt.SolidPattern) painter.setBrush(brush) starPath = QPainterPath() starPath.moveTo(points[0]) starPath.lineTo(points[2]) starPath.lineTo(points[4]) starPath.lineTo(points[1]) starPath.lineTo(points[3]) starPath.closeSubpath() starPath.addText(points[0], font, "0") starPath.addText(points[1], font, "1") starPath.addText(points[2], font, "2") starPath.addText(points[3], font, "3") starPath.addText(points[4], font, "4") painter.save() painter.translate(100, 120) painter.drawPath(starPath) painter.drawText(0, 0, "S1") painter.restore() painter.translate(300, 120) painter.scale(0.8, 0.8) painter.rotate(90) painter.drawPath(starPath) painter.drawText(0, 0, "S2") painter.resetTransform() painter.translate(500, 120) painter.rotate(-145) painter.drawPath(starPath) painter.drawText(0, 0, "S3")
def updateLinePos(self, scenePos): if self.m_ready_to_disc: if self.m_port_type == PORT_TYPE_AUDIO_JACK: pen = QPen(canvas.theme.line_audio_jack_sel, 2, Qt.DotLine) elif self.m_port_type == PORT_TYPE_MIDI_JACK: pen = QPen(canvas.theme.line_midi_jack_sel, 2, Qt.DotLine) elif self.m_port_type == PORT_TYPE_MIDI_ALSA: pen = QPen(canvas.theme.line_midi_alsa_sel, 2, Qt.DotLine) elif self.m_port_type == PORT_TYPE_PARAMETER: pen = QPen(canvas.theme.line_parameter_sel, 2, Qt.DotLine) else: pen = QPen(Qt.black) else: if self.m_port_type == PORT_TYPE_AUDIO_JACK: pen = QPen(canvas.theme.line_audio_jack_sel, 2) elif self.m_port_type == PORT_TYPE_MIDI_JACK: pen = QPen(canvas.theme.line_midi_jack_sel, 2) elif self.m_port_type == PORT_TYPE_MIDI_ALSA: pen = QPen(canvas.theme.line_midi_alsa_sel, 2) elif self.m_port_type == PORT_TYPE_PARAMETER: pen = QPen(canvas.theme.line_parameter_sel, 2) else: pen = QPen(Qt.black) pen.setCapStyle(Qt.FlatCap) pen.setWidthF(pen.widthF() + 0.00001) self.setPen(pen) phi = 0.75 if self.m_portgrp_lenght > 2 else 0.62 phito = 0.75 if self.m_portgrp_lenght_to > 2 else 0.62 if self.parentItem().type() == CanvasPortType: if self.m_portgrp_lenght > 1: first_old_y = canvas.theme.port_height * phi last_old_y = canvas.theme.port_height * ( self.m_portgrp_lenght - phi) delta = (last_old_y - first_old_y) / (self.m_portgrp_lenght - 1) old_y = first_old_y + (self.m_port_posinportgrp * delta) \ - canvas.theme.port_height * self.m_port_posinportgrp else: old_y = canvas.theme.port_height / 2 if self.m_portgrp_lenght_to == 1: new_y = 0 else: first_new_y = canvas.theme.port_height * phito last_new_y = canvas.theme.port_height * ( self.m_portgrp_lenght_to - phito) delta = (last_new_y - first_new_y) / (self.m_portgrp_lenght_to - 1) new_y1 = first_new_y + (self.m_port_posinportgrp_to * delta) new_y = new_y1 - ( (last_new_y - first_new_y) / 2 ) \ - canvas.theme.port_height * phito elif self.parentItem().type() == CanvasPortGroupType: first_old_y = canvas.theme.port_height * phi last_old_y = canvas.theme.port_height * (self.m_portgrp_lenght - phi) delta = (last_old_y - first_old_y) / (self.m_portgrp_lenght - 1) old_y = first_old_y + (self.m_port_posinportgrp * delta) if self.m_portgrp_lenght_to == 1: new_y = 0 elif (self.m_port_posinportgrp_to == self.m_port_posinportgrp and self.m_portgrp_lenght == self.m_portgrp_lenght_to): new_y = old_y - ( (last_old_y - first_old_y) / 2 ) \ - (canvas.theme.port_height * phi) else: first_new_y = canvas.theme.port_height * phito last_new_y = canvas.theme.port_height * ( self.m_portgrp_lenght_to - phito) delta = (last_new_y - first_new_y) / (self.m_portgrp_lenght_to - 1) new_y1 = first_new_y + (self.m_port_posinportgrp_to * delta) new_y = new_y1 - ( (last_new_y - first_new_y) / 2 ) \ - (canvas.theme.port_height * phito) final_x = scenePos.x() - self.p_itemX final_y = scenePos.y() - self.p_itemY + new_y if self.m_port_mode == PORT_MODE_OUTPUT: old_x = self.p_width + 12 mid_x = abs(final_x - old_x) / 2 new_x1 = old_x + mid_x new_x2 = final_x - mid_x diffxy = abs(final_y - old_y) - abs(final_x - old_x) if diffxy > 0: new_x1 += abs(diffxy) new_x2 -= abs(diffxy) elif self.m_port_mode == PORT_MODE_INPUT: old_x = 0 mid_x = abs(final_x - old_x) / 2 new_x1 = old_x - mid_x new_x2 = final_x + mid_x diffxy = abs(final_y - old_y) - abs(final_x - old_x) if diffxy > 0: new_x1 -= abs(diffxy) new_x2 += abs(diffxy) else: return path = QPainterPath(QPointF(old_x, old_y)) path.cubicTo(new_x1, old_y, new_x2, final_y, final_x, final_y) self.setPath(path)
def drawBezierCurve(self, qp): path = QPainterPath() path.moveTo(30, 30) path.cubicTo(30, 30, 200, 350, 350, 30) qp.drawPath(path)
def _itemsAt(self, func, obj, justOne=True): """ Go through all anchors, points and components (in this order) in the glyph, construct their canvas path and list items for which *func(path, obj)* returns True, or only return the first item if *justOne* is set to True. An item is a (point, contour) or (anchor, None) or (component, None) tuple. The second argument permits accessing parent contour to post notifications. Here is a sample *func* function that tests whether item with path *path* contains *pos*: def myFunction(path, pos): return path.contains(pos) This is useful to find out whether an item was clicked on canvas. """ scale = self._inverseScale # TODO: export this from drawing or use QSettings. # anchor anchorSize = 6 * scale anchorHalfSize = anchorSize / 2 # offCurve offWidth = 5 * scale offHalf = offWidth / 2.0 # onCurve onWidth = 7 * scale onHalf = onWidth / 2.0 # onCurve smooth smoothWidth = 8 * scale smoothHalf = smoothWidth / 2.0 if not justOne: ret = dict( anchors=[], contours=[], points=[], components=[], ) for anchor in reversed(self._glyph.anchors): path = QPainterPath() path.addEllipse(anchor.x - anchorHalfSize, anchor.y - anchorHalfSize, anchorSize, anchorSize) if func(path, obj): if justOne: return (anchor, None) ret["anchors"].append(anchor) for contour in reversed(self._glyph): for point in contour: path = QPainterPath() if point.segmentType is None: x = point.x - offHalf y = point.y - offHalf path.addEllipse(x, y, offWidth, offWidth) elif point.smooth: x = point.x - smoothHalf y = point.y - smoothHalf path.addEllipse(x, y, smoothWidth, smoothWidth) else: x = point.x - onHalf y = point.y - onHalf path.addRect(x, y, onWidth, onWidth) if func(path, obj): if justOne: return (point, contour) ret["contours"].append(contour) ret["points"].append(point) for component in reversed(self._glyph.components): path = component.getRepresentation("defconQt.QPainterPath") if func(path, obj): if justOne: return (component, None) ret["components"].append(component) if not justOne: return ret return None
def _load(self): # Get list of all map files for current zone map_file_name = MapData.get_zone_dict()[self.zone.strip().lower()] extensions = ['.txt', '_1.txt', '_2.txt', '_3.txt', '_4.txt', '_5.txt'] maps = [ os.path.join(MAP_FILES_LOCATION, m) for m in [(map_file_name + e) for e in extensions] if os.path.exists(os.path.join(MAP_FILES_LOCATION, m)) ] all_x, all_y, all_z = [], [], [] # TODO: Remove the references to raw # Create Lines and Points for map_file in maps: with open(map_file, 'r') as f: for line in f.readlines(): line_type = line.lower()[0:1] data = [value.strip() for value in line[1:].split(',')] if line_type == 'l': # line x1, y1, z1, x2, y2, z2 = list(map(float, data[0:6])) self.raw['lines'].append( MapLine(x1=x1, y1=y1, z1=z1, x2=x2, y2=y2, z2=z2, color=self.color_transform( QColor(int(data[6]), int(data[7]), int(data[8]))))) all_x.extend((x1, x2)) all_y.extend((y1, y2)) all_z.append(min(z1, z2)) # if abs(z1 - z2) < 2: # if z1 == z2: # all_z.extend((z1, z2)) elif line_type == 'p': # point x, y, z = map(float, data[0:3]) self.raw['poi'].append( MapPoint(x=x, y=y, z=z, size=int(data[6]), text=str(data[7]), color=self.color_transform( QColor(int(data[3]), int(data[4]), int(data[5]))))) # Create Grid Lines lowest_x, highest_x, lowest_y, highest_y, lowest_z, highest_z = min( all_x), max(all_x), min(all_y), max(all_y), min(all_z), max(all_z) left, right = int(math.floor(lowest_x / 1000) * 1000), int( math.ceil(highest_x / 1000) * 1000) top, bottom = int(math.floor(lowest_y / 1000) * 1000), int( math.ceil(highest_y / 1000) * 1000) for number in range(left, right + 1000, 1000): self.raw['grid'].append( MapLine(x1=number, x2=number, y1=top, y2=bottom, z1=0, z2=0, color=QColor(255, 255, 255, 25))) for number in range(top, bottom + 1000, 1000): self.raw['grid'].append( MapLine(y1=number, y2=number, x1=left, x2=right, z1=0, z2=0, color=QColor(255, 255, 255, 25))) self.grid = QGraphicsPathItem() line_path = QPainterPath() for line in self.raw['grid']: line_path.moveTo(line.x1, line.y1) line_path.lineTo(line.x2, line.y2) self.grid.setPath(line_path) self.grid.setPen( QPen(line.color, config.data['maps']['grid_line_width'])) self.grid.setZValue(0) # Get z levels counter = Counter(all_z) # bunch together zgroups based on peaks with floor being low point before rise z_groups = [] last_value = None first_run = True for z in sorted(counter.items(), key=lambda x: x[0]): if last_value is None: last_value = z continue if (abs(last_value[0] - z[0]) < 20) or z[1] < 8: last_value = (last_value[0], last_value[1] + z[1]) else: if first_run: first_run = False if last_value[1] < 40 or abs(last_value[0] - z[0]) < 18: last_value = z continue z_groups.append(last_value[0]) last_value = z # get last iteration if last_value[1] > 50: z_groups.append(last_value[0]) self._z_groups = z_groups # Create QGraphicsPathItem for lines seperately to retain colors temp_dict = {} for l in self.raw['lines']: lz = min(l.z1, l.z2) lz = self.get_closest_z_group(lz) if not temp_dict.get(lz, None): temp_dict[lz] = {'paths': {}} lc = l.color.getRgb() if not temp_dict[lz]['paths'].get(lc, None): path_item = QGraphicsPathItem() path_item.setPen( QPen(l.color, config.data['maps']['line_width'])) temp_dict[lz]['paths'][lc] = path_item path = temp_dict[lz]['paths'][lc].path() path.moveTo(l.x1, l.y1) path.lineTo(l.x2, l.y2) temp_dict[lz]['paths'][lc].setPath(path) # Group QGraphicsPathItems into QGraphicsItemGroups and update self for z in temp_dict.keys(): item_group = QGraphicsItemGroup() for (_, path) in temp_dict[z]['paths'].items(): item_group.addToGroup(path) self[z] = {'paths': None, 'poi': []} self[z]['paths'] = item_group # Create Points of Interest for p in self.raw['poi']: z = self.get_closest_z_group(p.z) self[z]['poi'].append(PointOfInterest(location=p)) self.geometry = MapGeometry( lowest_x=lowest_x, highest_x=highest_x, lowest_y=lowest_y, highest_y=highest_y, lowest_z=lowest_z, highest_z=highest_z, center_x=int(highest_x - (highest_x - lowest_x) / 2), center_y=int(highest_y - (highest_y - lowest_y) / 2), width=int(highest_x - lowest_x), height=int(highest_y - lowest_y), z_groups=z_groups)