def paintEvent(self, event): painter = QPainter() painter.begin(self) painter.setRenderHint(QPainter.Antialiasing) painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 127))) painter.setPen(QPen(Qt.NoPen)) for i in range(6): if (self.counter / 5) % 6 == i: painter.setBrush(QBrush(QColor(127 + (self.counter % 5) * 32, 127, 127))) else: painter.setBrush(QBrush(QColor(127, 127, 127))) painter.drawEllipse( self.width() / 2 + 30 * math.cos(2 * math.pi * i / 6.0) - 10, self.height() / 2 + 30 * math.sin(2 * math.pi * i / 6.0) - 10, 20, 20) painter.end()
def testGettersSetters(self): p = QgsProject() l = QgsLayout(p) s = QgsLayoutGridSettings(l) s.setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutPoints)) self.assertEqual(s.resolution().length(), 5.0) self.assertEqual(s.resolution().units(), QgsUnitTypes.LayoutPoints) s.setOffset(QgsLayoutPoint(6, 7, QgsUnitTypes.LayoutPixels)) self.assertEqual(s.offset().x(), 6.0) self.assertEqual(s.offset().y(), 7.0) self.assertEqual(s.offset().units(), QgsUnitTypes.LayoutPixels) s.setPen(QPen(QColor(255, 0, 255))) self.assertEqual(s.pen().color().name(), QColor(255, 0, 255).name()) s.setStyle(QgsLayoutGridSettings.StyleDots) self.assertEqual(s.style(), QgsLayoutGridSettings.StyleDots)
def __init__(self, startItem, startIndex, endItem, endIndex, parent=None, scene=None): super(ModelerArrowItem, self).__init__(parent) self.arrowHead = QPolygonF() self.endIndex = endIndex self.startIndex = startIndex self.startItem = startItem self.endItem = endItem self.endPoints = [] self.setFlag(QGraphicsItem.ItemIsSelectable, False) self.myColor = Qt.gray self.setPen( QPen(self.myColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.setZValue(0)
def __init__(self, startItem, startIndex, endItem, endIndex, parent=None, scene=None): super(ModelerArrowItem, self).__init__(parent) self.arrowHead = QPolygonF() self.endIndex = endIndex self.startIndex = startIndex self.startItem = startItem self.endItem = endItem self.endPoints = [] self.setFlag(QGraphicsItem.ItemIsSelectable, False) self.myColor = QApplication.palette().color(QPalette.WindowText) self.myColor.setAlpha(150) self.setPen( QPen(self.myColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.setZValue(0)
def changeColor(self, wdg, library, color1, name): #Action when clicking the tableview - color if library == "Qwt5": temp1 = wdg.plotWdg.itemList() for i in range(len(temp1)): if name == str(temp1[i].title().text()): curve = temp1[i] curve.setPen(QPen(color1, 3)) wdg.plotWdg.replot() # break # Don't break as there may be multiple curves with a common name (segments separated with None values) if library == "Matplotlib": temp1 = wdg.plotWdg.figure.get_axes()[0].get_lines() for i in range(len(temp1)): if name == str(temp1[i].get_gid()): # avoid this issue https://github.com/matplotlib/matplotlib/issues/1690/ temp1[i].set_color( '#%02x%02x%02x' % (color1.red(), color1.green(), color1.blue())) wdg.plotWdg.draw() break
def draw_background(self, painter, outline=True): old_pen = painter.pen() old_brush = painter.brush() p = QPen() b = QBrush() if self.__selected: p.setColor(QColor("#ffff99")) p.setWidth(2) b.setColor(QColor("#ffff66")) b.setStyle(Qt.SolidPattern) if self.__selected: painter.setBrush(b) painter.setPen(p) painter.drawRect(1, 0, self.boundingRect().width()-1, self.boundingRect().height()-1) if outline: painter.setBrush(QBrush()) painter.setPen(QPen()) painter.drawRect(0, 0, self.boundingRect().width(), self.boundingRect().height()-1) painter.setBrush(old_brush) painter.setPen(old_pen)
def genIcon(self): TECName = self.profile['TECName'] svgName = os.path.join(os.path.dirname(__file__), TECName + '_' + self.name + '.svg') pix = QSvgGenerator() pix.setFileName(svgName) pix.setSize(QSize(200, 100)) painter = QPainter() painter.begin(pix) painter.setPen(Qt.NoPen) # Paint the background before draw the legend line.(Essential!!) painter.fillRect(QRect(0, 0, 200, 100), Qt.white) painter.setPen(QPen(self.color, self.width * 3, self.lineStyle)) # Draw icon painter.drawLine(QLine(0, 50, 200, 50)) painter.end() pixmap = QPixmap(svgName) icon = QIcon(pixmap) self.icoName = svgName self.setIcon(icon)
def paint(self, painter, option, index): super().paint(painter, option, index) rect = QRect(option.rect) if not index.siblingAtColumn(0).data() == '-': painter.setPen(QPen(QColor(0, 0, 255), 2)) painter.drawLine(rect.topLeft(), rect.topRight()) painter.drawLine(rect.bottomLeft(), rect.bottomRight()) selected = option.state & QStyle.State_Selected rect = QRect(option.rect) if index.column() == 6: painter.setPen(QPen(QColor(255, 255, 255), 1)) painter.drawLine(rect.topRight(), rect.bottomRight()) elif index.column() == 2 or index.column() == 4 or index.column() == 7: painter.setPen(QPen(QColor(0, 0, 0), 1)) painter.drawLine(rect.topRight(), rect.bottomRight()) elif index.column() == 3 or index.column() == 5 or index.column() == 8: painter.setPen(QPen(QColor(0, 0, 0), 1)) painter.drawLine(rect.topLeft(), rect.bottomLeft()) painter.setPen(QPen(QColor(255, 255, 255), 1)) painter.drawLine(rect.topRight(), rect.bottomRight()) if selected: painter.setPen(QPen(QColor(255, 0, 0), 2)) painter.drawLine(rect.topLeft(), rect.topRight()) painter.drawLine(rect.bottomLeft(), rect.bottomRight())
def paint(self, painter, option, widget): if not painter: return painter.save() painter.setRenderHint(QPainter.Antialiasing, True) # do a bit of trigonometry to find out how to transform a rotated item such # that the center point is at the point feature x = 0.0 y = 0.0 if self.pixmap.width() > 0 and self.pixmap.height() > 0: half_item_diagonal = math.sqrt( self.pixmap.width() * self.pixmap.width() + self.pixmap.height() * self.pixmap.height()) / 2 diagonal_angle = math.acos( self.pixmap.width() / (half_item_diagonal * 2)) * 180 / math.pi x = half_item_diagonal * math.cos( (self.rotation - diagonal_angle) * math.pi / 180) y = half_item_diagonal * math.sin( (self.rotation - diagonal_angle) * math.pi / 180) painter.rotate(self.rotation) painter.translate(x - self.pixmap.width() / 2.0, -y - self.pixmap.height() / 2.0) painter.drawPixmap(0, 0, self.pixmap) # draw arrow, using a red line over a thicker white line so that the arrow is visible # against a range of backgrounds pen = QPen() pen.setWidth(GuiUtils.scale_icon_size(4)) pen.setColor(QColor(Qt.white)) painter.setPen(pen) painter.drawPath(self.arrow_path) pen.setWidth(GuiUtils.scale_icon_size(1)) pen.setColor(QColor(Qt.red)) painter.setPen(pen) painter.drawPath(self.arrow_path) painter.restore() # draw numeric value beside the symbol painter.save() painter.setRenderHint(QPainter.Antialiasing, True) buffer_pen = QPen() buffer_pen.setColor(Qt.white) buffer_pen.setWidthF(GuiUtils.scale_icon_size(4)) fm = QFontMetricsF(self.marker_font) label = QPainterPath() label.addText(self.pixmap.width(), self.pixmap.height() / 2.0 + fm.height() / 2.0, self.marker_font, str(round(self.rotation, 1))) painter.setPen(buffer_pen) painter.setBrush(Qt.NoBrush) painter.drawPath(label) painter.setPen(Qt.NoPen) painter.setBrush(QBrush(Qt.black)) painter.drawPath(label) painter.restore()
def drawForeground(self, painter, rect): #print "BoreHoleScene.drawForeground" if self.__redraw: with self.__project.connect() as con: cur = con.cursor() self.__redraw = False self.clear() fm = painter.fontMetrics() if self.__id is None: QGraphicsScene.drawForeground(self, painter, rect) return cur.execute( "SELECT geom FROM albion.hole WHERE id='{}'".format( self.__id)) res = cur.fetchone() if not res: QGraphicsScene.drawForeground(self, painter, rect) return hole = wkb.loads(bytes.fromhex(res[0])) line = [p[2] for p in hole.coords] tick_width = 20 spacing = 5 tick_text_offset = -10 tabs = [50, 75, 150, 250, 350, 400, 500] zmin, zmax = min(line), max(line) zpmin, zpmax = 0, ((zmin - zmax) - 5) / self.m_per_pixel text = self.addText(self.__id) text.setPos(tabs[1], -5 * fm.height()) label = 'Depth [m]' text = self.addText(label) text.setRotation(-90) text.setPos(0, 0) text = self.addText('Formation') text.setPos(tabs[1], -3 * fm.height()) text = self.addText('Radiometry') text.setPos(tabs[2], -3 * fm.height()) text = self.addText('Resistivity') text.setPos(tabs[3], -3 * fm.height()) text = self.addText('Mineralization') text.setPos(tabs[4], -3 * fm.height()) top = zpmin - 3 * fm.height() pen = QPen() pen.setWidth(3) for tab in [tabs[1], tabs[2], tabs[3], tabs[4], tabs[6]]: self.addLine(tab, top, tab, zpmax, pen) self.addLine(tabs[1], zpmin, tabs[-1], zpmin, pen) self.addLine(tabs[1], zpmax, tabs[-1], zpmax, pen) self.addLine(tabs[1], top, tabs[-1], top, pen) # depth ticks for z in range(0, int(-(zmax - zmin) - 5), -10): text = "% 4.0f" % (max(line) + z) z /= self.m_per_pixel width = fm.width(text) text = self.addText(text) text.setPos(tabs[0] - width - spacing, tick_text_offset + int(z)) self.addLine(tabs[0], z, tabs[1], z) self.addLine(tabs[2], z, tabs[4], z) #res = cur.execute("SELECT AsText(GEOMETRY), code FROM lithologies WHERE forage={}".format(self.__id)).fetchall() ## litho image #for geom, code in res: # line = [(float(pt.split()[2])-z_tube+h_tube_sol) # for pt in geom.replace('LINESTRING Z(','').replace(')','').split(',')] # z_start = line[0]/self.m_per_pixel # z_end = line[-1]/self.m_per_pixel # brush = QBrush() # brush.setTextureImage(self.texture(code)) # self.addRect(tabs[1], z_start, tabs[2]-tabs[1], z_end-z_start, brush=brush) ## bar diagram grid #for i in range(1, 10): # pen.setWidth(1 if i != 5 else 2) # x = tabs[3]+(tabs[4]-tabs[3])*float(i)/10 # self.addLine(x, zmin, x, zmax, pen) # formation color cur.execute( "SELECT geom, code FROM albion.formation WHERE hole_id='{}'" .format(self.__id)) for geom, code in cur.fetchall(): line = [ p[2] for p in wkb.loads(bytes.fromhex(geom)).coords ] z_start = (line[0] - zmax) / self.m_per_pixel z_end = (line[-1] - zmax) / self.m_per_pixel brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(self.formation_color(code)) self.addRect(tabs[1], z_start, tabs[2] - tabs[1], z_end - z_start, brush=brush) #width = fm.width(code); #text = self.addText(code) #text.setPos(tabs[2]+spacing, tick_text_offset+int(.5*(z_start+z_end))) self.addLine(tabs[2], z_start, tabs[2], z_start) self.addLine(tabs[2], z_end, tabs[2], z_end) # radiometry diagram cur.execute( "SELECT max(gamma) FROM albion.radiometry WHERE hole_id='{}'" .format(self.__id)) gamma_max = cur.fetchone()[0] cur.execute( "SELECT geom, gamma FROM albion.radiometry WHERE hole_id='{}' AND gamma>=0" .format(self.__id)) for geom, gamma in cur.fetchall(): line = [ p[2] for p in wkb.loads(bytes.fromhex(geom)).coords ] z_start = (line[0] - zmax) / self.m_per_pixel z_end = (line[-1] - zmax) / self.m_per_pixel brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(QColor(55, 51, 149)) self.addRect(tabs[2], z_start, (tabs[3] - tabs[2]) * gamma / gamma_max, z_end - z_start, pen=QPen(Qt.NoPen), brush=brush) # resistivity diagram cur.execute( "SELECT max(rho) FROM albion.resistivity WHERE hole_id='{}'" .format(self.__id)) rho_max = cur.fetchone()[0] cur.execute( "SELECT geom, rho FROM albion.resistivity WHERE hole_id='{}' AND rho>=0" .format(self.__id)) for geom, rho in cur.fetchall(): line = [ p[2] for p in wkb.loads(bytes.fromhex(geom)).coords ] z_start = (line[0] - zmax) / self.m_per_pixel z_end = (line[-1] - zmax) / self.m_per_pixel brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(QColor(155, 51, 49)) self.addRect(tabs[3], z_start, (tabs[4] - tabs[3]) * rho / rho_max, z_end - z_start, pen=QPen(Qt.NoPen), brush=brush) # mineralization cur.execute( "SELECT geom, oc, accu, grade FROM albion.mineralization WHERE hole_id='{}'" .format(self.__id)) for geom, oc, accu, grade in cur.fetchall(): line = [ p[2] for p in wkb.loads(bytes.fromhex(geom)).coords ] z_start = (line[0] - zmax) / self.m_per_pixel z_end = (line[-1] - zmax) / self.m_per_pixel brush = QBrush() brush.setStyle(Qt.SolidPattern) brush.setColor(QColor(250, 250, 50)) self.addRect(tabs[4], z_start, tabs[5] - tabs[4], z_end - z_start, brush=brush) txt = "oc=" + str(oc) + "\naccu=" + str( accu) + "\ngrade=" + str(grade) width = fm.width(txt) text = self.addText(txt) text.setPos( tabs[5] + spacing, -int(1.5 * fm.height()) + int(.5 * (z_start + z_end))) self.addLine(tabs[4], z_start, tabs[6], z_start) self.addLine(tabs[4], z_end, tabs[6], z_end) self.setSceneRect(self.itemsBoundingRect()) QGraphicsScene.drawForeground(self, painter, rect)
def __init__(self, parent=None): ''' Constructor ''' super().__init__(parent) self.surface = VideoWidgetSurface(self) self.setAttribute(Qt.WA_OpaquePaintEvent) self.Tracking_Video_RubberBand = QRubberBand(QRubberBand.Rectangle, self) self.Censure_RubberBand = QRubberBand(QRubberBand.Rectangle, self) color_blue = QColor(Qt.blue) color_black = QColor(Qt.black) color_amber = QColor(252, 215, 108) pal_blue = QPalette() pal_blue.setBrush(QPalette.Highlight, QBrush(color_blue)) self.Tracking_Video_RubberBand.setPalette(pal_blue) pal_black = QPalette() pal_black.setBrush(QPalette.Highlight, QBrush(color_black)) self.Censure_RubberBand.setPalette(pal_black) self._interaction = InteractionState() self._filterSatate = FilterState() self._isinit = False self._MGRS = False self.gt = None self.drawCesure = [] self.poly_coordinates, self.drawPtPos, self.drawLines, self.drawMeasureDistance, self.drawMeasureArea, self.drawPolygon = [], [], [], [], [], [] # Draw Polygon Canvas Rubberband self.poly_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), True) # Polygon type # set rubber band style self.poly_Canvas_RubberBand.setColor(color_amber) self.poly_Canvas_RubberBand.setWidth(3) # Tracking Canvas Rubberband self.Track_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), QgsWkbTypes.LineGeometry) # set rubber band style self.Track_Canvas_RubberBand.setColor(color_blue) self.Track_Canvas_RubberBand.setWidth(5) # Cursor Canvas Rubberband self.Cursor_Canvas_RubberBand = QgsRubberBand( iface.mapCanvas(), QgsWkbTypes.PointGeometry) self.Cursor_Canvas_RubberBand.setWidth(4) self.Cursor_Canvas_RubberBand.setColor(QColor(255, 100, 100, 250)) self.Cursor_Canvas_RubberBand.setIcon(QgsRubberBand.ICON_FULL_DIAMOND) self.parent = parent.parent() palette = self.palette() palette.setColor(QPalette.Background, Qt.transparent) self.setPalette(palette) self.origin, self.dragPos = QPoint(), QPoint() self.tapTimer = QBasicTimer() self.brush = QBrush(color_black) self.blue_Pen = QPen(color_blue, 3)
def drawLine(self, painter, commit, parent): commitRow = self.graph.commitRows[commit.commitid] commitCol = self.graph.commitColumns[commit.commitid] parentRow = self.graph.commitRows[parent.commitid] parentCol = self.graph.commitColumns[parent.commitid] commitX = self.RADIUS * 3 + commitCol * self.COLUMN_SEPARATION parentX = self.RADIUS * 3 + parentCol * self.COLUMN_SEPARATION commitY = commitRow * self.COMMIT_GRAPH_HEIGHT parentY = parentRow * self.COMMIT_GRAPH_HEIGHT color = self._columnColor(parentCol) if parent is not None and self.graph.isFauxLink(parent.commitid, commit.commitid)\ and len(parent.childrenIds)>1: # draw a faux line path = QPainterPath() path.moveTo(parentX, parentY) path.lineTo(commitX , commitY) color = QColor(255,160,255) pen = QPen() pen.setWidth(2) pen.setBrush(color) pen.setStyle(Qt.DashLine) painter.setPen(pen) painter.drawPath(path) # draw arrow # draw arrow ARROW_POINT_SIZE = 9 painter.setPen(color) painter.setBrush(color) line = QLineF(commitX , commitY, parentX, parentY) angle = math.acos(line.dx() / line.length()) if line.dy() >= 0: angle = 2.0 * math.pi - angle sourcePoint = QPointF(commitX,commitY) sourceArrowP1 = sourcePoint + QPointF(math.sin(angle + math.pi / 3) * ARROW_POINT_SIZE, math.cos(angle + math.pi / 3) * ARROW_POINT_SIZE) sourceArrowP2 = sourcePoint + QPointF(math.sin(angle + math.pi - math.pi / 3) * ARROW_POINT_SIZE, math.cos(angle + math.pi - math.pi / 3) * ARROW_POINT_SIZE) arrow = QPolygonF([line.p1(), sourceArrowP1, sourceArrowP2]) painter.drawPolygon(arrow) return path = QPainterPath() painter.setBrush(color) painter.setPen(color) if parentCol != commitCol: if parent.isFork() and commit.getParents()[0].commitid == parent.commitid: path.moveTo(commitX, commitY) path.lineTo(commitX, parentY) if parentX<commitX: path.lineTo(parentX + self.RADIUS + 1, parentY) else: path.lineTo(parentX - self.RADIUS, parentY) color = self._columnColor(commitCol) else: path2 = QPainterPath() path2.moveTo(commitX + self.RADIUS + 1, commitY) path2.lineTo(commitX + self.RADIUS + self.COLUMN_SEPARATION / 2, commitY + self.COLUMN_SEPARATION / 3) path2.lineTo(commitX + self.RADIUS + self.COLUMN_SEPARATION / 2, commitY - self.COLUMN_SEPARATION / 3) path2.lineTo(commitX + + self.RADIUS + 1, commitY) painter.setBrush(color) painter.setPen(color) painter.drawPath(path2) path.moveTo(commitX + self.RADIUS + self.COLUMN_SEPARATION / 2, commitY) path.lineTo(parentX, commitY) path.lineTo(parentX, parentY) if parent.isFork(): if commitCol in self.columnColor.keys(): del self.columnColor[commitCol] else: path.moveTo(commitX, commitY) path.lineTo(parentX, parentY) pen = QPen(color, self.PEN_WIDTH, Qt.SolidLine, Qt.FlatCap, Qt.RoundJoin) painter.strokePath(path, pen) if not commit.commitid in self.linked: y = commitRow * self.COLUMN_SEPARATION x = self.RADIUS * 3 + commitCol * self.COLUMN_SEPARATION painter.setPen(color) painter.setBrush(color) painter.drawEllipse(QPoint(x, y), self.RADIUS, self.RADIUS) self.linked.append(commit.commitid)
def drawHistogram(self): #if self.inputlayer is None: # return self.showInfo("Drawing histogram...") viewprect = QRectF(self.histoGraphicsView.viewport().rect()) self.histoGraphicsView.setSceneRect(viewprect) self.setupScene.clear() self.setupScene.update() histbottom = self.histoGraphicsView.sceneRect().bottom() histtop = self.histoGraphicsView.sceneRect().top() left = self.histoGraphicsView.sceneRect().left() + self.histopadding right = self.histoGraphicsView.sceneRect().right() - self.histopadding histheight = histbottom - histtop histwidth = right - left step = 1.0 * histwidth / self.histobins maxlength = histheight padding = 1 ll = QPoint(self.histopadding - 1, histheight - padding) start = QPointF(self.histoGraphicsView.mapToScene(ll)) # Check if there is only one value #myrange = (self.minValueSpinBox.value(),self.maxValueSpinBox.value()) if self.histogramAvailable: maxvalue = 0.0 for i in range(len(self.histo[0])): if self.histo[0][i] > maxvalue: maxvalue = self.histo[0][i] if maxvalue == 0: return self.maxBinNumber.setText(str(maxvalue)) # Create the histogram: #self.showInfo("maxvalue: " + str(maxvalue)) #self.showInfo("maxlength: " + str(maxlength)) #self.showInfo("step: " + str(step)) for i in range(self.histobins): binnumber = self.histo[0][i] if binnumber == 0: continue height = (1.0 * self.histo[0][i] / maxvalue * (maxlength - padding)) rectangle = QGraphicsRectItem(start.x() + step * i, start.y(), step, -height) rectangle.setPen(QPen(QColor(102, 102, 102))) rectangle.setBrush(QBrush(QColor(240, 240, 240))) self.setupScene.addItem(rectangle) #self.showInfo(str(i) + ": " + str(height)) #if self.levelsListView.model().rowCount() > 0: # Add lines for the levels minvalue = float(self.histMinValue.text()) maxvalue = float(self.histMaxValue.text()) datarange = maxvalue - minvalue if datarange == 0: return i = 0 while self.levelsListView.model().item(i): #self.showInfo("Element: " + # str(self.levelsListView.model().item(i).text())) #continue value = float(self.levelsListView.model().item(i).text()) xvalue = start.x() + histwidth * (value - minvalue) / datarange line = QGraphicsLineItem(xvalue, 0, xvalue, histheight) if i == 0 or i == (self.levelsListView.model().rowCount() - 1): line.setPen(QPen(QColor(204, 0, 0))) else: line.setPen(QPen(QColor(0, 204, 0))) self.setupScene.addItem(line) i = i + 1
def setValues(options=None): ''' Function to set Drawing Values ''' s = QSettings() ####### Magnifier Glass ####### shape_type = s.value(DrawToolBar.NameSpace + "/Options/magnifier/shape") if shape_type is not None: global TYPE_MAGNIFIER TYPE_MAGNIFIER = shape_type if options is not None: if TYPE_MAGNIFIER == 0: # Square options.rB_Square_m.setChecked(True) else: # Circle options.rB_Circle_m.setChecked(True) mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor") if mFactor is not None: global MAX_FACTOR MAX_FACTOR = int(mFactor) if options is not None: options.sb_factor.setValue(MAX_FACTOR) mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size") if mSize is not None: global MAX_MAGNIFIER MAX_MAGNIFIER = int(mSize) if options is not None: options.sl_Size.setValue(MAX_MAGNIFIER) ####### Drawings ####### poly_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/width") if poly_w is not None: global PolyWidth PolyWidth = int(poly_w) if options is not None: options.poly_width.setValue(PolyWidth) poly_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/pen") if poly_p is not None: global PolyPen PolyPen = QPen(QColor(poly_p)) PolyPen.setCapStyle(Qt.RoundCap) PolyPen.setWidth(PolyWidth) if options is not None: options.poly_pen.setColor(QColor(poly_p)) poly_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/brush") if poly_b is not None: global PolyBrush PolyBrush = QBrush(QColor(poly_b)) if options is not None: options.poly_brush.setColor(QColor(poly_b)) point_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/width") if point_w is not None: global PointWidth PointWidth = int(point_w) if options is not None: options.point_width.setValue(PointWidth) point_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/pen") if point_p is not None: global PointPen PointPen = QPen(QColor(point_p)) PointPen.setCapStyle(Qt.RoundCap) PointPen.setWidth(PointWidth) if options is not None: options.point_pen.setColor(QColor(point_p)) line_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/width") if line_w is not None: global LineWidth LineWidth = int(line_w) if options is not None: options.lines_width.setValue(LineWidth) line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen") if line_p is not None: global LinePen LinePen = QPen(QColor(line_p)) LinePen.setCapStyle(Qt.RoundCap) LinePen.setWidth(LineWidth) if options is not None: options.lines_pen.setColor(QColor(line_p)) measure_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/width") if measure_w is not None: global MeasureWidth MeasureWidth = int(measure_w) if options is not None: options.measures_width.setValue(MeasureWidth) measure_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/pen") if measure_p is not None: global MeasurePen MeasurePen = QPen(QColor(measure_p)) MeasurePen.setCapStyle(Qt.RoundCap) MeasurePen.setWidth(MeasureWidth) if options is not None: options.measures_pen.setColor(QColor(measure_p)) measure_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/brush") if measure_b is not None: global MeasureBrush MeasureBrush = QBrush(QColor(measure_b)) if options is not None: options.measures_brush.setColor(QColor(measure_b)) return
getNameSpace) from QGIS_FMV.video.QgsVideoUtils import VideoUtils as vut try: from pydevd import * except ImportError: None RulerTotalMeasure = 0.0 MAX_MAGNIFIER = 250 MAX_FACTOR = 2 TYPE_MAGNIFIER = 1 # Polygon Draw PolyWidth = 3 PolyPen = QPen(QColor(252, 215, 108), PolyWidth) PolyBrush = QBrush(QColor(252, 215, 108, 100)) # Point Draw PointWidth = 10 PointPen = QPen(QColor(220, 20, 60), PointWidth, cap=Qt.RoundCap) # Line Draw LineWidth = 3 LinePen = QPen(QColor(252, 215, 108), LineWidth) # Measure Draw MeasureWidth = 3 MeasurePen = QPen(QColor(185, 224, 175), MeasureWidth, cap=Qt.RoundCap,
def changePlotWidget(self, library, frame_for_plot): if library == "Qwt5" and has_qwt: plotWdg = QwtPlot(frame_for_plot) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( plotWdg.sizePolicy().hasHeightForWidth()) plotWdg.setSizePolicy(sizePolicy) plotWdg.setMinimumSize(QSize(0, 0)) plotWdg.setAutoFillBackground(False) #Decoration plotWdg.setCanvasBackground(Qt.white) plotWdg.plotLayout().setAlignCanvasToScales(True) zoomer = QwtPlotZoomer(QwtPlot.xBottom, QwtPlot.yLeft, QwtPicker.DragSelection, QwtPicker.AlwaysOff, plotWdg.canvas()) zoomer.setRubberBandPen(QPen(Qt.blue)) if platform.system() != "Windows": # disable picker in Windows due to crashes picker = QwtPlotPicker(QwtPlot.xBottom, QwtPlot.yLeft, QwtPicker.NoSelection, QwtPlotPicker.CrossRubberBand, QwtPicker.AlwaysOn, plotWdg.canvas()) picker.setTrackerPen(QPen(Qt.green)) #self.dockwidget.qwtPlot.insertLegend(QwtLegend(), QwtPlot.BottomLegend); grid = Qwt.QwtPlotGrid() grid.setPen(QPen(QColor('grey'), 0, Qt.DotLine)) grid.attach(plotWdg) return plotWdg elif library == "Matplotlib" and has_mpl: from matplotlib.figure import Figure from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg fig = Figure((1.0, 1.0), linewidth=0.0, subplotpars=matplotlib.figure.SubplotParams(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)) font = {'family': 'arial', 'weight': 'normal', 'size': 12} matplotlib.rc('font', **font) rect = fig.patch rect.set_facecolor((0.9, 0.9, 0.9)) self.subplot = fig.add_axes((0.07, 0.15, 0.92, 0.82)) self.subplot.set_xbound(0, 1000) self.subplot.set_ybound(0, 1000) self.manageMatplotlibAxe(self.subplot) canvas = FigureCanvasQTAgg(fig) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) canvas.setSizePolicy(sizePolicy) return canvas
def attachCurves(self, wdg, profiles, model1, library): if library == "Qwt5" and has_qwt: wdg.plotWdg.clear() for i in range(0, model1.rowCount()): profileName = model1.item(i, 4).data(Qt.EditRole) profileId = model1.item(i, 5).data(Qt.EditRole) isVisible = model1.item(i, 0).data(Qt.CheckStateRole) xx = profiles[i]["l"] yy = profiles[i][profileName] if library == "Qwt5" and has_qwt: # As QwtPlotCurve doesn't support nodata, split the data into single lines # with breaks wherever data is None. # Prepare two lists of coordinates (xx and yy). Make x=None whenever y==None. for j in range(len(yy)): if yy[j] is None or isnan(yy[j]): xx[j] = None yy[j] = None # Split xx and yy into single lines at None values xx = [ list(g) for k, g in itertools.groupby(xx, lambda x: x is None) if not k ] yy = [ list(g) for k, g in itertools.groupby(yy, lambda x: x is None) if not k ] # Create & attach one QwtPlotCurve per one single line for j in range(len(xx)): curve = QwtPlotCurve(profileId) curve.setData(xx[j], yy[j]) curve.setPen( QPen(model1.item(i, 1).data(Qt.BackgroundRole), 3)) curve.attach(wdg.plotWdg) curve.setVisible(isVisible) elif library == "Matplotlib" and has_mpl: lines = wdg.plotWdg.figure.get_axes()[0].get_lines() lineIds = [line.get_gid() for line in lines] if profileId in lineIds: # Update existing line line = lines[lineIds.index(profileId)] line.set_data([xx, yy]) else: # Create new line line = wdg.plotWdg.figure.get_axes()[0].plot( xx, yy, gid=profileId)[0] line.set_visible(isVisible) # X-axis have to be set before wdg is redrawn in changeColor, otherwise and # exception is sometimes thrown when time-based axis is used. minimumValueX = min(z for z in profiles[i]["l"]) maximumValueX = max(z for z in profiles[i]["l"]) wdg.plotWdg.figure.get_axes()[0].set_xlim( [minimumValueX, maximumValueX]) self.changeColor(wdg, "Matplotlib", model1.item(i, 1).data(Qt.BackgroundRole), profileId)
def setStyle(self): self.Style = QPen(QBrush(self.color), self.width, style=self.lineStyle) self.profile.update({'style': self.Style})
def paint(self, painter, option, index): if index.column() != 0: QStyledItemDelegate.paint(self, painter, option, index) return model: Any[PlanetSearchResultsModel | QAbstractItemModel] = \ index.model() node: PlanetNode = model.get_node(index) # TODO: Style these, too? # if node.node_type() in [NodeT.LOADING, NodeT.LOAD_MORE]: # QStyledItemDelegate.paint(self, painter, option, index) # return option_vi = QStyleOptionViewItem(option) self.initStyleOption(option_vi, index) # noinspection PyUnusedLocal style = QApplication.style() \ if option_vi.widget is None else option_vi.widget.style() # style = self.parent().style() opt_rect = option_vi.rect doc = QTextDocument() doc.setHtml(option_vi.text) #print(option_vi.text) option_vi.text = '' style.drawControl(QStyle.CE_ItemViewItem, option_vi, painter) ctx = QAbstractTextDocumentLayout.PaintContext() # Highlighting text if item is selected # if option_vi.state & QStyle.State_Selected: # ctx.palette.setColor( # QPalette.Text, # option_vi.palette.color( # QPalette.Active, QPalette.HighlightedText)) text_rect = style.subElementRect(QStyle.SE_ItemViewItemText, option_vi) painter.save() painter.translate(text_rect.topLeft()) painter.setClipRect(text_rect.translated(-text_rect.topLeft())) doc.documentLayout().draw(painter, ctx) painter.restore() if option.state & QStyle.State_MouseOver: if node.has_footprint() or node.has_group_footprint(): painter.save() painter.setPen( QPen(QBrush(QColor.fromRgb(0, 157, 165, 245)), 1.5)) painter.setBrush(Qt.NoBrush) painter.drawRect(opt_rect.marginsRemoved(QMargins(1, 1, 1, 1))) painter.restore() if node.has_footprint() or node.has_group_footprint(): # noinspection PyUnresolvedReferences self.previewFootprint.emit(node) else: # noinspection PyUnresolvedReferences self.clearFootprint.emit() if not node.can_be_downloaded(): # Note: Needs to come last, so it covers checkbox control # TODO: Figure out way of having checkbox not drawn, but still # set Node's unchecked state # opt_btn = QStyleOptionButton() # opt_btn.operator = option ci_rect: QRect = style.subElementRect( QStyle.SE_ViewItemCheckIndicator, option_vi) # opt_btn.rect = ci_rect # but_opt = QStyleOptionButton(option) # opt_btn.state = QStyle.State_Off # style.drawControl(QStyle.CE_CheckBox, opt_btn, painter) painter.save() painter.setPen(Qt.NoPen) painter.setBrush(QBrush(QColor.fromRgb(250, 250, 250, 255))) painter.drawRoundedRect(ci_rect, ci_rect.height() / 6, ci_rect.height() / 6) LOCK_ICON.paint(painter, ci_rect, Qt.AlignCenter, QIcon.Normal) painter.restore()
def paint(self, painter, option, widget): self.draw_background(painter) painter.setClipRect(0, 0, self.__width - 1, self.__height - 1) context = qgis_render_context(painter, self.__width, self.__height) context.setExtent(QgsRectangle(0, 0, self.__width, self.__height)) fields = self.__layer.fields() has_formation_code = "formation_code_column" in self.__column_mapping \ and self.__column_mapping["formation_code_column"] is not None # need to set fields in context so they can be evaluated in expression. # if not QgsExpressionNodeColumnRef prepareNode methods will fail when # checking that variable EXPR_FIELDS is defined (this variable is set # by setFields method context.expressionContext().setFields(fields) self.__renderer.startRender(context, fields) try: for i, f in enumerate(self.__data): depth_from = float(self.__field_value(f, "depth_from_column")) depth_to = float(self.__field_value(f, "depth_to_column")) if abs((self.__max_z - self.__min_z) * self.__height) > 0: y1 = (depth_from - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height y2 = (depth_to - self.__min_z) / ( self.__max_z - self.__min_z) * self.__height painter.setPen(QPen()) painter.setBrush(QBrush()) if i == 0: painter.drawLine(0, y1, self.__width - 1, y1) painter.drawLine(0, y2, self.__width - 1, y2) if has_formation_code: # legend text formation_code = str( self.__field_value(f, "formation_code_column")) if formation_code: fm = painter.fontMetrics() w = fm.width(formation_code) x = (self.__width / 2 - w) / 2 + self.__width / 2 y = (y1 + y2) / 2 if y - fm.ascent() > y1 and y + fm.descent() < y2: painter.drawText(x, y, formation_code) geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width / 2, y1 - y2))) else: geom = QgsGeometry.fromQPolygonF( QPolygonF( QRectF(0, self.__height - y1, self.__width, y1 - y2))) feature = QgsFeature(fields, 1) for field in fields: feature[field.name()] = f[field.name()] feature.setGeometry(geom) self.__renderer.renderFeature(feature, context) finally: self.__renderer.stopRender(context)
def _getPenAndBrush(self): """Get the pen and brush""" pen = QPen() blackBrush = QBrush(QColor("black")) whiteBrush = QBrush(QColor("white")) return pen, blackBrush, whiteBrush
def selectmarker(self, y): """ Marks one item """ selectpen = QPen(Qt.yellow) markline = self.scene().addLine(0, y, 250, y, selectpen) markline.setZValue(-1) self.selectlines.append(markline)
class DrawToolBar(object): NameSpace = getNameSpace() small_pt = 5 white_pen = QPen(Qt.white, small_pt) white_pen.setCapStyle(Qt.RoundCap) black_pen = QPen(Qt.black, small_pt) black_pen.setCapStyle(Qt.RoundCap) glass_pen = QPen(QColor(192, 192, 192, 128), 3) transparent_brush = QBrush(Qt.transparent) black_brush = QBrush(Qt.black) bold_12 = QFont("Arial", 12, QFont.Bold) # Stamp Image confidential = QPixmap.fromImage( QImage(":/imgFMV/images/stamp/confidential.png")) @staticmethod def setValues(options=None): ''' Function to set Drawing Values ''' s = QSettings() ####### Magnifier Glass ####### shape_type = s.value(DrawToolBar.NameSpace + "/Options/magnifier/shape") if shape_type is not None: global TYPE_MAGNIFIER TYPE_MAGNIFIER = shape_type if options is not None: if TYPE_MAGNIFIER == 0: # Square options.rB_Square_m.setChecked(True) else: # Circle options.rB_Circle_m.setChecked(True) mFactor = s.value(DrawToolBar.NameSpace + "/Options/magnifier/factor") if mFactor is not None: global MAX_FACTOR MAX_FACTOR = int(mFactor) if options is not None: options.sb_factor.setValue(MAX_FACTOR) mSize = s.value(DrawToolBar.NameSpace + "/Options/magnifier/size") if mSize is not None: global MAX_MAGNIFIER MAX_MAGNIFIER = int(mSize) if options is not None: options.sl_Size.setValue(MAX_MAGNIFIER) ####### Drawings ####### poly_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/width") if poly_w is not None: global PolyWidth PolyWidth = int(poly_w) if options is not None: options.poly_width.setValue(PolyWidth) poly_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/pen") if poly_p is not None: global PolyPen PolyPen = QPen(QColor(poly_p)) PolyPen.setCapStyle(Qt.RoundCap) PolyPen.setWidth(PolyWidth) if options is not None: options.poly_pen.setColor(QColor(poly_p)) poly_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/polygons/brush") if poly_b is not None: global PolyBrush PolyBrush = QBrush(QColor(poly_b)) if options is not None: options.poly_brush.setColor(QColor(poly_b)) point_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/width") if point_w is not None: global PointWidth PointWidth = int(point_w) if options is not None: options.point_width.setValue(PointWidth) point_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/points/pen") if point_p is not None: global PointPen PointPen = QPen(QColor(point_p)) PointPen.setCapStyle(Qt.RoundCap) PointPen.setWidth(PointWidth) if options is not None: options.point_pen.setColor(QColor(point_p)) line_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/width") if line_w is not None: global LineWidth LineWidth = int(line_w) if options is not None: options.lines_width.setValue(LineWidth) line_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/lines/pen") if line_p is not None: global LinePen LinePen = QPen(QColor(line_p)) LinePen.setCapStyle(Qt.RoundCap) LinePen.setWidth(LineWidth) if options is not None: options.lines_pen.setColor(QColor(line_p)) measure_w = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/width") if measure_w is not None: global MeasureWidth MeasureWidth = int(measure_w) if options is not None: options.measures_width.setValue(MeasureWidth) measure_p = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/pen") if measure_p is not None: global MeasurePen MeasurePen = QPen(QColor(measure_p)) MeasurePen.setCapStyle(Qt.RoundCap) MeasurePen.setWidth(MeasureWidth) if options is not None: options.measures_pen.setColor(QColor(measure_p)) measure_b = s.value(DrawToolBar.NameSpace + "/Options/drawings/measures/brush") if measure_b is not None: global MeasureBrush MeasureBrush = QBrush(QColor(measure_b)) if options is not None: options.measures_brush.setColor(QColor(measure_b)) return @staticmethod def drawOnVideo(drawPtPos, drawLines, drawPolygon, drawMDistance, drawMArea, drawCesure, painter, surface, gt): ''' Function to paint over the video ''' # Draw clicked points on video for position, pt in enumerate(drawPtPos): DrawToolBar.drawPointOnVideo(position + 1, pt, painter, surface, gt) # Draw clicked lines on video if len(drawLines) > 1: for idx, pt in enumerate(drawLines): if pt[0] is None: continue else: DrawToolBar.drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines) # Draw clicked Polygons on video if len(drawPolygon) > 1: poly = [] if any(None == x[1] for x in drawPolygon): for pt in drawPolygon: if pt[0] is None: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawPolygon) - drawPolygon[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawPolygon)): poly.append(drawPolygon[pt]) if len(poly) > 1: DrawToolBar.drawPolygonOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawPolygonOnVideo(drawPolygon, painter, surface, gt) # Draw Measure Distance on video # the measures don't persist in the video if len(drawMDistance) > 1: DrawToolBar.resetMeasureDistance() for idx, pt in enumerate(drawMDistance): if pt[0] is None: DrawToolBar.resetMeasureDistance() continue else: DrawToolBar.drawMeasureDistanceOnVideo( pt, idx, painter, surface, gt, drawMDistance) # Draw Measure Area on video # the measures don't persist in the video if len(drawMArea) > 1: poly = [] if any(None == x[1] for x in drawMArea): for pt in drawMArea: if pt[0] is None: DrawToolBar.drawMeasureAreaOnVideo( poly, painter, surface, gt) poly = [] continue poly.append(pt) last_occurence = len(drawMArea) - drawMArea[::-1].index( [None, None, None]) poly = [] for pt in range(last_occurence, len(drawMArea)): poly.append(drawMArea[pt]) if len(poly) > 1: DrawToolBar.drawMeasureAreaOnVideo(poly, painter, surface, gt) else: DrawToolBar.drawMeasureAreaOnVideo(drawMArea, painter, surface, gt) # Draw Censure if drawCesure: DrawToolBar.drawCensuredOnVideo(painter, drawCesure) return return @staticmethod def drawPointOnVideo(number, pt, painter, surface, gt): ''' Draw Points on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) # don't draw something outside the screen. if scr_x < vut.GetXBlackZone(surface) or scr_y < vut.GetYBlackZone( surface): return if scr_x > vut.GetXBlackZone(surface) + vut.GetNormalizedWidth( surface) or scr_y > vut.GetYBlackZone( surface) + vut.GetNormalizedHeight(surface): return center = QPoint(scr_x, scr_y) painter.setPen(PointPen) painter.drawPoint(center) painter.setFont(DrawToolBar.bold_12) painter.drawText(center + QPoint(5, -5), str(number)) return @staticmethod def drawLinesOnVideo(pt, idx, painter, surface, gt, drawLines): ''' Draw Lines on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) painter.setPen(LinePen) if len(drawLines) > 1: try: pt = drawLines[idx + 1] if hasElevationModel(): pt = GetLine3DIntersectionWithPlane( GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) # Draw Start/End Points painter.setPen(DrawToolBar.white_pen) painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawPolygonOnVideo(values, painter, surface, gt): ''' Draw Polygons on Video ''' poly = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setPen(PolyPen) painter.drawPolygon(polygon) painter.fillPath(path, PolyBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) return @staticmethod def resetMeasureDistance(): global RulerTotalMeasure RulerTotalMeasure = 0.0 @staticmethod def drawMeasureDistanceOnVideo(pt, idx, painter, surface, gt, drawMDistance): ''' Draw Measure Distance on Video ''' if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) if len(drawMDistance) > 1: try: painter.setPen(MeasurePen) end_pt = drawMDistance[idx + 1] if hasElevationModel(): end_pt = GetLine3DIntersectionWithPlane( GetSensor(), end_pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(end_pt[1], end_pt[0], gt, surface) end = QPoint(scr_x, scr_y) painter.drawLine(center, end) painter.setFont(DrawToolBar.bold_12) distance = round( sphere.distance((pt[0], pt[1]), (end_pt[0], end_pt[1])), 2) text = str(distance) + " m" global RulerTotalMeasure RulerTotalMeasure += distance # Line lenght painter.setPen(MeasurePen) painter.drawText(end + QPoint(5, -10), text) painter.setPen(DrawToolBar.white_pen) # Total lenght painter.drawText(end + QPoint(5, 10), str(round(RulerTotalMeasure, 2)) + " m") # Draw Start/End Points painter.drawPoint(center) painter.drawPoint(end) except Exception: None return @staticmethod def drawMeasureAreaOnVideo(values, painter, surface, gt): ''' Draw Measure Area on Video ''' a_value = sphere.polygon_area([values]) poly = [] lat = [] long = [] for pt in values: if hasElevationModel(): pt = GetLine3DIntersectionWithPlane(GetSensor(), pt, GetFrameCenter()[2]) scr_x, scr_y = vut.GetInverseMatrix(pt[1], pt[0], gt, surface) center = QPoint(scr_x, scr_y) poly.append(center) lat.append(pt[0]) long.append(pt[1]) lat = list(dict.fromkeys(lat)) long = list(dict.fromkeys(long)) # Calculate Centroid Position scr_x, scr_y = vut.GetInverseMatrix( sum(long) / len(long), sum(lat) / len(lat), gt, surface) centroid = QPoint(scr_x, scr_y) # Create Poligon polygon = QPolygonF(poly) path = QPainterPath() path.addPolygon(polygon) painter.setFont(DrawToolBar.bold_12) painter.setPen(MeasurePen) painter.drawPolygon(polygon) painter.fillPath(path, MeasureBrush) painter.setPen(DrawToolBar.white_pen) painter.drawPoints(polygon) # Area if a_value >= 10000: painter.drawText(centroid, str(round(a_value / 1000000, 2)) + " km²") else: painter.drawText(centroid, str(round(a_value, 2)) + " m²") return @staticmethod def drawCensuredOnVideo(painter, drawCesure): ''' Draw Censure on Video ''' try: for geom in drawCesure: painter.setPen(DrawToolBar.black_pen) painter.setBrush(DrawToolBar.black_brush) painter.drawRect(geom[0].x(), geom[0].y(), geom[0].width(), geom[0].height()) except Exception: None return @staticmethod def drawMagnifierOnVideo(widget, dragPos, source, painter): ''' Draw Magnifier on Video ''' oldTransform = painter.transform() painter.setTransform(oldTransform) painter.setBrush(DrawToolBar.transparent_brush) dim = min(widget.width(), widget.height()) magnifierSize = min(MAX_MAGNIFIER, dim * 2 / 3) radius = magnifierSize / 2 ring = radius - 15 box = QSize(magnifierSize, magnifierSize) center = dragPos - QPoint(0, radius) center += QPoint(0, radius / 2) corner = center - QPoint(radius, radius) xy = center * MAX_FACTOR - QPoint(radius, radius) # only set the dimension to the magnified portion zoomPixmap = QPixmap(box) zoomPixmap.fill(Qt.black) painter_p = QPainter(zoomPixmap) painter_p.setRenderHint(QPainter.HighQualityAntialiasing) painter_p.translate(-xy) painter_p.scale(MAX_FACTOR, MAX_FACTOR) painter_p.drawImage(widget.surface.videoRect(), source, widget.surface.sourceRect()) painter_p.end() clipPath = QPainterPath() center = QPointF(center) # Shape Type if TYPE_MAGNIFIER == 0: # Square clipPath.addRect(center.x(), center.y(), magnifierSize, magnifierSize) clipPath.translate(-radius, -radius) else: # Circle clipPath.addEllipse(center, ring, ring) painter.setClipPath(clipPath) painter.drawPixmap(corner, zoomPixmap) painter.setPen(DrawToolBar.glass_pen) painter.drawPath(clipPath) return @staticmethod def drawStampOnVideo(widget, painter): ''' Draw Stamp Confidential on Video ''' painter.drawPixmap(widget.surface.videoRect(), DrawToolBar.confidential, widget.surface.sourceRect())
def setupUi_plot(self): # plot self.plotLibSelector.setVisible(False) self.enableStatistics.setVisible(False) # stats by default because estimated are fast self.enableStatistics.setChecked(True) plot_count = 0 self.mplLine = None # make sure to invalidate when layers change if self.hasqwt: # Page 2 - qwt self.plotLibSelector.addItem('Qwt') plot_count += 1 # Setup Qwt Plot Area in Widget self.qwtPlot = QwtPlot(self.stackedWidget) self.qwtPlot.setAutoFillBackground(False) self.qwtPlot.setObjectName("qwtPlot") self.curve = QwtPlotCurve() self.curve.setSymbol( QwtSymbol(QwtSymbol.Ellipse, QBrush(Qt.white), QPen(Qt.red, 2), QSize(9, 9))) self.curve.attach(self.qwtPlot) # Size Policy ??? sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.qwtPlot.sizePolicy().hasHeightForWidth()) self.qwtPlot.setSizePolicy(sizePolicy) # Size Policy ??? self.qwtPlot.updateGeometry() self.stackedWidget.addWidget(self.qwtPlot) self.qwt_widgetnumber = self.stackedWidget.indexOf(self.qwtPlot) if self.hasmpl: # Page 3 - setup matplotlib self.plotLibSelector.addItem('matplotlib') # If matplotlib is the only one self.toggleInterpolation.setEnabled(True) self.toggleInterpolation.setVisible(True) plot_count += 1 self.mplBackground = None # http://www.scipy.org/Cookbook/Matplotlib/Animations self.mplFig = plt.Figure(facecolor='w', edgecolor='g', linewidth=0.0) self.mpl_subplot = self.mplFig.add_subplot(111) self.pltCanvas = FigureCanvasQTAgg(self.mplFig) self.pltCanvas.setParent(self.stackedWidget) self.pltCanvas.setAutoFillBackground(False) self.pltCanvas.setObjectName("mplPlot") self.mplPlot = self.pltCanvas self.mplPlot.updateGeometry() self.stackedWidget.addWidget(self.mplPlot) self.mpl_widgetnumber = self.stackedWidget.indexOf(self.mplPlot) if self.haspqg: # Page 3 - setup PyQtGraph self.plotLibSelector.addItem('PyQtGraph') plot_count += 1 # Setup PyQtGraph stuff pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') self.pqg_axis = DateTimeAxis(orientation='bottom') self.pqg_plot_widget = pg.PlotWidget( parent=self.stackedWidget, axisItems={'bottom': self.pqg_axis}) self.pqg_plot_item = self.pqg_plot_widget.getPlotItem() self.pqg_plot_widget.updateGeometry() self.stackedWidget.addWidget(self.pqg_plot_widget) self.pqg_widgetnumber = self.stackedWidget.indexOf( self.pqg_plot_widget) # on zoom change do: self.pqg_plot_item.sigXRangeChanged.connect(self.refresh_ticks) if plot_count > 1: self.plotLibSelector.setEnabled(True) self.plotLibSelector.setVisible(True) self.plotLibSelector.setCurrentIndex(0) if self.hasqwt: self.plotLibSelector.setCurrentIndex(self.qwt_widgetnumber) elif self.hasmpl: self.plotLibSelector.setCurrentIndex(self.mpl_widgetnumber) else: self.plotLibSelector.setCurrentIndex(self.pqg_widgetnumber) self.change_plot() elif plot_count == 1: self.plotLibSelector.setCurrentIndex(0) self.change_plot() else: # can only be 0 if nothing else matched message_text = "Mutant cannot find any graphiclibrary for " \ "creating plots. Please install either Qwt >= 5.0 " \ ",matplotlib >= 1.0 or PyQtGraph >= 0.9.8!" self.plot_message = QLabel(message_text) self.plot_message.setWordWrap(True) self.stackedWidget.addWidget(self.plot_message) self.pop_messagebar(message_text)
class GPSMarker(QgsMapCanvasItem): def __init__(self, canvas): super(GPSMarker, self).__init__(canvas) self.canvas = canvas self._quaility = 0 self._heading = 0 self.size = roam.config.settings.get('gps', {}).get('marker_size', 24) self.red = Qt.darkRed self.blue = QColor(129, 173, 210) self.green = Qt.darkGreen self._gpsinfo = QgsGpsInformation() self.pointbrush = QBrush(self.red) self.pointpen = QPen(Qt.black) self.pointpen.setWidth(1) self.map_pos = QgsPoint(0.0, 0.0) self.gps = None def setgps(self, gps): self.gps = gps def setSize(self, size): self.size = size def paint(self, painter, xxx, xxx2): self.setPos(self.toCanvasCoordinates(self.map_pos)) halfSize = self.size / 2.0 rect = QRectF(0 - halfSize, 0 - halfSize, self.size, self.size) painter.setRenderHint(QPainter.Antialiasing) if self.quality == 0: color = self.red elif self.quality == 1: color = self.green elif self.quality >= 2: color = self.blue else: color = self.red self.pointpen.setColor(Qt.gray) self.pointpen.setWidth(2) self.pointbrush.setColor(color) painter.setBrush(self.pointbrush) painter.setPen(self.pointpen) y = 0 - halfSize x = rect.width() / 2 - halfSize line = QLine(x, y, x, rect.height() - halfSize) y = rect.height() / 2 - halfSize x = 0 - halfSize line2 = QLine(x, y, rect.width() - halfSize, y) # Arrow p = QPolygonF() p.append(QPoint(0 - halfSize, 0)) p.append(QPoint(0, -self.size)) x = rect.width() - halfSize p.append(QPoint(x, 0)) p.append(QPoint(0, 0)) offsetp = QPolygonF() offsetp.append(QPoint(0 - halfSize, 0)) offsetp.append(QPoint(0, -self.size)) x = rect.width() - halfSize offsetp.append(QPoint(x, 0)) offsetp.append(QPoint(0, 0)) waypoint = self.gps.waypoint if waypoint: az = self.map_pos.azimuth(waypoint) painter.save() painter.rotate(az) self.pointbrush.setColor(Qt.red) painter.setBrush(self.pointbrush) path = QPainterPath() path.addPolygon(offsetp) painter.drawPath(path) painter.restore() painter.save() painter.rotate(self._heading) path = QPainterPath() path.addPolygon(p) painter.drawPath(path) painter.restore() painter.drawEllipse(rect) painter.drawLine(line) painter.drawLine(line2) def boundingRect(self): halfSize = self.size / 2.0 size = self.size * 2 return QRectF(-size, -size, 2.0 * size, 2.0 * size) @property def quality(self): return self._gpsinfo.quality @quality.setter def quality(self, value): self._quaility = value self.update() def setCenter(self, map_pos, gpsinfo): self._heading = gpsinfo.direction self._gpsinfo = gpsinfo self.map_pos = QgsPointXY(map_pos) self.setPos(self.toCanvasCoordinates(self.map_pos)) def updatePosition(self): self.setCenter(self.map_pos, self._gpsinfo)
class Toggle(QCheckBox): # This widget was originally implemented by Martin Fitzpatrick # @ https://github.com/learnpyqt/python-qtwidgets # It is slightly modified to be used as a state toggle button _transparent_pen = QPen(Qt.transparent) _light_grey_pen = QPen(Qt.lightGray) def __init__(self, parent=None, bar_color=Qt.gray, checked_color="#00B0FF", handle_color=Qt.white, labels=None): super().__init__(parent) self.setLabels(labels) # Save our properties on the object via self, so we can access them later # in the paintEvent. self._bar_brush = QBrush(bar_color) self._bar_checked_brush = QBrush(QColor(checked_color).lighter()) self._handle_brush = QBrush(handle_color) self._handle_checked_brush = QBrush(QColor(checked_color)) # Setup the rest of the widget. self.setContentsMargins(8, 0, 8, 0) self._handle_position = 0 self.stateChanged.connect(self.handle_state_change) def sizeHint(self): return QSize(58, 45) def hitButton(self, pos: QPoint): return self.contentsRect().contains(pos) def setLabels(self, labels: tuple): """ Sets the labels to be displayed for each state the button may represent. :param labels: (tuple-of-str) text to be displayed for each toggling state. """ if labels is None or len(labels) != 2: return self._labels = labels def getLabel(self, state: bool): """ Gets the label to be displyed on the button accordingly to its state. :param state: (bool) whether this button is toggle (checked). :return: (str) label to be displayed """ if self._labels is None: return "" return self._labels[int(state)] def paintEvent(self, e: QPaintEvent): contRect = self.contentsRect() handleRadius = round(0.24 * contRect.height()) p = QPainter(self) p.setRenderHint(QPainter.Antialiasing) p.setPen(self._transparent_pen) barRect = QRectF(0, 0, contRect.width() - handleRadius, 0.40 * contRect.height()) barRect.moveCenter(contRect.center()) rounding = barRect.height() / 2 # the handle will move along this line trailLength = contRect.width() - 2 * handleRadius xPos = contRect.x( ) + handleRadius + trailLength * self._handle_position if self.isChecked(): p.setBrush(self._bar_checked_brush) p.drawRoundedRect(barRect, rounding, rounding) # p.drawText(barRect, self.getLabel(True)) p.setBrush(self._handle_checked_brush) else: p.setBrush(self._bar_brush) p.drawRoundedRect(barRect, rounding, rounding) # p.drawText(barRect, self.getLabel(False)) p.setPen(self._light_grey_pen) p.setBrush(self._handle_brush) p.drawEllipse(QPointF(xPos, barRect.center().y()), handleRadius, handleRadius) p.end() @pyqtSlot(int) def handle_state_change(self, value): self._handle_position = 1 if value else 0 @pyqtProperty(float) def handle_position(self): return self._handle_position @handle_position.setter def handle_position(self, pos): """change the property we need to trigger QWidget.update() method, either by: 1- calling it here [ what we're doing ]. 2- connecting the QPropertyAnimation.valueChanged() signal to it. """ self._handle_position = pos self.update()
def paint(self, painter, option, widget=None): rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2.0, -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2.0, ModelerGraphicItem.BOX_WIDTH + 2, ModelerGraphicItem.BOX_HEIGHT + 2) if isinstance(self.element, QgsProcessingModelParameter): color = QColor(238, 242, 131) stroke = QColor(234, 226, 118) selected = QColor(116, 113, 68) elif isinstance(self.element, QgsProcessingModelChildAlgorithm): color = QColor(255, 255, 255) stroke = Qt.gray selected = QColor(50, 50, 50) else: color = QColor(172, 196, 114) stroke = QColor(90, 140, 90) selected = QColor(42, 65, 42) if self.isSelected(): stroke = selected color = color.darker(110) painter.setPen(QPen(stroke, 0)) # 0 width "cosmetic" pen painter.setBrush(QBrush(color, Qt.SolidPattern)) painter.drawRect(rect) font = QFont('Verdana', 8) font.setPixelSize(12) painter.setFont(font) painter.setPen(QPen(Qt.black)) text = self.getAdjustedText(self.text) if isinstance(self.element, QgsProcessingModelChildAlgorithm ) and not self.element.isActive(): painter.setPen(QPen(Qt.gray)) text = text + "\n(deactivated)" fm = QFontMetricsF(font) text = self.getAdjustedText(self.text) h = fm.ascent() pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, ModelerGraphicItem.BOX_HEIGHT / 2.0 - h + 1) painter.drawText(pt, text) painter.setPen(QPen(Qt.black)) if isinstance(self.element, QgsProcessingModelChildAlgorithm): h = -(fm.height() * 1.2) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'In') i = 1 if not self.element.parametersCollapsed(): for param in [ p for p in self.element.algorithm().parameterDefinitions() if not p.isDestination() ]: if not param.flags( ) & QgsProcessingParameterDefinition.FlagHidden: text = self.getAdjustedText(param.description()) h = -(fm.height() * 1.2) * (i + 1) h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) i += 1 h = fm.height() * 1.1 h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h) painter.drawText(pt, 'Out') if not self.element.outputsCollapsed(): for i, out in enumerate( self.element.algorithm().outputDefinitions()): text = self.getAdjustedText(out.description()) h = fm.height() * 1.2 * (i + 2) h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h) painter.drawText(pt, text) if self.pixmap: painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8, self.pixmap) elif self.picture: painter.drawPicture(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8, self.picture)
def drawspectra(self): """ Drawing the spectra on the graphicsstage """ layername = self.dlg.qgLayer.currentText() fieldname = self.dlg.qgField.currentText() layer = self.dlg.qgLayer.currentLayer() if layer == None: return # Happens some times, just as well to return self.scene.acalib = float(self.dlg.leA.text()) self.scene.bcalib = float(self.dlg.leB.text()) self.scene.unit = self.dlg.leUnit.text() logscale = self.dlg.cbLog.isChecked() if logscale: dataset = [] for n in self.view.spectreval: if n == 0: n = 0.9 dataset.append(math.log(n) - math.log(0.9)) # 0.9 offset and back to be able to plot zero-values else: dataset = self.view.spectreval #DONE: Add x and y axis #DONE: Add scale factors to scale x axis from channel number to keV #DONE: Add settings to have custom unit #TODO: Custom scales #TODO: Keep spectra to compare #DONE: Draw spectra as line, not "line-histogram" #TODO: Select different drawing styles #DONE: Save as file #DONE: export data to clipboard #TODO: export image to clipboard #TODO: Peak detection #TODO: Save different set of calibration values self.scene.h = 300 # Height of stage self.scene.clear() self.scene.crdtext = None self.scene.markerline = None backgroundbrush = QBrush(Qt.white) outlinepen = QPen(Qt.white) # Needs this when saving as png, or background from map will shine through self.scene.addRect(0, 0, 1200, 300, outlinepen, backgroundbrush) self.scene.bottom = 20 # Bottom clearing (for x tick marks and labels) self.scene.left = self.scene.bottom # Left clearing (for y tick marks and labels) n = self.scene.left bt = self.scene.bottom h = self.scene.h self.scene.addLine(float(n - 1), float(h - bt), float(n - 1), 10.0) # Y-axis self.scene.addLine(float(n - 1), float(h - bt - 1), float(len(dataset) + 10), float(h - bt - 1)) # X-axis # Scales the spectra to fit with the size of the graphicsview fact = 1.0 fact = (h - bt - 10) / max(dataset) prevch = 0 for ch in dataset: # TODO: User selectable type of plot # self.scene.addLine(float(n),float(h-bt),float(n),(h-bt-fact*ch)) # self.scene.addLine(float(n),float(h-(bt+4)-fact*ch),float(n),(h-bt-fact*ch)) self.scene.addLine(float(n), float(h - bt - fact * prevch), float(n + 1), (h - bt - fact * ch)) prevch = ch n += 1 self.scene.end = n - 1 tickval = self.tickinterval s = QgsSettings() layername = self.dlg.qgLayer.currentText() fieldname = self.dlg.qgField.currentText() # This is already read in from the fields #acalib=s.value(self.pluginname+"/"+layername+"_"+fieldname+"_a",s.value(self.pluginname+"/defaulta", 1)) #bcalib=s.value(self.pluginname+"/"+layername+"_"+fieldname+"_b",s.value(self.pluginname+"/defaultb", 0)) #self.scene.unit=s.value(self.pluginname+"/"+layername+"_"+fieldname+"_unit",s.value(self.pluginname+"/defaultunit", 0)) acalib = self.scene.acalib bcalib = self.scene.bcalib maxval = acalib * n + bcalib tickdist = tickval #if maxval/n > 5: # Avoids to tight numbering. # tickdist*=2 # Needs some better vay of doing this - left = self.scene.left while tickval < maxval: tickch = (tickval - bcalib) / acalib + left self.scene.addLine(float(tickch), float(h - bt), float(tickch), float(h - bt + 5)) # Ticklines text = self.scene.addText(str(tickval)) text.setPos(tickch + left - 40, 280) tickval += tickdist text = self.scene.addText(self.scene.unit) text.setPos(self.scene.end + 15, 280) ntext = self.scene.addText("n = {}".format(str(self.view.n))) ntext.setPos(self.scene.end + 50, 1)