def counterClockwise(polygon: []): poly = QPolygon() for p in polygon: poly.append(QPoint(p[0], p[1])) rect = poly.boundingRect() center = rect.center() return polygon
def create_hexagon(x0, y0, hex_a): polygon = QPolygon() polygon.append(QPoint(x0, y0 + hex_a)) polygon.append(QPoint(x0 + hex_a, y0)) polygon.append(QPoint(x0 + 2 * hex_a, y0 + hex_a)) polygon.append(QPoint(x0 + 2 * hex_a, y0 + 2 * hex_a)) polygon.append(QPoint(x0 + hex_a, y0 + 3 * hex_a)) polygon.append(QPoint(x0, y0 + 2 * hex_a)) return polygon
def paintEvent(self, event): QWidget.paintEvent(self, event) width, height = self.width(), self.height() polygon = QPolygon() for i, rate in enumerate(self.loads): x = width - i * self.pointDistance y = height - rate * height if x < self.boxWidth: break polygon.append(QPoint(x, y)) painter = QPainter(self) pen = QPen() pen.setColor(Qt.darkGreen) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing, True) #画网格 painter.setOpacity(0.5) gridSize = self.pointDistance * 4 deltaX = (width - self.boxWidth) % gridSize + self.boxWidth deltaY = height % gridSize for i in range(int(width / gridSize)): x = deltaX + gridSize * i painter.drawLine(x, 0, x, height) for j in range(int(height / gridSize)): y = j * gridSize + deltaY painter.drawLine(self.boxWidth, y, width, y) #画折线 pen.setColor(Qt.darkCyan) pen.setWidth(2) painter.setPen(pen) painter.setOpacity(1) painter.drawPolyline(polygon) #画展示框 if len(self.loads) > 0: rate = self.loads[0] else: rate = 1.0 rect1 = QRect(4, height * 0.05, self.boxWidth - 9, height * 0.7) rect2 = QRect(4, height * 0.8, self.boxWidth - 9, height * 0.2) centerX = int(rect1.width() / 2) + 1 pen.setWidth(1) for i in range(rect1.height()): if i % 4 == 0: continue if (rect1.height() - i) / rect1.height() > rate: pen.setColor(Qt.darkGreen) else: pen.setColor(Qt.green) painter.setPen(pen) for j in range(rect1.width()): if centerX - 1 <= j <= centerX + 1: continue painter.drawPoint(rect1.x() + j, rect1.y() + i) pen.setColor(Qt.black) painter.setPen(pen) painter.drawText(rect2, Qt.AlignHCenter | Qt.AlignVCenter, str(int(rate * 100)) + "%")
def draw_mesh(self, canvas): """ Divide figure and it's air-rectangles by right triangles """ M = self.mesh scale = self.generate_scaler() form = self.mesh.data["form"] # Draw air surroundings canvas.setPen(self.COL_AIR) if M.NAT != 0: self.draw_rect_mesh(canvas, 0, 0, M.NAL + M.NFX + M.NAR, M.NAT) if M.NAB != 0: self.draw_rect_mesh(canvas, 0, M.NAT + M.NFY, M.NAL + M.NFX + M.NAR, M.NAB) if M.NAL != 0: self.draw_rect_mesh(canvas, 0, M.NAT, M.NAL, M.NFY) if M.NAR != 0: self.draw_rect_mesh(canvas, M.NAL + M.NFX, M.NAT, M.NAR, M.NFY) # Draw contour of mirrored air part most_left_x, most_left_y = scale(self.vertexes[0]) most_right_x, most_right_y = scale(self.vertexes[1]) third_x, third_y = scale(self.vertexes[2]) if form == 0: canvas.drawLine(most_left_x, most_left_y, most_right_x, most_left_y) canvas.drawLine(most_right_x, most_right_y, most_right_x, most_left_y) elif form == 1: canvas.drawLine(most_left_x, most_right_y, most_right_x, most_right_y) canvas.drawLine(most_left_x, most_right_y, most_left_x, most_left_y) elif form == 2: canvas.drawLine(most_left_x, third_y, most_right_x, third_y) canvas.drawLine(most_right_x, most_right_y, most_right_x, third_y) elif form == 3: canvas.drawLine(most_left_x, third_y, most_right_x, third_y) canvas.drawLine(most_left_x, most_left_y, most_left_x, third_y) # Draw the figure and complete it to rectangle with air canvas.setPen(self.COL_FIG) self.draw_figure_mesh(canvas, form) # Fill the figure the_figure = QPolygon() for vertex in self.vertexes: x, y = scale(vertex) the_figure.append(QPoint(x, y)) the_figure.append(the_figure.first()) # close the polygon canvas.setPen(self.COL_FIG) canvas.setBrush(QBrush(self.COL_FIG_INNNER)) # drawPolygon() use it canvas.drawPolygon(the_figure)
def mouseReleaseEvent(self, event): super(GraphicsScene, self).mousePressEvent(event) pos = event.scenePos() if event.button() == Qt.LeftButton: self.draw_switch = False if pos.x()>=0 \ and pos.x()<self.pixmapunderground.width() \ and pos.y()>=0 \ and pos.y()<self.pixmapunderground.height(): label = self.dialog.gettext() #ask for label if label[1] == True and len(label[0]) > 0 and len( self.poly) > 0: #if user input a label # save the label on backend if len(self.poly) > 1: # point the label on screen poly = QPolygon() for p in self.poly: poly.append(p.toPoint()) # print(p) brush = QBrush() labelcolor = QColor(*[ c * 255 for c in plt.get_cmap('tab10').colors[int(label[0]) - 1] ]) brush.setColor(labelcolor) brush.setStyle(Qt.SolidPattern) self.addPolygon(QPolygonF(poly), pen=QPen(labelcolor), brush=brush) x, y = polygon([p.toPoint().x() for p in self.poly], [p.toPoint().y() for p in self.poly]) else: self.addEllipse(self.poly[0].x(), self.poly[0].y(), 2, 2, pen=QPen(Qt.red)) x = self.poly[0].toPoint().x() y = self.poly[0].toPoint().y() self.geodata.manuallabel[y, x] = int(label[0]) # remove the trace painted so far for p in self.pathset: self.removeItem(p)
def draw_item(self, face, painter): is_draw = True if self.is_clipping: is_draw = self.sphere.is_face_visible(face) if is_draw: polygon = QPolygon() for index, point_index in enumerate(face): p1_x = int(self.sphere.geom.points[face[index - 1]][0]) p1_y = int(self.sphere.geom.points[face[index - 1]][1]) p1_z = int(self.sphere.geom.points[face[index - 1]][2]) p2_x = int(self.sphere.geom.points[point_index][0]) p2_y = int(self.sphere.geom.points[point_index][1]) p2_z = int(self.sphere.geom.points[point_index][2]) if self.sphere.projection_name == "front": # Фронтальная проекция (вид спереди) -> z = 0 real_p1 = QPoint(p1_x, p1_y) real_p2 = QPoint(p2_x, p2_y) elif self.sphere.projection_name == "horizontal": # Горизонтальная проекция (вид сверху) -> y = 0 real_p1 = QPoint(p1_x, p1_z) real_p2 = QPoint(p2_x, p2_z) elif self.sphere.projection_name == "profile": # Профильная проекция (вид сбоку) -> x = 0 real_p1 = QPoint(p1_y, p1_z) real_p2 = QPoint(p2_y, p2_z) else: real_p1 = QPoint(p1_x, p1_y) real_p2 = QPoint(p2_x, p2_y) # Точки для проволочного рисования real_p1.setX(self.width() / 2 + real_p1.x()) real_p1.setY(self.height() / 2 - real_p1.y()) real_p2.setX(self.width() / 2 + real_p2.x()) real_p2.setY(self.height() / 2 - real_p2.y()) # Полигоны для рисования с цветом polygon.append(real_p1) polygon.append(real_p2) if not self.is_light: painter.drawLine(real_p1, real_p2) if self.is_light: painter.setBrush( self.sphere.get_face_light(face, self.faces_color)) painter.drawPolygon(polygon)
def draw_item(self, face, painter): is_draw = True if self.is_clipping: is_draw = self.sphere.is_face_visible(face) if is_draw: polygon = QPolygon() for index, point_index in enumerate(face): p1_x = int(self.sphere.geom.points[face[index-1]][0]) p1_y = int(self.sphere.geom.points[face[index-1]][1]) p1_z = int(self.sphere.geom.points[face[index-1]][2]) p2_x = int(self.sphere.geom.points[point_index][0]) p2_y = int(self.sphere.geom.points[point_index][1]) p2_z = int(self.sphere.geom.points[point_index][2]) if self.sphere.projection_name == "front": # Фронтальная проекция (вид спереди) -> z = 0 real_p1 = QPoint(p1_x, p1_y) real_p2 = QPoint(p2_x, p2_y) elif self.sphere.projection_name == "horizontal": # Горизонтальная проекция (вид сверху) -> y = 0 real_p1 = QPoint(p1_x, p1_z) real_p2 = QPoint(p2_x, p2_z) elif self.sphere.projection_name == "profile": # Профильная проекция (вид сбоку) -> x = 0 real_p1 = QPoint(p1_y, p1_z) real_p2 = QPoint(p2_y, p2_z) else: real_p1 = QPoint(p1_x, p1_y) real_p2 = QPoint(p2_x, p2_y) # Точки для проволочного рисования real_p1.setX(self.width()/2 + real_p1.x()) real_p1.setY(self.height()/2 - real_p1.y()) real_p2.setX(self.width()/2 + real_p2.x()) real_p2.setY(self.height()/2 - real_p2.y()) # Полигоны для рисования с цветом polygon.append(real_p1) polygon.append(real_p2) if not self.is_light: painter.drawLine(real_p1, real_p2) if self.is_light: painter.setBrush(self.sphere.get_face_light(face, self.faces_color)) painter.drawPolygon(polygon)
def draw_element(self, canvas, A, B, C, material, scale): first = QPoint(*scale(A)) second = QPoint(*scale(B)) third = QPoint(*scale(C)) element = QPolygon() element.append(first) element.append(second) element.append(third) element.append(first) if material == 1: canvas.setPen(COL_FIG) canvas.setBrush(QBrush(COL_FIG_INNNER)) # drawPolygon() use it else: canvas.setPen(COL_AIR) canvas.setBrush(QBrush(COL_AIR_INNER)) canvas.drawPolygon(element)
def draw_y_axis(self, qp, size): qp.setPen(self.gray_pen) qp.setBrush(self.gray_brush) unit_text_width = self.fm.size(Qt.TextSingleLine, self.y_unit).width() time_text_height = self.fm.size(Qt.TextSingleLine, "12:00").height() qp.drawLine(self.padding + unit_text_width + 1, size.height() - time_text_height + 4 - self.padding, self.padding + unit_text_width + 1, self.padding) polygon = QPolygon() polygon.append(QPoint(self.padding + unit_text_width + 1, self.padding)) polygon.append( QPoint(self.padding + unit_text_width + 1 - 4, self.padding + 6)) polygon.append( QPoint(self.padding + unit_text_width + 1 + 4, self.padding + 6)) qp.drawPolygon(polygon, fillRule=Qt.WindingFill) if self.y_range[1] - self.y_range[0] > 0: self.draw_y_axis_labels(qp, size, unit_text_width, time_text_height) qp.setFont(self.font) qp.setPen(self.text_pen) qp.drawText(self.padding, self.padding + 15, self.y_unit)
def draw_x_axis(self, qp, size): qp.setPen(self.gray_pen) qp.setBrush(self.gray_brush) unit_text_width = self.fm.size(Qt.TextSingleLine, self.y_unit).width() time_text_height = self.fm.size(Qt.TextSingleLine, "12:00").height() qp.drawLine(self.padding + unit_text_width + 1 - 4, size.height() - time_text_height - self.padding, size.width() - self.padding, size.height() - time_text_height - self.padding) polygon = QPolygon() polygon.append( QPoint(size.width() - self.padding, size.height() - time_text_height - self.padding)) polygon.append( QPoint(size.width() - self.padding - 6, size.height() - time_text_height - self.padding + 4)) polygon.append( QPoint(size.width() - self.padding - 6, size.height() - time_text_height - self.padding - 4)) qp.drawPolygon(polygon, fillRule=Qt.WindingFill) if self.x_range[1] - self.x_range[0] > timedelta(seconds=0): self.draw_x_axis_labels(qp, size, unit_text_width, time_text_height)
def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor("#888888"))) path1 = QPainterPath() path1.moveTo(5, 5) path1.cubicTo(40, 5, 50, 50, 99, 99) path1.cubicTo(5, 99, 50, 50, 5, 5) painter.drawPath(path1) painter.drawPie(130, 20, 90, 60, 30 * 16, 120 * 16) painter.drawChord(240, 30, 90, 60, 0, 16 * 180) painter.drawRoundedRect(20, 120, 80, 50, 10, 10) polygon = QPolygon() polygon.append(QPoint(130, 140)) polygon.append(QPoint(180, 170)) polygon.append(QPoint(180, 140)) polygon.append(QPoint(220, 110)) polygon.append(QPoint(140, 100)) painter.drawPolygon(polygon) painter.drawRect(250, 110, 60, 60) baseline = QPointF(20, 250) font = QFont("Georgia", 55) path2 = QPainterPath() path2.addText(baseline, font, "Q") painter.drawPath(path2) painter.drawEllipse(140, 200, 60, 60) painter.drawEllipse(240, 200, 90, 60)
def _paint_arrows(self): def transform(x, y, r, x0, y0): return QPoint(x0 + math.cos(r) * x - math.sin(r) * y, y0 + math.sin(r) * x + math.cos(r) * y) self.arrow_panel.setStyleSheet("background-color:transparent") self.arrow_panel.raise_() painter = QPainter(self.arrow_panel) # drawing the arrows # setting the brush for arrows brush = QBrush(QColor(100, 100, 100, 200)) painter.setBrush(brush) # enable antialising painter.setRenderHint(QPainter.Antialiasing) # remove the border painter.setPen(QPen(QColor(0, 0, 0, 0))) for arrow in self.arrows: if arrow.width <= 0: continue arrow_head_width = arrow.width * 3 * self.cellSize arrow_head_length = arrow_head_width * 0.8 x_from, y_from = self._get_coordinate(arrow.sq_from) x_to, y_to = self._get_coordinate(arrow.sq_to) distance = math.sqrt((y_from - y_to)**2 + (x_from - x_to)**2) width = arrow.width * self.cellSize angle = math.atan2(y_to - y_from, x_to - x_from) - math.pi / 2 x0 = x_from + self.cellSize // 2 y0 = y_from + self.cellSize // 2 # draw an arrow. first create a polygon which will receive some points polygon = QPolygon() polygon.append(transform(width / 2, 0, angle, x0, y0)) polygon.append( transform(width / 2, distance - arrow_head_length, angle, x0, y0)) polygon.append( transform(arrow_head_width / 2, distance - arrow_head_length, angle, x0, y0)) polygon.append(transform(0, distance, angle, x0, y0)) polygon.append( transform(-arrow_head_width / 2, distance - arrow_head_length, angle, x0, y0)) polygon.append( transform(-width / 2, distance - arrow_head_length, angle, x0, y0)) polygon.append(transform(-width / 2, 0, angle, x0, y0)) painter.drawPolygon(polygon)
def draw_annotations(self, _index): blank = QImage(self.pixmap_img.width(), self.pixmap_img.height(), QImage.Format_ARGB32) self.pixmap_mask.clear() for key, item in self.display_mask.items(): self.scene.removeItem(item) self.display_mask.clear() # 利用 label 檔的輪廓資訊繪製遮罩 if len(self.FM.annotations) > 0: try: f_name = self.FM.image_list[_index] f_size = os_path.getsize(f'{self.FM.image_dir}/{f_name}') f_name = f'{f_name}{f_size}' a = self.FM.annotations[f_name] self.UI.statusbar.showMessage( f"{len(a['regions'])} annotation(s) loaded") # polygons = [r['shape_attributes'] for r in a['regions']] labelcolors = [ self.colors.RED, self.colors.GREEN, self.colors.BLUE, self.colors.YELLOW, self.colors.FUCHSIA, self.colors.AQUA ] nameref = { 'Red': 0, 'Green': 1, 'Blue': 2, 'Yellow': 3, 'Fuchsia': 4, 'Aqua': 5 } cidx = 0 for r in a['regions']: area = QPolygon() p = r['shape_attributes'] for i in range(len(p['all_points_x'])): area.append( QPoint(p['all_points_x'][i], p['all_points_y'][i])) try: paint_color = labelcolors[nameref[ r['region_attributes']['Color']]] except KeyError: paint_color = labelcolors[cidx] cidx = (cidx + 1) % 6 classname = r['region_attributes']['Name'] try: self.pixmap_mask[classname] except KeyError: self.pixmap_mask[classname] = QPixmap(blank) # Painting prep self.painter = QPainter(self.pixmap_mask[classname]) self.painter.setCompositionMode( QPainter.CompositionMode_Source) self.painter.setPen(QPen(paint_color)) self.painter.setBrush(QBrush(paint_color)) self.painter.drawPolygon(area) self.painter.end() except KeyError: self.UI.statusbar.showMessage('No annotation for this image') # 若沒有資料導入 創建預設類別圖層 if len(self.pixmap_mask) == 0: self.pixmap_mask[self.default_class] = QPixmap(blank) # 更新 Class 下拉式清單 self.UI.comboBox.clear() for key, val in self.pixmap_mask.items(): self.UI.comboBox.addItem(key)
def paintEvent(self, event): #width, height = self.width(), self.height() polygon = QPolygon() for i, data in enumerate(self.datas): x = i * self.pointDistance y = 160 - data #如果曲线运动到边界了,就需要隐藏。 if x + 130 > 370: continue #把点放到polygon,方便画折线 polygon.append(QPoint(x + 130, y)) painter = QPainter(self) pen = QPen() pen.setColor(Qt.darkCyan) painter.setPen(pen) # 设置QPainter.Antialiasing, True反走样,否则,你会看到咱们画出的线是锯齿状的…… painter.setRenderHint(QPainter.Antialiasing, True) #两点确定一条直线 画坐标轴 painter.drawLine(130, 160, 370, 160) #x轴 painter.drawLine(130, 160, 130, 70) #y轴 #画y轴的各种数值 for i in range(0, 100, 10): painter.drawText(105, 160 - i, str(i)) #x轴下标 painter.drawText(360, 175, 't') #测试点painter.drawText(360,70,'.') #画一个图的四面边框 pen.setColor(Qt.black) painter.setPen(pen) #四条边 painter.drawLine(100, 190, 100, 40) painter.drawLine(100, 190, 400, 190) painter.drawLine(100, 40, 400, 40) painter.drawLine(400, 190, 400, 40) painter.drawText(240, 210, "图1") # 画折线 pen.setColor(Qt.darkCyan) pen.setWidth(2) painter.setPen(pen) painter.setOpacity(1) painter.drawPolyline(polygon) # 传入点集 #第二个图 #四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(600, 40, 900, 40) painter.drawLine(600, 40, 600, 190) painter.drawLine(600, 190, 900, 190) painter.drawLine(900, 190, 900, 40) painter.drawText(740, 210, "图2") #x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(630, 160, 630, 70) painter.drawLine(630, 160, 870, 160) # x轴下标 painter.drawText(860, 175, 't') #y轴各种数值 for i in range(0, 100, 10): painter.drawText(605, 160 - i, str(i)) #三条折线的点集 polygon1 = QPolygon() for i, data in enumerate(self.datas1): x = i * self.pointDistance y = 160 - data #如果曲线运动到边界了,就需要隐藏。 if x + 630 > 870: continue #把点放到polygon,方便画折线 polygon1.append(QPoint(x + 630, y)) painter.drawPolyline(polygon1) polygon2 = QPolygon() for i, data in enumerate(self.datas2): x = i * self.pointDistance y = 160 - data #如果曲线运动到边界了,就需要隐藏。 if x + 630 > 870: continue #把点放到polygon,方便画折线 polygon2.append(QPoint(x + 630, y)) painter.drawPolyline(polygon2) polygon3 = QPolygon() for i, data in enumerate(self.datas3): x = i * self.pointDistance y = 160 - data #如果曲线运动到边界了,就需要隐藏。 if x + 630 > 870: continue #把点放到polygon,方便画折线 polygon3.append(QPoint(x + 630, y)) painter.drawPolyline(polygon3) #第三个图 #四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(100, 230, 400, 230) painter.drawLine(100, 230, 100, 380) painter.drawLine(100, 380, 400, 380) painter.drawLine(400, 380, 400, 230) painter.drawText(240, 400, "图3") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(130, 350, 130, 260) painter.drawLine(130, 350, 370, 350) # 第四个图 # 四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(600, 230, 900, 230) painter.drawLine(600, 230, 600, 380) painter.drawLine(600, 380, 900, 380) painter.drawLine(900, 380, 900, 230) painter.drawText(740, 400, "图4") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(630, 350, 630, 260) painter.drawLine(630, 350, 870, 350) # 第五个图 # 四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(100, 420, 400, 420) painter.drawLine(100, 420, 100, 570) painter.drawLine(100, 570, 400, 570) painter.drawLine(400, 570, 400, 420) painter.drawText(240, 590, "图5") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(130, 540, 130, 450) painter.drawLine(130, 540, 370, 540) # 第六个图 # 四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(600, 420, 900, 420) painter.drawLine(600, 420, 600, 570) painter.drawLine(600, 570, 900, 570) painter.drawLine(900, 570, 900, 420) painter.drawText(740, 590, "图6") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(630, 540, 630, 450) painter.drawLine(630, 540, 870, 540) # 第七个图 # 四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(100, 610, 400, 610) painter.drawLine(100, 610, 100, 760) painter.drawLine(100, 760, 400, 760) painter.drawLine(400, 760, 400, 610) painter.drawText(240, 780, "图7") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(130, 730, 130, 640) painter.drawLine(130, 730, 370, 730) # 第八个图 # 四条边 pen.setColor(Qt.black) painter.setPen(pen) painter.drawLine(600, 610, 900, 610) painter.drawLine(600, 610, 600, 760) painter.drawLine(600, 760, 900, 760) painter.drawLine(900, 760, 900, 610) painter.drawText(740, 780, "图8") # x,y坐标 pen.setColor(Qt.darkCyan) painter.setPen(pen) painter.drawLine(630, 730, 630, 640) painter.drawLine(630, 730, 870, 730)
class Feuille(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.paths = [] self.current = QPolygon() self.select = QPolygon() self.ctrl = False self.color = QColor("black") self.width = 1 self.buttonpressed = -1 self.selected_poly = [] 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 mousePressEvent(self, event): self.select = QPolygon() self.selected_poly = [] self.buttonpressed = event.button() if self.buttonpressed == Qt.RightButton: self.selected = QPolygon() self.select.append(event.pos()) else: self.current = QPolygon() self.current.append(event.pos()) self.update() def mouseReleaseEvent(self, event): if self.buttonpressed == Qt.RightButton: pass # appeller le menu #self.current.remove(self.current.size()-1) self.paths.append((self.current, self.color, self.width)) self.current = QPolygon() self.buttonpressed = -1 self.update() def mouseMoveEvent(self, event): if self.buttonpressed == Qt.RightButton: self.select.append(event.pos()) self.selected_poly = [] for index, path in enumerate(self.paths): if containspoly(self.select, path[0]): self.selected_poly.append((path[0], index)) else: self.current.append(event.pos()) self.update()
def drawStar(self): poly = QPolygon() for s in Star: poly.append(QPoint(s[0] - 3, s[1]) * common['Star']) return poly
def paintEvent(self, event): w, h = self.width(), self.height() painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing) blackpen = QPen(Qt.black, 1) nopen = QPen() nopen.setStyle(Qt.NoPen) greypen = QPen(Qt.gray, 1) painter.setPen(blackpen) nofill = QBrush() bfill = QBrush(QColor(0, 0, 0)) wfill = QBrush(QColor(255, 255, 255)) if self._histogram is not None: painter.fillRect(self.rect(), wfill) rect = QRect( 0, 0, max(0, self.minclip - self.min) * w / (self.max - self.min), h) painter.fillRect(rect, bfill) ww = max(0, self.max - self.maxclip) * w / (self.max - self.min) rect = QRect(w - ww, 0, ww, h) painter.fillRect(rect, bfill) fill = QBrush(QColor(*self.color)) poly = QPolygon() path = QPainterPath() pathstarted = False H = log(self._histogram / self._histogram.sum()) / log(2) H = maximum(H, -25) m = self.minclip / 255 M = self.maxclip / 255 for j, k in enumerate(H): x = j * w / (len(self._histogram) - 1) y = min(h * (k + 4) / (-25 + 4), h) poly.append(QPoint(x, y)) u = j / len(self._histogram) if (isinstance(m, ndarray) or isinstance(M, ndarray) or isinstance(self.gamma, ndarray)): continue if m <= u <= M: v = 1 - (1 - (u - m) / (M - m))**self.gamma if u < M or self.gamma >= 1: dvdu = self.gamma * \ (1 - (u - m)/(M - m))**(self.gamma - 1)/(M - m) else: dvdu = 1 if pathstarted: path.lineTo(v * w, y - log(dvdu) / log(2) / (-25 + 4)) else: path.moveTo(v * w, y - log(dvdu) / log(2) / (-25 + 4)) pathstarted = True poly.append(QPoint(w, h)) poly.append(QPoint(0, h)) painter.setPen(nopen) painter.setBrush(fill) painter.drawPolygon(poly) painter.setPen(greypen) painter.setBrush(nofill) painter.drawPath(path)
class SnapshotFreehandGrabber(QWidget): """ Class implementing a grabber widget for a freehand snapshot region. @signal grabbed(QPixmap) emitted after the region was grabbed """ grabbed = pyqtSignal(QPixmap) def __init__(self): """ Constructor """ super(SnapshotFreehandGrabber, self).__init__( None, Qt.X11BypassWindowManagerHint | Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint | Qt.Tool) self.__selection = QPolygon() self.__mouseDown = False self.__newSelection = False self.__handleSize = 10 self.__showHelp = True self.__grabbing = False self.__dragStartPoint = QPoint() self.__selectionBeforeDrag = QPolygon() self.__locale = QLocale() self.__helpTextRect = QRect() self.__helpText = self.tr( "Select a region using the mouse. To take the snapshot," " press the Enter key or double click. Press Esc to quit.") self.__pixmap = QPixmap() self.__pBefore = QPoint() self.setMouseTracking(True) QTimer.singleShot(200, self.__initialize) def __initialize(self): """ Private slot to initialize the rest of the widget. """ self.__desktop = QApplication.desktop() x = self.__desktop.x() y = self.__desktop.y() if qVersion() >= "5.0.0": self.__pixmap = QApplication.screens()[0].grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) else: self.__pixmap = QPixmap.grabWindow( self.__desktop.winId(), x, y, self.__desktop.width(), self.__desktop.height()) self.resize(self.__pixmap.size()) self.move(x, y) self.setCursor(Qt.CrossCursor) self.show() self.grabMouse() self.grabKeyboard() self.activateWindow() 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())) def mousePressEvent(self, evt): """ Protected method to handle mouse button presses. @param evt mouse press event (QMouseEvent) """ self.__pBefore = evt.pos() self.__showHelp = not self.__helpTextRect.contains(evt.pos()) if evt.button() == Qt.LeftButton: self.__mouseDown = True self.__dragStartPoint = evt.pos() self.__selectionBeforeDrag = QPolygon(self.__selection) if not self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.__newSelection = True self.__selection = QPolygon() else: self.setCursor(Qt.ClosedHandCursor) elif evt.button() == Qt.RightButton: self.__newSelection = False self.__selection = QPolygon() self.setCursor(Qt.CrossCursor) self.update() def mouseMoveEvent(self, evt): """ Protected method to handle mouse movements. @param evt mouse move event (QMouseEvent) """ shouldShowHelp = not self.__helpTextRect.contains(evt.pos()) if shouldShowHelp != self.__showHelp: self.__showHelp = shouldShowHelp self.update() if self.__mouseDown: if self.__newSelection: p = evt.pos() self.__selection.append(p) else: # moving the whole selection p = evt.pos() - self.__pBefore # Offset self.__pBefore = evt.pos() # save position for next iteration self.__selection.translate(p) self.update() else: if self.__selection.boundingRect().isEmpty(): return if self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.setCursor(Qt.OpenHandCursor) else: self.setCursor(Qt.CrossCursor) def mouseReleaseEvent(self, evt): """ Protected method to handle mouse button releases. @param evt mouse release event (QMouseEvent) """ self.__mouseDown = False self.__newSelection = False if self.__selection.containsPoint(evt.pos(), Qt.WindingFill): self.setCursor(Qt.OpenHandCursor) self.update() def mouseDoubleClickEvent(self, evt): """ Protected method to handle mouse double clicks. @param evt mouse double click event (QMouseEvent) """ self.__grabRegion() def keyPressEvent(self, evt): """ Protected method to handle key presses. @param evt key press event (QKeyEvent) """ if evt.key() == Qt.Key_Escape: self.grabbed.emit(QPixmap()) elif evt.key() in [Qt.Key_Enter, Qt.Key_Return]: self.__grabRegion() else: evt.ignore() 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, qp): if self.pixmap is None: self.status_update_signal.emit("no image loaded") return if self.showImage: qp.drawPixmap(0, 0, self.pixmap) if not self.showSpiral: return image = self.pixmap.toImage() # convert to image density = self.density dist = self.dist ampScale = self.ampScale start_time = time.time() radius = 1 # variable for the radius alpha = 0 # angle of current point aradius = 0 qp.setRenderHint(QPainter.Antialiasing) # Calculates the first point # currently just the center # TODO: create button to set center with mouse k = density / radius alpha += k radius += dist / (360 / k) x = aradius * cos(radians(alpha)) + image.width() / 2 y = -aradius * sin(radians(alpha)) + image.height() / 2 samples = 0 lines = 0 # when have we reached the far corner of the image? # TODO: this will have to change if not centered endRadius = sqrt( pow((image.width() / 2), 2) + pow((image.height() / 2), 2)) shapeOn = False points = QPolygon() # Have we reached the far corner of the image? while radius < endRadius: k = (density / 2) / radius alpha += k radius += dist / (360 / k) x = radius * cos(radians(alpha)) + image.width() / 2 y = -radius * sin(radians(alpha)) + image.height() / 2 # Are we within the the image? # If so check if the shape is open. If not, open it if ((x >= 0) and (x < image.width() - 1) and (y > 0) and (y < image.height())): samples += 1 # Get the color and brightness of the sampled pixel c = image.pixel(int(x), int(y)) b = qGray(c) b = remap(b, 0, 255, dist * ampScale, 0) # Move up according to sampled brightness aradius = radius + (b / dist) xa = aradius * cos(radians(alpha)) + image.width() / 2 ya = -aradius * sin(radians(alpha)) + image.height() / 2 # Move around depending on density k = (density / 2) / radius alpha += k radius += dist / (360 / k) # Move down according to sampled brightness bradius = radius - (b / dist) xb = bradius * cos(radians(alpha)) + image.width() / 2 yb = -bradius * sin(radians(alpha)) + image.height() / 2 # Add vertices to shape if (shapeOn == False): shapeOn = True points.append(QPoint(xa, ya)) points.append(QPoint(xb, yb)) else: # We are outside of the image so close the shape if it is open if shapeOn == True: qp.drawPolyline(points) lines += len(points) points.clear() shapeOn = False if shapeOn: qp.drawPolyline(points) lines += len(points) points.clear() process_time = time.time() - start_time self.status_update_signal.emit( "finished in %f secs, took %d samples, drew %d lines" % (process_time, samples, lines))
class MyLabel(QLabel): def __init__(self, parent=None): super(MyLabel, self).__init__(parent) self.clicked = pyqtSignal() self.x0 = self.y0 = self.x1 = self.y1 = 0 self.flag = False self.rect = QRect() self.pFlag = False self.chosen_points = QPolygon() self.path = QPainterPath() self.num = 0 def wheelEvent(self, event): if event.angleDelta().y() < 0: print('down') self.narrowImageSize() else: print('up') self.enlargeImageSize() def mouseMoveEvent(self, event): if self.flag: #记录坐标信息 self.x1 = event.pos().x() self.y1 = event.pos().y() self.path.lineTo(self.x1, self.y1) self.update() def mousePressEvent(self, event): self.flag = True self.pFlag = True self.x0 = event.pos().x() self.y0 = event.pos().y() self.x1 = self.x0 self.y1 = self.y0 self.clicked.emit() self.chosen_points.append(event.pos()) self.update() def mouseReleaseEvent(self, event): self.flag = False def cusDrawElli(self, qp): self.rect.setRect(self.x0, self.y0, self.x1 - self.x0, self.y1 - self.y0) qp.setPen(QPen(Qt.red, 2, Qt.SolidLine)) qp.drawEllipse(self.rect) def cusDrawRect(self, qp): self.rect.setRect(self.x0, self.y0, self.x1 - self.x0, self.y1 - self.y0) qp.setPen(QPen(Qt.red, 2, Qt.SolidLine)) qp.drawRect(self.rect) def cusDrawPoint(self, qp): qp.setPen(QPen(Qt.red, 5)) for pos in self.chosen_points: qp.drawPoint(pos) def cusDrawPolyline(self, qp): qp.setPen(QPen(Qt.red, 2)) qp.drawPolyline(self.chosen_points)
def paint_triangle(points, painter): triangle = QPolygon() for i in points: triangle.append(i) painter.drawPolygon(triangle)
def voronoi_function(list_players, list_opponents, field): points = [] for o in list_opponents: points.append(o.getLocation()) for p in list_players: points.append(p.getLocation()) if len(list_players + list_opponents) == 0: return if len(list_players + list_opponents) == 1: field = [ QPoint(field[0][0], field[0][1]), QPoint(field[1][0], field[1][1]), QPoint(field[2][0], field[2][1]), QPoint(field[3][0], field[3][1]) ] if list_players: list_players[0].polygon.setPolygon(QPolygonF(QPolygon(field))) return if list_opponents: list_opponents[0].polygon.setPolygon(QPolygonF(QPolygon(field))) return if len(points) == 2: startpoints = np.array(points) mitte = startpoints.mean(axis=0) #mitte = [(points[0][0]+points[1][0])/2, (points[0][1]+points[1][1])/2] v = startpoints[0] - startpoints[1] if (v[1] == 0): n = np.array([0, 1]) else: n = np.array([1, -v[0] / v[1]]) p1 = mitte + 5000 * n p2 = mitte + (-5000) * n pc = pyclipper.Pyclipper() pc.AddPath(field, pyclipper.PT_CLIP, True) pc.AddPath([p1, p2], pyclipper.PT_SUBJECT, False) line = pc.Execute2(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO) line = pyclipper.PolyTreeToPaths(line) firstPoly, secondPoly = splitPolygon(line[0], field) firstpol = QPolygon() secondpol = QPolygon() for p in firstPoly: firstpol.append(QPoint(p[0], p[1])) for p in secondPoly: secondpol.append(QPoint(p[0], p[1])) for p in list_opponents + list_players: if firstpol.containsPoint( QPoint(p.getLocation()[0], p.getLocation()[1]), Qt.OddEvenFill): p.polygon.setPolygon(QPolygonF(firstpol)) if secondpol.containsPoint( QPoint(p.getLocation()[0], p.getLocation()[1]), Qt.OddEvenFill): p.polygon.setPolygon(QPolygonF(secondpol)) return pointArray = np.asarray(points) vor = Voronoi(pointArray) vertices = vor.ridge_vertices eckpunkte = vor.vertices #print("Points: " + str(vor.points)) #print("Ridge_Vertices: " + str(vertices)) #print("Vertices: " + str(eckpunkte.tolist())) #print("Ridge_Points: " + str(vor.ridge_points)) #print("Regions: " + str(vor.regions)) #print("Point_regions" + str(vor.point_region)) pointidx = 0 val = [] for point in vor.points: ##iteration über punkte lines = [] poly = [] schnittpunkte = [] far_line = [] regions = vor.regions regionidx = vor.point_region.tolist()[pointidx] if min(regions[regionidx], default=-1) >= 0: ##behandlung falls polygon geschlossen for vidx in regions[regionidx]: poly.append([vor.vertices[vidx][0], vor.vertices[vidx][1]]) pc = pyclipper.Pyclipper() pc.AddPath(field, pyclipper.PT_CLIP, True) pc.AddPath(poly, pyclipper.PT_SUBJECT, True) poly = pc.Execute2(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO) poly = pyclipper.PolyTreeToPaths( poly) #Hinzufügen der Eckpunkte der closed Polygone poly = poly[0] else: ridgeidx = 0 field_copy = deepcopy(field) for punkte_paar in vor.ridge_points: ##iteration über die kanten die aus dem punkt gebildet werden punkte_paar = np.asarray(punkte_paar) if np.any(punkte_paar == pointidx): if min(vor.ridge_vertices[ridgeidx] ) >= 0: ##definierte linien des offenen polygons li = [ vor.vertices[vor.ridge_vertices[ridgeidx] [0]].tolist(), vor.vertices[vor.ridge_vertices[ridgeidx] [1]].tolist() ] lines.append([li[0], li[1]]) val.append(li) else: ##für offenes polygon center = pointArray.mean(axis=0) v = vor.vertices[vor.ridge_vertices[ridgeidx]][ 1] # finite end Voronoi vertex ausgangspunkt1 = pointArray[punkte_paar[1]] ausgangspunkt2 = pointArray[punkte_paar[0]] t = ausgangspunkt1 - ausgangspunkt2 # tangent x = np.linalg.norm(t) t = t / x n = np.array([-t[1], t[0]]) # normal midpoint = pointArray[punkte_paar].mean(axis=0) far_point = v + np.sign(np.dot(midpoint - center, n)) * n * 50000 p1 = [v[0], v[1]] p2 = [far_point[0], far_point[1]] far_line.append(p2) line = [p1, p2] lines.append(line) ridgeidx += 1 if lines: poly = ltp(lines) pc = pyclipper.Pyclipper() pc.AddPath(field, pyclipper.PT_CLIP, True) pc.AddPath(poly, pyclipper.PT_SUBJECT, True) poly = pc.Execute2(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO) poly = pyclipper.PolyTreeToPaths(poly) if poly: poly = poly[0] pc = pyclipper.Pyclipper() pc.AddPath(field, pyclipper.PT_CLIP, True) pc.AddPath(far_line, pyclipper.PT_SUBJECT, False) intersect_far = pc.Execute2(pyclipper.CT_INTERSECTION, pyclipper.PFT_NONZERO, pyclipper.PFT_NONZERO) intersect_far = pyclipper.PolyTreeToPaths(intersect_far) if intersect_far: intersect_far = intersect_far[0] for p in intersect_far: idx = poly.index(p) idx2 = idx + 1 if idx2 > len(poly) - 1: idx2 = -1 if poly[idx2] in intersect_far: iscp = poly[idx - 1] elif poly[idx - 1] in intersect_far: iscp = poly[idx2] for eck in field: if checkPointOnLine(p, [iscp, eck]): poly.pop(idx) poly.insert(idx, eck) add_player_poly(poly, pointidx, list_players, list_opponents) pointidx += 1 return val
class Winform(QWidget): def __init__(self, parent=None): super(Winform, self).__init__(parent) self.pix = QPixmap() # 实例化一个 QPixmap 对象 self.pen1 = QPen() # 定义笔格式对象 self.pen2 = QPen() self.pen1.setWidth(2) # 设置笔的宽度 self.pen2.setWidth(2) # 设置笔的宽度 self.pen1.setColor(Qt.red) self.pen2.setColor(Qt.blue) self.points_list = [] self.points_list1 = [] self.mouse_flag = 'H' self.msk_flag = True self.msk = QPixmap(self.size()) self.msk.fill(Qt.black) self.polygon = QPolygon() self.path = QPainterPath() self.resize(1024, 768) # 绘图函数 def paintEvent(self, event): painter0 = QPainter(self) painter1 = QPainter(self.pix) painter2 = QPainter(self.msk) if self.mouse_flag == 'H': painter1.setPen(self.pen1) else: painter1.setPen(self.pen2) for iii in range(len(self.points_list) - 1): painter1.drawLine(self.points_list[iii], self.points_list[iii + 1]) painter0.drawPixmap(self.rect(), self.pix) # 在画布上画出 if self.msk_flag: for iii in range(len(self.points_list) - 1): self.polygon.append(self.points_list[iii]) self.path.addPolygon(QPolygonF(self.polygon)) painter2.setBrush(Qt.white) painter2.fillPath(self.path, Qt.white) self.points_list = [] self.polygon = QPolygon() self.path = QPainterPath() # 鼠标按压事件 def mousePressEvent(self, event): # 鼠标左右键按下 if event.button() == Qt.LeftButton: self.pix = self.pix.scaled(self.size()) self.mouse_flag = 'H' self.msk_flag = False self.points_list.append(event.pos()) if event.button() == Qt.RightButton: self.mouse_flag = 'V' self.msk_flag = False self.points_list.append(event.pos()) # 鼠标移动事件 def mouseMoveEvent(self, event): # 鼠标左键按下的同时移动鼠标 if event.buttons() and (Qt.LeftButton or Qt.RightButton): self.points_list.append(event.pos()) self.msk_flag = False self.update() # 鼠标释放事件 def mouseReleaseEvent(self, event): # 鼠标左键释放 if event.button() == Qt.LeftButton or Qt.RightButton: try: self.points_list.append(self.points_list[0]) except: pass self.msk_flag = True self.update()
def paintEvent(self, event): painter = QPainter(self.viewport()) painter.fillRect(0, 0, self.viewport().width(), self.viewport().height(), QColor('#181818')) self.pos = self.verticalScrollBar().value() data_start = 0 data_end = 0 if len(self.data) > self.visible_lines(): data_start = self.pos data_end = self.pos + self.visible_lines() else: data_end = len(self.data) drawing_pos_y = 10 trace_depth = 0 fontMetrics = QFontMetrics(QFont(self.font)) text_options = QTextOption() text_options.setAlignment(Qt.AlignLeft) text_options.setWrapMode(QTextOption.WrapAtWordBoundaryOrAnywhere) for i, line in enumerate(self.data): if i == self.pos: break if line['event'] == 'leave': trace_depth -= 1 elif line['event'] == 'enter': trace_depth += 1 for i, line in enumerate(self.data[data_start:data_end]): if i > self.visible_lines(): break is_obj = False if isinstance(line['data'], str) and line['data'].startswith('{'): is_obj = True line['data'] = json.loads(line['data']) drawing_pos_x = 10 painter.setPen(QColor('#fff')) if line['event'] == 'leave': if trace_depth: trace_depth -= 1 drawing_pos_x += (trace_depth * 20) painter.setPen(QColor('crimson')) painter.setBrush(QColor('#222')) polygon = QPolygon() polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(self.viewport().width() - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 10, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x - 6, drawing_pos_y + (self._char_height * 0.5))) painter.drawPolygon(polygon) elif line['event'] == 'enter': trace_depth += 1 drawing_pos_x += (trace_depth * 20) painter.setPen(QColor('yellowgreen')) painter.setBrush(QColor('#222')) polygon = QPolygon() polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y - (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 5, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(int(floor(self.viewport().width())) - 21, drawing_pos_y + self._char_height + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y + self._char_height + (self._char_height * 0.5))) #polygon.append(QPoint(drawing_pos_x + 21, drawing_pos_y + (self._char_height * 0.5))) polygon.append(QPoint(drawing_pos_x + 6, drawing_pos_y - (self._char_height * 0.5))) painter.drawPolygon(polygon) drawing_pos_x += 20 rect = QRectF(drawing_pos_x, drawing_pos_y, self.viewport().width() - 25 - drawing_pos_x, self._char_height + 10) if line['event'] == 'enter': arg_str = '(' for a in range(len(line['data'])): arg_str += 'arg_{0}, '.format(a) if len(line['data']): arg_str = arg_str[:-2] arg_str += ')' painter.drawText(rect, line['class'] + arg_str, option=text_options) else: painter.drawText(rect, line['class'], option=text_options) drawing_pos_y += self._char_height + 15 if isinstance(line['data'], str): if line['data']: rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, self.viewport().width() - drawing_pos_x - 25, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, line['data']) rect = QRectF(drawing_pos_x, drawing_pos_y, rect.width(), rect.height()) painter.setPen(QColor('#888')) painter.drawText(rect, line['data'], option=text_options) drawing_pos_y += rect.height() + 5 else: width = int(floor(self.viewport().width() - drawing_pos_x - (5 * self._char_width) - 35)) max_chars = int(floor(width / self._char_width)) hold_x = drawing_pos_x + 5 width -= 20 painter.setPen(QColor('#888')) for data in line['data']: drawing_pos_x = hold_x if isinstance(line['data'][data], int): text = '{0:d}'.format(line['data'][data]) elif isinstance(line['data'][data], str): text = line['data'][data] elif isinstance(line['data'][data], list): text = str(line['data'][data]) else: text = str(line['data'][data]) if line['event'] == 'enter': arg = 'arg_{0}: '.format(data) painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, arg) drawing_pos_x += len(arg) * self._char_width elif line['event'] == 'leave': retval = data + ': ' painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, retval) drawing_pos_x += len(retval) * self._char_width if len(text) * self._char_width < width: painter.drawText(drawing_pos_x, drawing_pos_y + self._base_line, text) drawing_pos_y += self._char_height + 5 else: rect = fontMetrics.boundingRect(drawing_pos_x, drawing_pos_y, width, 0, Qt.AlignLeft | Qt.TextWordWrap | Qt.TextWrapAnywhere, text) rect = QRectF(rect) painter.drawText(rect, text, option=text_options) drawing_pos_y += rect.height() + 5 drawing_pos_y += self._char_height + 5
def map_render(self): max_x = self.map.cross_list.farthest_node.x max_y = self.map.cross_list.farthest_node.y self.painter.setPen(Qt.NoPen) for wy in self.map.ways: attrs = wy.attr try: x = attrs['amenity'] except KeyError: continue if x == 'parking': self.painter.setBrush(QColor(254, 194, 146)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['surface'] if not x: continue except KeyError: continue if x == 'paving_stones' or x == 'paved' or x == 'concrete:plates' or x == 'asphalt' or x == 'cobblestone': self.painter.setBrush(QColor(220, 220, 220)) elif x == 'earth' or x == 'sand': self.painter.setBrush((QColor(231, 179, 22))) elif x == 'grass': self.painter.setBrush(QColor(55, 232, 30)) else: print('{} is not showed in surface'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['leisure'] except KeyError: continue if x == 'swimming_pool': self.painter.setBrush(QColor(150, 182, 218)) elif x == 'park' or x == 'playground': self.painter.setBrush(QColor(150, 218, 179)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['natural'] except KeyError: continue if x == 'water': self.painter.setBrush(QColor(146, 160, 209)) elif x == 'grassland': self.painter.setBrush(QColor(55, 232, 30)) elif x == 'wood': self.painter.setBrush(QColor(75, 189, 72)) else: print('{} is not showed in natural'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['landuse'] if not x: continue except KeyError: continue if x == 'grass' or x == 'meadow': self.painter.setBrush(QColor(55, 232, 30)) elif x == 'forest': self.painter.setBrush(QColor(75, 189, 72)) elif x == 'commercial' or x == 'retail' or x == 'construction' or x == 'park' or x == 'residential': self.painter.setBrush((QColor(220, 220, 220))) else: print('{} is not showed in landuse'.format(x)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['building'] if not x: continue except KeyError: continue self.painter.setBrush(QColor(213, 191, 223)) polygon = QPolygon() length = len(wy.point) - 1 for i in range(length): new_pt = self.map.cross_list.get_node(wy.point[i]['ref']) polygon.append( QPoint(new_pt.x * self.size_x / max_x, self.size_y - new_pt.y * self.size_y / max_y)) self.painter.drawPolygon(polygon) for wy in self.map.ways: attrs = wy.attr try: x = attrs['waterway'] except KeyError: continue pen = QPen() pen.setColor(QColor(146, 160, 209)) pen.setWidth(8 * pow(self.zoom_ratio, 0.5 * self.zoom[1])) self.painter.setPen(pen) length = len(wy.point) - 1 for i in range(length): start = self.map.cross_list.get_node(wy.point[i]['ref']) end = self.map.cross_list.get_node(wy.point[i + 1]['ref']) self.painter.drawLine( start.x * self.size_x / max_x, self.size_y - start.y * self.size_y / max_y, end.x * self.size_x / max_x, self.size_y - end.y * self.size_y / max_y) for wy in self.map.ways: attrs = wy.attr try: x = attrs['highway'] if not x: continue except KeyError: continue pen = QPen() pen.setColor(QColor(202, 200, 153)) pen.setWidth(2 * pow(self.zoom_ratio, 0.5 * self.zoom[1])) self.painter.setPen(pen) length = len(wy.point) - 1 for i in range(length): start = self.map.cross_list.get_node(wy.point[i]['ref']) end = self.map.cross_list.get_node(wy.point[i + 1]['ref']) self.painter.drawLine( start.x * self.size_x / max_x, self.size_y - start.y * self.size_y / max_y, end.x * self.size_x / max_x, self.size_y - end.y * self.size_y / max_y)