def data(self, index, role=Qt.DisplayRole): column = index.column() if role == Qt.DisplayRole: field = self._mapping[index.row()] column_def = self.columns[column] value = field[column_def['name']] fieldType = column_def['type'] if fieldType == QVariant.Type: if value == QVariant.Invalid: return '' return self.fieldTypes[value] return value if role == Qt.EditRole: field = self._mapping[index.row()] column_def = self.columns[column] value = field[column_def['name']] return value if role == Qt.TextAlignmentRole: fieldType = self.columns[column]['type'] if fieldType in [QVariant.Int]: hAlign = Qt.AlignRight else: hAlign = Qt.AlignLeft return hAlign + Qt.AlignVCenter if role == Qt.ForegroundRole: column_def = self.columns[column] if column_def['name'] == 'expression': brush = QBrush() if self._errors[index.row()]: brush.setColor(Qt.red) else: brush.setColor(Qt.black) return brush if role == Qt.ToolTipRole: column_def = self.columns[column] if column_def['name'] == 'expression': return self._errors[index.row()]
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)
def CreatePDF(self, task, out, timestamp, data, frame, rows, columns, fileName, VManager): ''' Create PDF QgsTask ''' font_normal = QFont("Helvetica", 8, QFont.Normal) font_bold = QFont("Helvetica", 9, QFont.Bold) printer = QPrinter(QPrinter.HighResolution) printer.setOutputFormat(QPrinter.PdfFormat) printer.setPageSize(QPrinter.A4) printer.setOutputFileName(out) printer.setFullPage(True) document = QTextDocument() document.setDefaultFont(font_normal) document.setPageSize(printer.paperSize(QPrinter.Point)); cursor = QTextCursor(document) video_t = QCoreApplication.translate("QgsFmvMetadata", "Video : ") time_t = QCoreApplication.translate("QgsFmvMetadata", "TimeStamp : ") cursor.insertHtml( """ <p style='text-align: center;'> <img style='display: block; margin-left: auto; margin-right: auto;' src=\':/imgFMV/images/header_logo.png\' width='200' height='25' /> <p style='text-align: center;'> <strong>%s</strong>%s<strong> <p style='text-align: center;'> <strong>%s</strong>%s <p></p> """ % (video_t, fileName, time_t, timestamp)) tableFormat = QTextTableFormat() tableFormat.setBorderBrush(QBrush(Qt.black)) tableFormat.setAlignment(Qt.AlignHCenter) tableFormat.setHeaderRowCount(1) tableFormat.setCellPadding(2) tableFormat.setCellSpacing(2) cursor.insertTable(rows + 1, columns, tableFormat) tableHeaderFormat = QTextCharFormat() tableHeaderFormat.setFont(font_bold) tableHeaderFormat.setBackground(QColor("#67b03a")) tableHeaderFormat.setForeground(Qt.white) tableHeaderFormat.setVerticalAlignment(QTextCharFormat.AlignMiddle) alternate_background = QTextCharFormat() alternate_background.setBackground(QColor("#DDE9ED")) for column in range(columns): cursor.mergeBlockCharFormat(tableHeaderFormat) cursor.insertText(VManager.horizontalHeaderItem( column).text()) cursor.movePosition(QTextCursor.NextCell) row = 1 for key in sorted(data.keys()): values = [str(key), str(data[key][0]),str(data[key][1])] for column in range(columns): cursor.insertText(values[column]) if (row) % 2 == 0: cursor.mergeBlockCharFormat(alternate_background) cursor.movePosition(QTextCursor.NextCell) row += 1 cursor.movePosition(QTextCursor.End) current_t = QCoreApplication.translate("QgsFmvMetadata", "Current Frame") self.TextBlockCenter(cursor, TextFormat= QTextFormat.PageBreak_AlwaysBefore) cursor.insertHtml(""" <br><p style='text-align: center;'><strong>""" + current_t +"""</strong></p><br> """) self.TextBlockCenter(cursor) cursor.insertImage(frame.scaledToWidth(500, Qt.SmoothTransformation)) document.print_(printer) if task.isCanceled(): return None return {'task': task.description()}
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 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 draw(self, renderContext): self.renderContext = renderContext extent = renderContext.extent() if extent.isEmpty() or extent.width() == float("inf"): qDebug("Drawing is skipped because map extent is empty or inf.") return True mapSettings = self.iface.mapCanvas().mapSettings() painter = renderContext.painter() isDpiEqualToCanvas = painter.device().logicalDpiX( ) == mapSettings.outputDpi() if isDpiEqualToCanvas or not self.useLastZoomForPrint: # calculate zoom level tile_mpp1 = self.layerDef.tsize1 / self.layerDef.TILE_SIZE # should be attribute, not method call.. viewport_mpp = extent.width() / painter.viewport().width() lg = math.log(float(tile_mpp1) / float(viewport_mpp), 2) zoom = int(math.modf( lg)[1]) + 1 * (math.modf(lg)[0] > self.CHANGE_SCALE_VALUE) + 1 zoom = max(0, min(zoom, self.layerDef.zmax)) # zoom = max(self.layerDef.zmin, zoom) else: # for print composer output image, use last zoom level of map item on print composer (or map canvas) zoom = self.canvasLastZoom # zoom limit if zoom < self.layerDef.zmin: msg = self.tr( "Current zoom level ({0}) is smaller than zmin ({1}): {2}" ).format(zoom, self.layerDef.zmin, self.layerDef.title) self.emitShowBarMessage(msg, QGisMessageBarLevel.Info, 2) return True while True: # calculate tile range (yOrigin is top) size = self.layerDef.tsize1 / 2**(zoom - 1) if self.layerDef.tile_ranges is None: # should add xOffset & yOffset in first part of conditional matrixSize = 2**zoom ulx = max( 0, int((extent.xMinimum() + self.layerDef.tsize1) / size)) uly = max( 0, int((self.layerDef.tsize1 - extent.yMaximum()) / size)) lrx = min( int((extent.xMaximum() + self.layerDef.tsize1) / size), matrixSize - 1) lry = min( int((self.layerDef.tsize1 - extent.yMinimum()) / size), matrixSize - 1) else: # for tile_ranges xmin, xmax, ymin, ymax = self.layerDef.tile_ranges[zoom] ulx = max( int((extent.xMinimum() - self.layerDef.originX) / size), xmin) uly = max( int((self.layerDef.originY - extent.yMaximum()) / size), ymin) lrx = min( int((extent.xMaximum() - self.layerDef.originX) / size), xmax) lry = min( int((self.layerDef.originY - extent.yMinimum()) / size), ymax) # bounding box limit if self.layerDef.bbox: trange = self.layerDef.bboxDegreesToTileRange( zoom, self.layerDef.bbox) ulx = max(ulx, trange.xmin) uly = max(uly, trange.ymin) lrx = min(lrx, trange.xmax) lry = min(lry, trange.ymax) if lrx < ulx or lry < uly: # tile range is out of the bounding box return True # tile count limit tileCount = (lrx - ulx + 1) * (lry - uly + 1) if tileCount > self.MAX_TILE_COUNT: # as tile count is over the limit, decrease zoom level zoom -= 1 # if the zoom level is less than the minimum, do not draw if zoom < self.layerDef.zmin: msg = self.tr( "Tile count is over limit ({0}, max={1})").format( tileCount, self.MAX_TILE_COUNT) self.emitShowBarMessage(msg, QGisMessageBarLevel.Warning, 4) return True continue # zoom level has been determined break self.logT("TileLayer.draw: {0} {1} {2} {3} {4}".format( zoom, ulx, uly, lrx, lry)) # save painter state painter.save() # set pen and font painter.setPen(Qt.black) font = QFont(painter.font()) font.setPointSize(10) painter.setFont(font) if self.layerDef.serviceUrl[0] == ":": painter.setBrush(QBrush(Qt.NoBrush)) self.drawDebugInfo(renderContext, zoom, ulx, uly, lrx, lry) else: # create Tiles class object and throw url into it tiles = Tiles(zoom, ulx, uly, lrx, lry, self.layerDef) urls = [] cacheHits = 0 for ty in range(uly, lry + 1): for tx in range(ulx, lrx + 1): data = None url = self.layerDef.tileUrl(zoom, tx, ty) if self.tiles and zoom == self.tiles.zoom and url in self.tiles.tiles: data = self.tiles.tiles[url].data tiles.addTile(url, Tile(zoom, tx, ty, data)) if data is None: urls.append(url) elif data: # memory cache exists cacheHits += 1 # else: # tile was not found (Downloader.NOT_FOUND=0) self.tiles = tiles if len(urls) > 0: # fetch tile data files = self.fetchFiles(urls) for url in files.keys(): self.tiles.setImageData(url, files[url]) if self.iface: cacheHits += self.downloader.cacheHits downloadedCount = self.downloader.fetchSuccesses - self.downloader.cacheHits msg = self.tr( "{0} files downloaded. {1} cache hits.").format( downloadedCount, cacheHits) barmsg = None if self.downloader.errorStatus != Downloader.NO_ERROR: if self.downloader.errorStatus == Downloader.TIMEOUT_ERROR: barmsg = self.tr("Download Timeout - {}").format( self.name()) else: msg += self.tr(" {} files failed.").format( self.downloader.fetchErrors) if self.downloader.fetchSuccesses == 0: barmsg = self.tr( "Failed to download all {0} files. - {1}" ).format(self.downloader.fetchErrors, self.name()) self.showStatusMessage(msg, 5000) if barmsg: self.emitShowBarMessage(barmsg, QGisMessageBarLevel.Warning, 4) # apply layer style oldOpacity = painter.opacity() painter.setOpacity(0.01 * (100 - self.transparency)) oldSmoothRenderHint = painter.testRenderHint( QPainter.SmoothPixmapTransform) if self.smoothRender: painter.setRenderHint(QPainter.SmoothPixmapTransform) # draw tiles if not renderContext.coordinateTransform(): # no need to reproject tiles self.drawTiles(renderContext, self.tiles) # self.drawTilesDirectly(renderContext, self.tiles) else: # reproject tiles self.drawTilesOnTheFly(renderContext, self.tiles) # restore layer style painter.setOpacity(oldOpacity) if self.smoothRender: painter.setRenderHint(QPainter.SmoothPixmapTransform, oldSmoothRenderHint) # draw credit on the bottom right corner if self.creditVisibility and self.layerDef.credit: margin, paddingH, paddingV = (3, 4, 3) # scale scaleX, scaleY = self.getScaleToVisibleExtent(renderContext) scale = max(scaleX, scaleY) painter.scale(scale, scale) visibleSWidth = painter.viewport().width() * scaleX / scale visibleSHeight = painter.viewport().height() * scaleY / scale rect = QRect(0, 0, visibleSWidth - margin, visibleSHeight - margin) textRect = painter.boundingRect(rect, Qt.AlignBottom | Qt.AlignRight, self.layerDef.credit) bgRect = QRect(textRect.left() - paddingH, textRect.top() - paddingV, textRect.width() + 2 * paddingH, textRect.height() + 2 * paddingV) painter.fillRect(bgRect, QColor(240, 240, 240, 150)) # 197, 234, 243, 150)) painter.drawText(rect, Qt.AlignBottom | Qt.AlignRight, self.layerDef.credit) # restore painter state painter.restore() if isDpiEqualToCanvas: # save zoom level for printing (output with different dpi from map canvas) self.canvasLastZoom = zoom return True
def setSkipped(self, layer_id, category): item, subitem = self.getItem(layer_id, category, True) subitem.setForeground(1, QBrush(Qt.gray)) subitem.setText(1, "Skipped") self.setMetadata(item, category) QCoreApplication.processEvents()
def update_available_layers(self): self.trw_layers.setUpdatesEnabled( False) # Don't render until we're ready # Grab some context data show_domains = self.chk_show_domains.isChecked() show_structures = self.chk_show_structures.isChecked() show_associations = self.chk_show_associations.isChecked() top_level_items_expanded_info = [] for i in range(self.trw_layers.topLevelItemCount()): top_level_items_expanded_info.append( self.trw_layers.topLevelItem(i).isExpanded()) # Save selection self.update_selected_items() # Iterate models adding children self.trw_layers.blockSignals( True) # We don't want to get itemSelectionChanged here self.trw_layers.clear() self.trw_layers.blockSignals(False) sorted_models = sorted(self.models_tree.keys()) for model in sorted_models: children = [] model_item = QTreeWidgetItem([model]) # Filter by search text list_tables = self.filter_tables_by_search_text( self.models_tree[model].keys(), self.txt_search_text.text()) sorted_tables = sorted(list_tables) for table in sorted_tables: current_table_info = self.models_tree[model][table] if current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN and not show_domains \ or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE and not show_structures \ or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION and not show_associations: continue table_item = QTreeWidgetItem([table]) table_item.setData(0, Qt.UserRole, self.models_tree[model][table]) geometry_type = QgsWkbTypes().geometryType( QgsWkbTypes().parseType(current_table_info[ QueryNames.GEOMETRY_TYPE_MODEL_BAKER]) ) if current_table_info[ QueryNames.GEOMETRY_TYPE_MODEL_BAKER] else None icon_name = self.icon_names[ 3 if geometry_type is None else geometry_type] # Is the layer already loaded in canvas? if self.app.core.get_ladm_layer_from_qgis( self._db, current_table_info[QueryNames.TABLE_NAME_MODEL_BAKER], EnumLayerRegistryType.IN_LAYER_TREE) is not None: table_item.setText( 0, table + QCoreApplication.translate( "LoadLayersDialog", " [already loaded]")) table_item.setData(0, Qt.ForegroundRole, QBrush(Qt.lightGray)) table_item.setFlags(Qt.ItemIsEnabled) # Not selectable else: # Laye not in QGIS Layer Tree if not current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER]: # This is a class font = QFont() font.setBold(True) table_item.setData(0, Qt.FontRole, font) if current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN: icon_name = self.icon_names[4] elif current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE: if geometry_type is None: icon_name = self.icon_names[5] elif current_table_info[ QueryNames. KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION: icon_name = self.icon_names[6] icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format( icon_name)) table_item.setData(0, Qt.DecorationRole, icon) children.append(table_item) model_item.addChildren(children) self.trw_layers.addTopLevelItem(model_item) # Set selection iterator = QTreeWidgetItemIterator(self.trw_layers, QTreeWidgetItemIterator.Selectable) self.trw_layers.blockSignals( True) # We don't want to get itemSelectionChanged here while iterator.value(): item = iterator.value() if item.text(0) in self.selected_items_dict: item.setSelected(True) iterator += 1 self.trw_layers.blockSignals(False) # Make model items non selectable # Set expand taking previous states into account for i in range(self.trw_layers.topLevelItemCount()): self.trw_layers.topLevelItem(i).setFlags( Qt.ItemIsEnabled) # Not selectable self.trw_layers.topLevelItem(i).setExpanded( top_level_items_expanded_info[i] if top_level_items_expanded_info else True) self.trw_layers.setUpdatesEnabled(True) # Now render!
def treeItemChanged(self, current, previous): if not isinstance(current, FeatureItem): self.attributesTable.clear() self.attributesTable.setHorizontalHeaderLabels( ["Old value", "New value", "Change type"]) self.attributesTable.setRowCount(0) return new = current.new old = current.old reference = new or old changeTypeColor = [Qt.green, QColor(255, 170, 0), Qt.red, Qt.white] changeTypeName = ["Added", "Modified", "Removed", "Unchanged"] self.attributesTable.clear() self.attributesTable.verticalHeader().show() self.attributesTable.horizontalHeader().show() self.attributesTable.setRowCount(len(reference.fields().toList()) + 1) fields = [f.name() for f in reference.fields().toList()] labels = fields + ["geometry"] self.attributesTable.setVerticalHeaderLabels(labels) self.attributesTable.setHorizontalHeaderLabels( ["Old value", "New value", "Change type"]) for i, attrib in enumerate(fields): try: if old is None: newvalue = new[attrib] oldvalue = "" changeType = ADDED elif new is None: oldvalue = old[attrib] newvalue = "" changeType = REMOVED else: oldvalue = old[attrib] newvalue = new[attrib] if oldvalue != newvalue: changeType = MODIFIED else: changeType = UNCHANGED except: oldvalue = newvalue = "" changeType = UNCHANGED self.attributesTable.setItem(i, 0, DiffItem(oldvalue)) self.attributesTable.setItem(i, 1, DiffItem(newvalue)) self.attributesTable.setItem(i, 2, DiffItem(changeTypeName[changeType])) for col in range(3): self.attributesTable.item(i, col).setBackground( QBrush(changeTypeColor[changeType])) row = len(reference.fields().toList()) if old is None: newvalue = QgsWkbTypes.displayString( new.geometry().wkbType()) if new.geometry() is not None else "" newvalue_tooltip = new.geometry().asWkt() if new.geometry( ) is not None else None oldvalue = "" oldvalue_tooltip = None changeType = ADDED elif new is None: oldvalue = QgsWkbTypes.displayString( old.geometry().wkbType()) if old.geometry() else "" oldvalue_tooltip = old.geometry().asWkt() if old.geometry( ) is not None else None newvalue = "" newvalue_tooltip = None changeType = REMOVED else: oldvalue = QgsWkbTypes.displayString( old.geometry().wkbType()) if old.geometry() else "" newvalue_tooltip = new.geometry().asWkt() if new.geometry( ) is not None else None oldvalue_tooltip = old.geometry().asWkt() if old.geometry( ) is not None else None newvalue = QgsWkbTypes.displayString( new.geometry().wkbType()) if new.geometry() else "" if old.geometry().asWkt() != new.geometry().asWkt(): changeType = MODIFIED else: changeType = UNCHANGED self.attributesTable.setItem( row, 0, DiffItem(oldvalue, tooltip=oldvalue_tooltip)) self.attributesTable.setItem( row, 1, DiffItem(newvalue, tooltip=newvalue_tooltip)) self.attributesTable.setItem(row, 2, DiffItem(changeTypeName[changeType])) for col in range(3): try: self.attributesTable.item(row, col).setBackground( QBrush(changeTypeColor[changeType])) except: pass self.attributesTable.horizontalHeader().setMinimumSectionSize(88) self.attributesTable.resizeColumnsToContents() header = self.attributesTable.horizontalHeader() for column in range(header.count()): header.setSectionResizeMode( column, QHeaderView.Fixed ) # can set this to ResizeToContents or Stretch width = header.sectionSize(column) header.resizeSection(column, width) header.setSectionResizeMode(column, QHeaderView.Interactive)
def setMetadata(item, category): if item and category == METADATA: item.setForeground(1, QBrush(Qt.blue)) item.setIcon(1, CHECK_ICON)
def data(self, index: QModelIndex, role: Qt.ItemDataRole = Qt.DisplayRole) -> Union[ None, QBrush, QFont, Qt.AlignmentFlag, str]: """ Returns data from the table cell? """ if not index.isValid() or not 0 <= index.row() < self.rowCount(): return None row = index.row() - self.offsetY column = index.column() - self.offsetX if role == Qt.DisplayRole: # Table cell data if row >= 0 and column >= 0: return self.tab[row][column][0] # Row descriptions? elif column < 0 and row >= 0 and self.rows[0]: return self.rows[row + 1][column] # Row title field? elif row == -1 and column < 0 and self.rows[0]: return self.rows[0][column] # Column description and names? elif column >= -1 and row < 0 and self.columns[0]: if self.rows[0]: # Break line? if row == -1: return '' # Descriptions and column names if there is a break line? return self.columns[column + 1][row + 1] # Column descriptions and names if there is no break line? return self.columns[column + 1][row] elif role == Qt.UserRole: if row >= 0 and column >= 0: return self.tab[row][column][1] elif role == Qt.UserRole + 1: if row < 0 and column >= 0: return 'column' elif row >= 0 and column < 0: return 'row' elif row >= 0 and column >= 0: return 'data' # Cell filling elif role == Qt.BackgroundRole: if row < 0 or column < 0: # Gray for cells with descriptions and names color = QColor(245, 235, 235) brush = QBrush(color) return brush elif role == Qt.TextAlignmentRole: if column < 0 and row < -1 and self.rows: return Qt.AlignRight | Qt.AlignVCenter elif column >= 0 and row < 0: return Qt.AlignHCenter | Qt.AlignVCenter elif column >= 0 and row >= 0: return Qt.AlignRight | Qt.AlignVCenter elif role == Qt.FontRole: if row < 0 and column < 0: font = QFont() font.setBold(True) return font return None
def append_CharacterMarkerSymbolLayerAsSvg(symbol, layer, context: Context): # pylint: disable=too-many-locals """ Appends a CharacterMarkerSymbolLayer to a symbol, rendering the font character to an SVG file. """ font_family = layer.font character = chr(layer.unicode) color = symbol_color_to_qcolor(layer.color) angle = convert_angle(layer.angle) font = QFont(font_family) font.setPointSizeF(layer.size) # Using the rect of a painter path gives better results then using font metrics path = QPainterPath() path.setFillRule(Qt.WindingFill) path.addText(0, 0, font, character) rect = path.boundingRect() font_bounding_rect = QFontMetricsF(font).boundingRect(character) # adjust size -- marker size in esri is the font size, svg marker size in qgis is the svg rect size scale = rect.width() / font_bounding_rect.width() gen = QSvgGenerator() svg_path = symbol_name_to_filename(context.symbol_name, context.picture_folder, 'svg') gen.setFileName(svg_path) gen.setViewBox(rect) painter = QPainter(gen) painter.setFont(font) # todo -- size! if context.parameterise_svg: painter.setBrush(QBrush(QColor(255, 0, 0))) else: painter.setBrush(QBrush(color)) painter.setPen(Qt.NoPen) painter.drawPath(path) painter.end() if context.parameterise_svg: with open(svg_path, 'r') as f: t = f.read() t = t.replace('#ff0000', 'param(fill)') t = t.replace('fill-opacity="1" ', 'fill-opacity="param(fill-opacity)"') t = t.replace( 'stroke="none"', 'stroke="param(outline)" stroke-opacity="param(outline-opacity) 1" stroke-width="param(outline-width) 0"' ) with open(svg_path, 'w') as f: f.write(t) svg_path = context.convert_path(svg_path) out = QgsSvgMarkerSymbolLayer(svg_path) out.setSizeUnit(context.units) out.setSize(context.convert_size(scale * rect.width())) out.setAngle(angle) out.setFillColor(color) out.setStrokeWidth(0) out.setEnabled(layer.enabled) out.setLocked(layer.locked) out.setOffset( adjust_offset_for_rotation( QPointF(context.convert_size(layer.x_offset), -context.convert_size(layer.y_offset)), layer.angle)) out.setOffsetUnit(context.units) symbol.appendSymbolLayer(out)
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 colorBackground(self, row, col, color): self.model.setData(self.model.index(row, col), QBrush(color), Qt.BackgroundRole)
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 _recurse_tree(self, bl_el=None, proj_el=None, parent: QStandardItem = None): if self.business_logic is None: return if bl_el is None: bl_el = self.business_logic.find('Node') is_root = proj_el is None bl_attr = bl_el.attrib if proj_el is None: proj_el = self.project new_proj_el = proj_el if 'xpath' in bl_el.attrib: new_proj_el = xpathone_withref(self.project, proj_el, bl_el.attrib['xpath']) if new_proj_el is None: # We just ignore layers we can't find. Log them though return # The label is either explicit or it's an xpath lookup curr_label = '<unknown>' if 'label' in bl_el.attrib: curr_label = bl_el.attrib['label'] elif 'xpathlabel' in bl_el.attrib: found = new_proj_el.xpath(bl_el.attrib['xpathlabel']) curr_label = found[0].text if found is not None and len( found) > 0 else '<unknown>' curr_item = QStandardItem() curr_item.setText(curr_label) children_container = bl_el.find('Children') # If there are children then this is a branch if children_container: curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/BrowseFolder.png')) if is_root is True: curr_item.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_ROOT, project=self, data=dict(children_container.attrib)), Qt.UserRole), else: curr_item.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_FOLDER, project=self, data=dict(children_container.attrib)), Qt.UserRole), for child_node in children_container.xpath('*'): # Handle any explicit <Node> children if child_node.tag == 'Node': self._recurse_tree(child_node, new_proj_el, curr_item) # Repeaters are a separate case elif child_node.tag == 'Repeater': qrepeater = QStandardItem( QIcon(':/plugins/qrave_toolbar/BrowseFolder.png'), child_node.attrib['label']) qrepeater.setData( ProjectTreeData(QRaveTreeTypes.PROJECT_REPEATER_FOLDER, project=self, data=dict(children_container.attrib)), Qt.UserRole), curr_item.appendRow(qrepeater) repeat_xpath = child_node.attrib['xpath'] repeat_node = child_node.find('Node') if repeat_node is not None: for repeater_el in new_proj_el.xpath(repeat_xpath): self._recurse_tree(repeat_node, repeater_el, qrepeater) # Otherwise this is a leaf else: bl_type = bl_el.attrib['type'] if bl_type == 'polygon': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Polygon.png')) elif bl_type == 'line': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Polyline.png')) elif bl_type == 'point': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/MultiDot.png')) elif bl_type == 'raster': curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/layers/Raster.png')) else: curr_item.setIcon( QIcon(':/plugins/qrave_toolbar/RaveAddIn_16px.png')) # Couldn't find this node. Ignore it. meta = { meta.attrib['name']: meta.text for meta in new_proj_el.findall('MetaData/Meta') } new_proj_el.find('Path') layer_name = None layer_uri = os.path.join(self.project_dir, new_proj_el.find('Path').text) # If this is a geopackage it's special if new_proj_el.getparent().tag == 'Layers': layer_name = new_proj_el.find('Path').text layer_uri = os.path.join( self.project_dir, new_proj_el.getparent().getparent().find('Path').text) layer_type = bl_attr['type'] if 'type' in bl_attr else 'unknown' map_layer = QRaveMapLayer(curr_label, layer_type, layer_uri, bl_attr, meta, layer_name) curr_item.setData( ProjectTreeData(QRaveTreeTypes.LEAF, project=self, data=map_layer), Qt.UserRole) if not map_layer.exists: curr_item.setData(QBrush(Qt.red), Qt.ForegroundRole) curr_item_font = curr_item.font() curr_item_font.setItalic(True) curr_item.setFont(curr_item_font) curr_item.setToolTip('File not found: {}'.format( map_layer.layer_uri)) elif map_layer.layer_uri: curr_item.setToolTip(map_layer.layer_uri) if parent: parent.appendRow(curr_item) return curr_item
def setupUi(self, Dialog): Dialog.setObjectName("Dialog") Dialog.resize( QtCore.QSize(QtCore.QRect(0, 0, 440, 660).size()).expandedTo( Dialog.minimumSizeHint())) self.gridlayout = QGridLayout(Dialog) self.gridlayout.setObjectName("gridlayout") font = QFont() font.setPointSize(15) font.setWeight(50) font.setBold(True) self.label_2 = QLabel(Dialog) self.label_2.setFont(font) self.label_2.setTextFormat(QtCore.Qt.RichText) self.label_2.setObjectName("label_2") self.gridlayout.addWidget(self.label_2, 1, 1, 1, 2) self.textEdit = QTextEdit(Dialog) palette = QPalette() brush = QBrush(QColor(0, 0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QPalette.Active, QPalette.Base, brush) brush = QBrush(QColor(0, 0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QPalette.Inactive, QPalette.Base, brush) brush = QBrush(QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QPalette.Disabled, QPalette.Base, brush) self.textEdit.setPalette(palette) self.textEdit.setAutoFillBackground(True) self.textEdit.width = 320 self.textEdit.height = 360 self.textEdit.setFrameShape(QFrame.NoFrame) self.textEdit.setFrameShadow(QFrame.Plain) self.textEdit.setReadOnly(True) self.textEdit.setObjectName("textEdit") self.textEdit.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction) self.gridlayout.addWidget(self.textEdit, 2, 1, 5, 2) self.pushButton = QPushButton(Dialog) self.pushButton.setObjectName("pushButton") self.gridlayout.addWidget(self.pushButton, 4, 2, 1, 1) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.gridlayout.addItem(spacerItem, 3, 1, 1, 1) self.retranslateUi(Dialog) self.pushButton.clicked.connect(Dialog.reject) QtCore.QMetaObject.connectSlotsByName(Dialog)
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 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 fill_model(self, record, parent): """ Fill data in the treeview depending on the structure. It expects JSON data. The JSON data may contain LADM_COL object collections in the form: "ladm_col_table_name" : [{"id": 5, "records":{k,v pairs}}, {"id": 8, "records":{k,v pairs}}, ...] """ for key, values in record.items(): # either tuple or dict if type(values) is list: if not len(values): # Empty object parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData( 0, "{} (0)".format(DICT_PLURAL[key] if key in DICT_PLURAL else key)) kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) kv_item.setData(0, {"type": key}, Qt.UserRole) kv_item.setData( 0, QIcon(DICT_PACKAGE_ICON[DICT_TABLE_PACKAGE[key]]) if key in DICT_TABLE_PACKAGE else None, Qt.DecorationRole) continue for value in values: if type(value) is dict: if len( value ) == 2 and 'id' in value and 'attributes' in value: # We have a list of LADM_COL model objects, we deal differently with them... self.fill_collection(key, values, parent) break elif type(values) is dict: if key == 'attributes': # Dict of key-value pairs, reuse the function self.fill_model(values, parent) else: # Non-LADM object (e.g., external boundaries) parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData(0, "{}:".format(key)) self.fill_model(values, kv_item) else: # Simple key-value pair parent.insertChildren(parent.childCount(), 1, self.rootItem.columnCount()) kv_item = parent.child(parent.childCount() - 1) kv_item.setData(0, "{}: {}".format(key, values)) value_user_role = {"value": values} if key.startswith("Archivo fuente"): value_user_role.update({'url': values}) kv_item.setData(0, value_user_role, Qt.UserRole) if values is None: kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) # Additional item for a file preview if key.startswith("Archivo fuente"): if values: if values.startswith(DEFAULT_ENDPOINT_SOURCE_SERVICE ): # We want the thumbnail kv_item.insertChildren(kv_item.childCount(), 1, self.rootItem.columnCount()) kv_subitem = kv_item.child(kv_item.childCount() - 1) kv_subitem.setData(0, { 'type': 'img', 'url': values }, Qt.UserRole)
def paint(self, painter, option, widget=None): rect = self.itemRect() 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) if self.hover_over_item: color = color.darker(105) 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(QApplication.palette().color(QPalette.WindowText))) 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 _getPenAndBrush(self): """Get the pen and brush""" pen = QPen() blackBrush = QBrush(QColor("black")) whiteBrush = QBrush(QColor("white")) return pen, blackBrush, whiteBrush
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, join=Qt.RoundJoin)
def paintEvent(self, event): # based on # http://qt.gitorious.org/qt/qt/blobs/master/src/gui/widgets/qslider.cpp painter = QPainter(self) style = self.style() opt = QStyleOptionSlider() self.initStyleOption(opt) groove_rect = style.subControlRect(style.CC_Slider, opt, QStyle.SC_SliderGroove, self) handle_rect = style.subControlRect(style.CC_Slider, opt, QStyle.SC_SliderHandle, self) slider_space = style.pixelMetric(style.PM_SliderSpaceAvailable, opt) range_x1 = style.sliderPositionFromValue(self.minimum(), self.maximum(), self._low, slider_space) range_x2 = style.sliderPositionFromValue(self.minimum(), self.maximum(), self._high, slider_space) range_height = 4 groove_rect = QRectF( groove_rect.x(), handle_rect.center().y() - (range_height / 2), groove_rect.width(), range_height, ) range_rect = QRectF( groove_rect.x() + (handle_rect.width() / 2) + range_x1, handle_rect.center().y() - (range_height / 2), range_x2 - range_x1, range_height, ) if style.metaObject().className() != "QMacStyle": # Paint groove for Fusion and Windows styles cur_brush = painter.brush() cur_pen = painter.pen() painter.setBrush(QBrush(QColor(169, 169, 169))) painter.setPen(Qt.NoPen) # painter.drawRect(groove_rect) painter.drawRoundedRect(groove_rect, groove_rect.height() / 2, groove_rect.height() / 2) painter.setBrush(cur_brush) painter.setPen(cur_pen) cur_brush = painter.brush() cur_pen = painter.pen() # painter.setBrush(QBrush(QColor(18, 141, 148))) # painter.setPen(Qt.NoPen) painter.drawRect(range_rect) painter.setBrush(cur_brush) painter.setPen(cur_pen) for i, value in enumerate([self._low, self._high]): opt = QStyleOptionSlider() self.initStyleOption(opt) # Only draw the groove for the first slider so it doesn't get drawn # on top of the existing ones every time # if i == 0: # opt.subControls = QStyle.SC_SliderGroove | \ # QStyle.SC_SliderHandle # else: opt.subControls = QStyle.SC_SliderHandle if self.tickPosition() != self.NoTicks: opt.subControls |= QStyle.SC_SliderTickmarks if self.isSliderDown(): opt.state |= QStyle.State_Sunken else: opt.state |= QStyle.State_Active if self.pressed_control: opt.activeSubControls = self.pressed_control else: opt.activeSubControls = self.hover_control opt.sliderPosition = value opt.sliderValue = value style.drawComplexControl(QStyle.CC_Slider, opt, painter, self)
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
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)
def on_btnAdd_clicked(self): item = QTreeWidgetItem() item.setText(0, '0.00') item.setText(1, '0.00') item.setBackground(2, QBrush(QColor(127, 127, 127))) self.reliefClassTree.addTopLevelItem(item)
def fill_model(self, record, parent): """ Fill data in the treeview depending on the structure. It expects JSON data. The JSON data may contain LADM-COL object collections in the form: "ladm_col_table_name" : [{"id": 5, "attributes":{k,v pairs}}, {"id": 8, "attributes":{k,v pairs}}, ...] """ plural = LayerConfig.get_dict_plural(self.names) icons = LayerConfig.get_dict_package_icon() dict_table_package = LayerConfig.get_dict_table_package(self.names) for key, values in record.items(): # either tuple or dict if type(values) is list: if not len(values): # Empty object kv_item = self._create_new_item(parent) kv_item.setData( 0, "{} (0)".format(plural[key] if key in plural else key)) kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) kv_item.setData(0, {"type": key}, Qt.UserRole) kv_item.setData( 0, QIcon(icons[dict_table_package[key]]) if key in dict_table_package else None, Qt.DecorationRole) continue for value in values: if type(value) is dict: if len( value ) == 2 and 'id' in value and 'attributes' in value: # We have a list of LADM-COL model objects, we deal differently with them... self.fill_collection(key, values, parent, plural, icons) break elif type(values) is dict: if key == 'attributes': # Dict of key-value pairs, reuse the function self.fill_model(values, parent) else: # Non-LADM object (e.g., external boundaries) kv_item = self._create_new_item(parent) kv_item.setData(0, "{}:".format(key)) self.fill_model(values, kv_item) else: # Simple key-value pair kv_item = self._create_new_item(parent) kv_text = "{}: {}".format(key, values) kv_item.setData(0, kv_text) value_user_role = {"value": values} if key.startswith("Archivo fuente"): value_user_role.update({'url': values}) kv_item.setData(0, value_user_role, Qt.UserRole) if values is None: kv_item.setData(0, QBrush(Qt.lightGray), Qt.ForegroundRole) else: kv_item.setData(0, kv_text, Qt.ToolTipRole) # Additional item for a file preview if key.startswith("Archivo fuente"): if values: if values.startswith(DEFAULT_ENDPOINT_SOURCE_SERVICE ): # We want the thumbnail kv_subitem = self._create_new_item(kv_item) kv_subitem.setData(0, { 'type': 'img', 'url': values }, Qt.UserRole)
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, ModelerParameter): color = QColor(238, 242, 131) stroke = QColor(234, 226, 118) selected = QColor(116, 113, 68) elif isinstance(self.element, Algorithm): 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, Algorithm) and not self.element.active: 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, Algorithm): 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.paramsFolded: for param in self.element.algorithm.parameters: if not param.hidden: 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.outputsFolded: for i, out in enumerate(self.element.algorithm.outputs): 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)