def runTestForLayer(self, layer, testname): tempdir = tempfile.mkdtemp() layer = QgsVectorLayer(layer, 'Layer', 'ogr') QgsProject.instance().addMapLayer(layer) self.iface.mapCanvas().setExtent(layer.extent()) geom = next(layer.getFeatures()).geometry() highlight = QgsHighlight(self.iface.mapCanvas(), geom, layer) color = QColor(Qt.red) highlight.setColor(color) highlight.setWidth(2) color.setAlpha(50) highlight.setFillColor(color) highlight.show() image = QImage(QSize(400, 400), QImage.Format_ARGB32) image.fill(Qt.white) painter = QPainter() painter.begin(image) self.iface.mapCanvas().render(painter) painter.end() control_image = os.path.join(tempdir, 'highlight_{}.png'.format(testname)) image.save(control_image) checker = QgsRenderChecker() checker.setControlPathPrefix("highlight") checker.setControlName("expected_highlight_{}".format(testname)) checker.setRenderedImage(control_image) self.assertTrue(checker.compareImages("highlight_{}".format(testname))) shutil.rmtree(tempdir)
def __init__(self): QWidget.__init__(self) self.setWindowTitle(self.tr('Qdraw - Settings')) self.setFixedSize(320, 100) self.center() # default color self.color = QColor(60, 151, 255, 255) self.sld_opacity = QSlider(Qt.Horizontal, self) self.sld_opacity.setRange(0, 255) self.sld_opacity.setValue(255) self.sld_opacity.tracking = True self.sld_opacity.valueChanged.connect(self.handler_opacitySliderValue) self.lbl_opacity = QLabel(self.tr('Opacity') + ': 100%', self) self.dlg_color = QColorDialog(self) btn_chColor = QPushButton(self.tr('Change the drawing color'), self) btn_chColor.clicked.connect(self.handler_chColor) vbox = QVBoxLayout() vbox.addWidget(self.lbl_opacity) vbox.addWidget(self.sld_opacity) vbox.addWidget(btn_chColor) self.setLayout(vbox)
def __init__(self): self.iface = iface self.srs_wgs84 = QgsCoordinateReferenceSystem(4326) self.transform_decorator = QgsCoordinateTransform(self.srs_wgs84, self.srs_wgs84) self.rb = QgsRubberBand(self.iface.mapCanvas(), QGisGeometryType.Point) self.rb.setColor(QColor('magenta')) self.rb.setIconSize(12) self.features_rb = QgsRubberBand(self.iface.mapCanvas(), QGisGeometryType.Point) magenta_transp = QColor('#3388ff') magenta_transp.setAlpha(120) self.features_rb.setColor(magenta_transp) self.features_rb.setIconSize(12) self.features_rb.setWidth(2)
def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) # create composition self.mMapSettings = QgsMapSettings() self.mComposition = QgsComposition(self.mMapSettings, QgsProject.instance()) self.mComposition.setPaperSize(297, 210) self.mComposerRect1 = QgsComposerShape(20, 20, 150, 100, self.mComposition) self.mComposerRect1.setShapeType(QgsComposerShape.Rectangle) self.mComposerRect1.setBackgroundColor(QColor.fromRgb(255, 150, 0)) self.mComposition.addComposerShape(self.mComposerRect1) self.mComposerRect2 = QgsComposerShape(50, 50, 150, 100, self.mComposition) self.mComposerRect2.setShapeType(QgsComposerShape.Rectangle) self.mComposerRect2.setBackgroundColor(QColor.fromRgb(0, 100, 150)) self.mComposition.addComposerShape(self.mComposerRect2)
def renderTile(self, x, y, feedback, make_trans): """ Render one tile :param x: The x index of the current tile :param y: The y index of the current tile """ if make_trans: background_color = QColor(255, 255, 255, 0) self.image.fill(background_color.rgba()) else: background_color = QColor(255, 255, 255) self.image.fill(background_color.rgb()) painter = QPainter(self.image) self.settings.setExtent(QgsRectangle( self.extent.xMinimum() + x * self.mupp * self.tile_size, self.extent.yMaximum() - (y + 1) * self.mupp * self.tile_size, self.extent.xMinimum() + (x + 1) * self.mupp * self.tile_size, self.extent.yMaximum() - y * self.mupp * self.tile_size)) job = QgsMapRendererCustomPainterJob(self.settings, painter) job.renderSynchronously() painter.end() # Needs not to be deleted or Windows will kill it too early... tmpfile = tempfile.NamedTemporaryFile(suffix='.png', delete=False) try: self.image.save(tmpfile.name) src_ds = osgeo.gdal.Open(tmpfile.name) self.dataset.WriteRaster(x * self.tile_size, y * self.tile_size, self.tile_size, self.tile_size, src_ds.ReadRaster(0, 0, self.tile_size, self.tile_size)) except Exception as e: feedback.reportError(str(e)) finally: del src_ds tmpfile.close() os.unlink(tmpfile.name)
def __init__(self, methodName): """Run once on class initialization.""" unittest.TestCase.__init__(self, methodName) # create composition self.mComposition = QgsComposition(QgsProject.instance()) self.mComposition.setPaperSize(297, 210) self.mComposerShape = QgsComposerShape(20, 20, 150, 100, self.mComposition) self.mComposerShape.setBackgroundColor(QColor.fromRgb(255, 150, 0)) self.mComposition.addComposerShape(self.mComposerShape)
def testSingleBandPseudoColorRenderer_Exact(self): # get min and max of the band to renderer bandNo = 3 stats = self.raster_layer.dataProvider().bandStatistics(bandNo, QgsRasterBandStats.Min | QgsRasterBandStats.Max) minValue = stats.minimumValue maxValue = stats.maximumValue # create shader for the renderer shader = QgsRasterShader(minValue, maxValue) colorRampShaderFcn = QgsColorRampShader(minValue, maxValue) colorRampShaderFcn.setColorRampType(QgsColorRampShader.Exact) colorRampShaderFcn.setClassificationMode(QgsColorRampShader.Continuous) colorRampShaderFcn.setClip(True) items = [] for index in range(10): items.append(QgsColorRampShader.ColorRampItem(index, QColor('#{0:02d}{0:02d}{0:02d}'.format(index)), "{}".format(index))) colorRampShaderFcn.setColorRampItemList(items) shader.setRasterShaderFunction(colorRampShaderFcn) # create instance to test rasterRenderer = QgsSingleBandPseudoColorRenderer(self.raster_layer.dataProvider(), bandNo, shader) self.raster_layer.setRenderer(rasterRenderer) # do test dom, root = self.rendererToSld(self.raster_layer.renderer()) self.assertNoOpacity(root) self.assertChannelBand(root, 'sld:GrayChannel', '{}'.format(bandNo)) # check ColorMapEntry classes colorMap = root.elementsByTagName('sld:ColorMap') colorMap = colorMap.item(0).toElement() self.assertFalse(colorMap.isNull()) self.assertEqual(colorMap.attribute('type'), 'values') self.assertFalse(colorMap.hasAttribute('extendend')) colorMapEntries = colorMap.elementsByTagName('sld:ColorMapEntry') self.assertEqual(colorMapEntries.count(), 10) for index in range(colorMapEntries.count()): colorMapEntry = colorMapEntries.at(index).toElement() self.assertEqual(colorMapEntry.attribute('quantity'), '{}'.format(index)) self.assertEqual(colorMapEntry.attribute('label'), '{}'.format(index)) self.assertEqual(colorMapEntry.attribute('opacity'), '') self.assertEqual(colorMapEntry.attribute('color'), '#{0:02d}{0:02d}{0:02d}'.format(index)) # add check that is set ColoMap extended="true" if colormap is bigger that 255 entries # !NOTE! can't reuse previous shader => segmentation fault shader = QgsRasterShader(minValue, maxValue) colorRampShaderFcn = QgsColorRampShader(minValue, maxValue) colorRampShaderFcn.setColorRampType(QgsColorRampShader.Exact) colorRampShaderFcn.setClassificationMode(QgsColorRampShader.Continuous) colorRampShaderFcn.setClip(True) items = [] for index in range(255): items.append(QgsColorRampShader.ColorRampItem(index, QColor.fromHsv(index, 255, 255, 255), "{}".format(index))) colorRampShaderFcn.setColorRampItemList(items) shader.setRasterShaderFunction(colorRampShaderFcn) # create instance to test rasterRenderer = QgsSingleBandPseudoColorRenderer(self.raster_layer.dataProvider(), bandNo, shader)
def initGui(self): # Create action that will start plugin configuration self.action = QAction( QIcon(self.plugin_dir + "/icon.svg"), u"Distribution Map Generator...", self.iface.mainWindow()) # connect the action to the run method self.action.triggered.connect(self.run) self.dlg.ui.buttonBox.accepted.connect(self.confirm) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&Distribution Map Generator", self.action) # Set colour for output background colour chooser: self.BACKGROUND_COLOUR = QColor(192,192,255) self.dlg.ui.frmColour.setStyleSheet("QWidget { background-color: %s }" % self.BACKGROUND_COLOUR.name())
def envelope2layer(self, envelope): """Transform metadata envelope into a QGIS layer.""" # layer md_lyr = QgsVectorLayer("Polygon?crs=epsg:4326", "Metadata envelope", "memory") md_lyr.setLayerTransparency(75) symbols = md_lyr.rendererV2().symbols() symbol = symbols[0] symbol.setColor(QColor.fromRgb(255,20,147)) if envelope.get("type") == "Polygon": # parse coordinates coords = envelope.get("coordinates")[0] poly_pts = [QgsPoint(round(i[0], 3), round(i[1], 3)) for i in coords] # add geometry to layer poly = QgsFeature() poly.setGeometry(QgsGeometry.fromPolygon([poly_pts])) md_lyr.dataProvider().addFeatures([poly]) md_lyr.updateExtents() elif envelope.get("type") == "MultiPolygon": coords = envelope.get("bbox") bbox = QgsRectangle(round(coords[0], 3), round(coords[1], 3), round(coords[2], 3), round(coords[3], 3),) poly = QgsFeature() poly.setGeometry(QgsGeometry.fromWkt(bbox.asWktPolygon())) md_lyr.dataProvider().addFeatures([poly]) md_lyr.updateExtents() elif envelope.get("type") == "Point": return md_lyr else: pass # method ending return md_lyr
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 setLexers(self): self.lexer = QsciLexerPython() loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace") fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int) font = QFont(loadFont) font.setFixedPitch(True) font.setPointSize(fontSize) font.setStyleHint(QFont.TypeWriter) font.setStretch(QFont.SemiCondensed) font.setLetterSpacing(QFont.PercentageSpacing, 87.0) font.setBold(False) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black)))) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1) self.lexer.setColor( QColor( self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5) self.lexer.setColor( QColor( self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8) self.lexer.setColor( QColor( self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9) self.lexer.setColor( QColor( self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12) self.lexer.setColor( QColor( self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4) self.lexer.setColor( QColor( self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) for style in range(0, 33): paperColor = QColor( self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer)
def testQgsGradientFillSymbolLayer(self): """Test setting and getting QgsGradientFillSymbolLayer properties. """ mGradientLayer = QgsGradientFillSymbolLayer() mExpectedValue = type(QgsGradientFillSymbolLayer()) mValue = type(mGradientLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayer.Radial mGradientLayer.setGradientType(mExpectedValue) mValue = mGradientLayer.gradientType() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayer.ColorRamp mGradientLayer.setGradientColorType(mExpectedValue) mValue = mGradientLayer.gradientColorType() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QColor('#55aaff') mGradientLayer.setColor2(mExpectedValue) mValue = mGradientLayer.color2() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayer.Viewport mGradientLayer.setCoordinateMode(mExpectedValue) mValue = mGradientLayer.coordinateMode() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsGradientFillSymbolLayer.Reflect mGradientLayer.setGradientSpread(mExpectedValue) mValue = mGradientLayer.gradientSpread() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(0.5, 0.8) mGradientLayer.setReferencePoint1(mExpectedValue) mValue = mGradientLayer.referencePoint1() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mGradientLayer.setReferencePoint1IsCentroid(mExpectedValue) mValue = mGradientLayer.referencePoint1IsCentroid() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(0.2, 0.4) mGradientLayer.setReferencePoint2(mExpectedValue) mValue = mGradientLayer.referencePoint2() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = True mGradientLayer.setReferencePoint2IsCentroid(mExpectedValue) mValue = mGradientLayer.referencePoint2IsCentroid() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 90 mGradientLayer.setAngle(mExpectedValue) mValue = mGradientLayer.angle() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QPointF(10, 20) mGradientLayer.setOffset(mExpectedValue) mValue = mGradientLayer.offset() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = QgsUnitTypes.RenderMapUnits mGradientLayer.setOffsetUnit(mExpectedValue) mValue = mGradientLayer.offsetUnit() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def testPaletted(self): """ test paletted raster renderer with raster with color table""" path = os.path.join(unitTestDataPath('raster'), 'with_color_table.tif') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) self.assertTrue(layer.isValid(), 'Raster not loaded: {}'.format(path)) renderer = QgsPalettedRasterRenderer(layer.dataProvider(), 1, [QgsPalettedRasterRenderer.Class(1, QColor(0, 255, 0), 'class 2'), QgsPalettedRasterRenderer.Class(3, QColor(255, 0, 0), 'class 1')]) self.assertEqual(renderer.nColors(), 2) self.assertEqual(renderer.usesBands(), [1]) # test labels self.assertEqual(renderer.label(1), 'class 2') self.assertEqual(renderer.label(3), 'class 1') self.assertFalse(renderer.label(101)) # test legend symbology - should be sorted by value legend = renderer.legendSymbologyItems() self.assertEqual(legend[0][0], 'class 2') self.assertEqual(legend[1][0], 'class 1') self.assertEqual(legend[0][1].name(), '#00ff00') self.assertEqual(legend[1][1].name(), '#ff0000') # test retrieving classes classes = renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'class 1') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') # test set label # bad index renderer.setLabel(1212, 'bad') renderer.setLabel(3, 'new class') self.assertEqual(renderer.label(3), 'new class') # color ramp r = QgsLimitedRandomColorRamp(5) renderer.setSourceColorRamp(r) self.assertEqual(renderer.sourceColorRamp().type(), 'random') self.assertEqual(renderer.sourceColorRamp().count(), 5) # clone new_renderer = renderer.clone() classes = new_renderer.classes() self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(new_renderer.sourceColorRamp().type(), 'random') self.assertEqual(new_renderer.sourceColorRamp().count(), 5) # write to xml and read doc = QDomDocument('testdoc') elem = doc.createElement('qgis') renderer.writeXml(doc, elem) restored = QgsPalettedRasterRenderer.create(elem.firstChild().toElement(), layer.dataProvider()) self.assertTrue(restored) self.assertEqual(restored.usesBands(), [1]) classes = restored.classes() self.assertTrue(classes) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[1].value, 3) self.assertEqual(classes[0].label, 'class 2') self.assertEqual(classes[1].label, 'new class') self.assertEqual(classes[0].color.name(), '#00ff00') self.assertEqual(classes[1].color.name(), '#ff0000') self.assertEqual(restored.sourceColorRamp().type(), 'random') self.assertEqual(restored.sourceColorRamp().count(), 5) # render test layer.setRenderer(renderer) ms = QgsMapSettings() ms.setLayers([layer]) ms.setExtent(layer.extent()) checker = QgsRenderChecker() checker.setControlName("expected_paletted_renderer") checker.setMapSettings(ms) self.assertTrue(checker.runTest("expected_paletted_renderer"), "Paletted rendering test failed")
def runAlgorithm(self): self.feedback = self.createFeedback() self.context = dataobjects.createContext(self.feedback) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: parameters = self.getParameterValues() if checkCRS and not self.algorithm().validateInputCrs( parameters, self.context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Parameters do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.algorithm().checkParameterValues( parameters, self.context) if not ok: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.runButton().setEnabled(False) self.cancelButton().setEnabled(False) buttons = self.mainWidget().iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.clearProgress() self.setProgressText( QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…')) self.setInfo(QCoreApplication.translate( 'AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format( self.algorithm().displayName()), escapeHtml=False) self.feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.algorithm( ).parameterDefinition(k).valueAsPythonString(v, self.context)) self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') self.feedback.pushInfo('') start_time = time.time() if self.iterateParam: # Make sure the Log tab is visible before executing the algorithm try: self.showLog() self.repaint() except: pass self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback): self.feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) self.cancelButton().setEnabled(False) self.finish(True, parameters, self.context, self.feedback) else: self.cancelButton().setEnabled(False) self.resetGui() else: command = self.algorithm().asPythonCommand( parameters, self.context) if command: ProcessingLog.addToLog(command) QgsGui.instance().processingRecentAlgorithmLog().push( self.algorithm().id()) self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: self.feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) self.feedback.pushInfo(self.tr('Results:')) self.feedback.pushCommandInfo(pformat(results)) else: self.feedback.reportError( self.tr('Execution failed after {0:0.2f} seconds'). format(time.time() - start_time)) self.feedback.pushInfo('') if self.feedback_dialog is not None: self.feedback_dialog.close() self.feedback_dialog.deleteLater() self.feedback_dialog = None self.cancelButton().setEnabled(False) if not self.in_place: self.finish(ok, results, self.context, self.feedback) elif ok: self.close() self.feedback = None self.context = None if not self.in_place and not ( self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading): # Make sure the Log tab is visible before executing the algorithm self.showLog() task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback) task.executed.connect(on_complete) self.setCurrentTask(task) else: self.proxy_progress = QgsProxyProgressTask( QCoreApplication.translate( "AlgorithmDialog", "Executing “{}”").format( self.algorithm().displayName())) QgsApplication.taskManager().addTask(self.proxy_progress) self.feedback.progressChanged.connect( self.proxy_progress.setProxyProgress) self.feedback_dialog = self.createProgressDialog() self.feedback_dialog.show() if self.in_place: ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback) else: ok, results = execute(self.algorithm(), parameters, self.context, self.feedback) self.feedback.progressChanged.disconnect() self.proxy_progress.finalize(ok) on_complete(ok, results) except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox().accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage( "", self.tr("Wrong or missing parameter value: {0}").format( e.parameter.description()), level=Qgis.Warning, duration=5)
class TileSet(): """ A set of tiles """ def __init__(self, map_theme, layer, extent, tile_size, mupp, output, make_trans, map_settings, project): """ :param map_theme: :param extent: :param layer: :param tile_size: :param mupp: :param output: :param map_settings: Map canvas map settings used for some fallback values and CRS """ self.extent = extent self.mupp = mupp self.tile_size = tile_size driver = self.getDriverForFile(output) if not driver: raise QgsProcessingException( u'Could not load GDAL driver for file {}'.format(output)) crs = map_settings.destinationCrs() self.x_tile_count = math.ceil(extent.width() / mupp / tile_size) self.y_tile_count = math.ceil(extent.height() / mupp / tile_size) xsize = self.x_tile_count * tile_size ysize = self.y_tile_count * tile_size if make_trans: no_bands = 4 else: no_bands = 3 self.dataset = driver.Create(output, xsize, ysize, no_bands) self.dataset.SetProjection(str(crs.toWkt())) self.dataset.SetGeoTransform( [extent.xMinimum(), mupp, 0, extent.yMaximum(), 0, -mupp]) self.image = QImage(QSize(tile_size, tile_size), QImage.Format_ARGB32) self.settings = QgsMapSettings() self.settings.setOutputDpi(self.image.logicalDpiX()) self.settings.setOutputImageFormat(QImage.Format_ARGB32) self.settings.setDestinationCrs(crs) self.settings.setOutputSize(self.image.size()) self.settings.setFlag(QgsMapSettings.Antialiasing, True) self.settings.setFlag(QgsMapSettings.RenderMapTile, True) self.settings.setFlag(QgsMapSettings.UseAdvancedEffects, True) r = project.readNumEntry('Gui', '/CanvasColorRedPart', 255)[0] g = project.readNumEntry('Gui', '/CanvasColorGreenPart', 255)[0] b = project.readNumEntry('Gui', '/CanvasColorBluePart', 255)[0] if make_trans: self.bgColor = QColor(r, g, b, 0) else: self.bgColor = QColor(r, g, b) self.settings.setBackgroundColor(self.bgColor) if QgsProject.instance().mapThemeCollection().hasMapTheme(map_theme): self.settings.setLayers( QgsProject.instance().mapThemeCollection( ).mapThemeVisibleLayers( map_theme)) self.settings.setLayerStyleOverrides( QgsProject.instance().mapThemeCollection( ).mapThemeStyleOverrides( map_theme)) elif layer: self.settings.setLayers([layer]) else: self.settings.setLayers(map_settings.layers()) def render(self, feedback, make_trans): for x in range(self.x_tile_count): for y in range(self.y_tile_count): if feedback.isCanceled(): return cur_tile = x * self.y_tile_count + y num_tiles = self.x_tile_count * self.y_tile_count self.renderTile(x, y, feedback, make_trans) feedback.setProgress(int((cur_tile / num_tiles) * 100)) def renderTile(self, x, y, feedback, make_trans): """ Render one tile :param x: The x index of the current tile :param y: The y index of the current tile """ if make_trans: self.image.fill(self.bgColor.rgba()) else: self.image.fill(self.bgColor.rgb()) painter = QPainter(self.image) self.settings.setExtent(QgsRectangle( self.extent.xMinimum() + x * self.mupp * self.tile_size, self.extent.yMaximum() - (y + 1) * self.mupp * self.tile_size, self.extent.xMinimum() + (x + 1) * self.mupp * self.tile_size, self.extent.yMaximum() - y * self.mupp * self.tile_size)) job = QgsMapRendererCustomPainterJob(self.settings, painter) job.renderSynchronously() painter.end() # Needs not to be deleted or Windows will kill it too early... tmpfile = tempfile.NamedTemporaryFile(suffix='.png', delete=False) try: self.image.save(tmpfile.name) src_ds = osgeo.gdal.Open(tmpfile.name) self.dataset.WriteRaster(x * self.tile_size, y * self.tile_size, self.tile_size, self.tile_size, src_ds.ReadRaster(0, 0, self.tile_size, self.tile_size)) except Exception as e: feedback.reportError(str(e)) finally: del src_ds tmpfile.close() os.unlink(tmpfile.name) def getDriverForFile(self, filename): """ Get the GDAL driver for a filename, based on its extension. (.gpkg, .mbtiles...) """ _, extension = os.path.splitext(filename) # If no extension is set, use .tif as default if extension == '': extension = '.tif' driver_name = QgsRasterFileWriter.driverForExtension(extension[1:]) return osgeo.gdal.GetDriverByName(driver_name)
def testQgsColorBrewerColorRampV2(self): # test color brewer color ramps r = QgsColorBrewerColorRamp('OrRd', 6) self.assertEqual(r.type(), 'colorbrewer') self.assertEqual(r.schemeName(), 'OrRd') self.assertEqual(r.count(), 6) self.assertEqual(r.value(0), 0) self.assertEqual(r.value(1), 0.2) self.assertEqual(r.value(2), 0.4) self.assertEqual(r.value(3), 0.6) self.assertEqual(r.value(4), 0.8) self.assertEqual(r.value(5), 1) self.assertTrue(not r.color(-1).isValid()) self.assertTrue(not r.color(6).isValid()) self.assertEqual(r.color(0), QColor(254, 240, 217)) self.assertEqual(r.color(0.2), QColor(253, 212, 158)) self.assertEqual(r.color(0.4), QColor(253, 187, 132)) self.assertEqual(r.color(0.6), QColor(252, 141, 89)) self.assertEqual(r.color(0.8), QColor(227, 74, 51)) self.assertEqual(r.color(1.0), QColor(179, 0, 0)) # try using an invalid scheme name bad = QgsColorBrewerColorRamp('badscheme', 6) self.assertFalse(bad.color(0).isValid()) self.assertEqual(bad.value(1), 0) # test creating from properties props = r.properties() fromProps = QgsColorBrewerColorRamp.create(props) self.assertEqual(fromProps.type(), 'colorbrewer') self.assertEqual(fromProps.schemeName(), 'OrRd') self.assertEqual(fromProps.count(), 6) self.assertEqual(fromProps.color(0), QColor(254, 240, 217)) self.assertEqual(fromProps.color(0.2), QColor(253, 212, 158)) self.assertEqual(fromProps.color(0.4), QColor(253, 187, 132)) self.assertEqual(fromProps.color(0.6), QColor(252, 141, 89)) self.assertEqual(fromProps.color(0.8), QColor(227, 74, 51)) self.assertEqual(fromProps.color(1.0), QColor(179, 0, 0)) # test cloning ramp cloned = r.clone() self.assertEqual(cloned.type(), 'colorbrewer') self.assertEqual(cloned.schemeName(), 'OrRd') self.assertEqual(cloned.count(), 6) self.assertEqual(cloned.color(0), QColor(254, 240, 217)) self.assertEqual(cloned.color(0.2), QColor(253, 212, 158)) self.assertEqual(cloned.color(0.4), QColor(253, 187, 132)) self.assertEqual(cloned.color(0.6), QColor(252, 141, 89)) self.assertEqual(cloned.color(0.8), QColor(227, 74, 51)) self.assertEqual(cloned.color(1.0), QColor(179, 0, 0)) # set scheme name r.setSchemeName('Reds') self.assertEqual(r.schemeName(), 'Reds') self.assertEqual(r.count(), 6) self.assertEqual(r.color(0), QColor(254, 229, 217)) self.assertEqual(r.color(0.2), QColor(252, 187, 161)) self.assertEqual(r.color(0.4), QColor(252, 146, 114)) self.assertEqual(r.color(0.6), QColor(251, 106, 74)) self.assertEqual(r.color(0.8), QColor(222, 45, 38)) self.assertEqual(r.color(1.0), QColor(165, 15, 21)) # test invert function r.invert() self.assertEqual(r.color(0), QColor(165, 15, 21)) self.assertEqual(r.color(0.2), QColor(222, 45, 38)) self.assertEqual(r.color(1), QColor(254, 229, 217)) r.invert() # set colors r.setColors(3) self.assertEqual(r.colors(), 3) self.assertEqual(r.count(), 3) self.assertEqual(r.color(0), QColor(254, 224, 210)) self.assertEqual(r.color(0.5), QColor(252, 146, 114)) self.assertEqual(r.color(1.0), QColor(222, 45, 38)) # test static members names = QgsColorBrewerColorRamp.listSchemeNames() self.assertTrue('Reds' in names and 'OrRd' in names) self.assertEqual( len(QgsColorBrewerColorRamp.listSchemeVariants('bad scheme')), 0) variants = QgsColorBrewerColorRamp.listSchemeVariants('Reds') self.assertEqual(variants, [3, 4, 5, 6, 7, 8, 9])
def add_layers(self):#not tested and not ready, must fix basic styles (preferrably colors based on some definition dicitonary MyGroup = self.root.insertGroup(0, "stratigraphy_layers_for_qgis2threejs")#verify this is inserted at top canvas = self.iface.mapCanvas() list_with_all_strat_layer = [] for key in self.strat_layers_dict: list_with_all_strat_layer.append(key) #print list_with_all_strat_layer#debug list_with_all_strat_layer.append('strat_obs_p_for_qgsi2threejs') colors = [] layer_list = [] utils.add_layers_to_list(layer_list, list_with_all_strat_layer, geometrycolumn='geometry', dbconnection=self.dbconnection) for strat_layer_view in list_with_all_strat_layer: try: supplied_color = self.symbolcolors_dict[strat_layer_view] except KeyError: color = None else: try: # matplotlib 2 color = mpl.colors.to_rgbsupplied_color() except AttributeError: try: # matplotlib 1 converter = mpl.colors.ColorConverter() color = converter.to_rgb(supplied_color) color = [x * 255 for x in color] except Exception as e: utils.MessagebarAndLog.warning( bar_msg=ru(QCoreApplication.translate('PrepareForQgis2Threejs', 'Setting color from dict failed')), log_msg=ru(QCoreApplication.translate('PrepareForQgis2Threejs', 'Error msg %s'))%str(e)) color = None colors.append(color) for idx, layer in enumerate(layer_list):#now loop over all the layers, add them to canvas and set colors if not layer.isValid(): try: print(layer.name() + ' is not valid layer') except: pass pass else: # TODO: Made this a comment, but there might be some hidden feature thats still needed! #map_canvas_layer_list.append(QgsMapCanvasLayer(layer)) #now try to load the style file stylefile = os.path.join(os.sep,os.path.dirname(__file__),"..","definitions",layer.name() + ".qml") try: layer.loadNamedStyle(stylefile) except: try: print("Loading stylefile %s failed."%stylefile) except: pass color = colors[idx] if color: current_symbol = layer.renderer().symbol() current_symbol.setColor(QColor.fromRgb(color[0], color[1], color[2])) QgsProject.instance().addMapLayers([layer],False) MyGroup.insertLayer(0,layer) #finally refresh canvas canvas.refresh()
def setTitleColor(self, color): self.titleColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.titleColor ) self.titleColorBtn.setIcon( QIcon(pixmap) )
class QdrawSettings(QWidget): """Window used to change settings (transparency/color)""" settingsChanged = pyqtSignal() def __init__(self): QWidget.__init__(self) self.setWindowTitle(self.tr('Qdraw - Settings')) self.setFixedSize(320, 100) self.center() # default color self.color = QColor(60, 151, 255, 255) self.sld_opacity = QSlider(Qt.Horizontal, self) self.sld_opacity.setRange(0, 255) self.sld_opacity.setValue(255) self.sld_opacity.tracking = True self.sld_opacity.valueChanged.connect(self.handler_opacitySliderValue) self.lbl_opacity = QLabel(self.tr('Opacity') + ': 100%', self) self.dlg_color = QColorDialog(self) btn_chColor = QPushButton(self.tr('Change the drawing color'), self) btn_chColor.clicked.connect(self.handler_chColor) vbox = QVBoxLayout() vbox.addWidget(self.lbl_opacity) vbox.addWidget(self.sld_opacity) vbox.addWidget(btn_chColor) self.setLayout(vbox) def tr(self, message): return QCoreApplication.translate('Qdraw', message) def handler_opacitySliderValue(self, val): self.color.setAlpha(val) self.lbl_opacity.setText( self.tr('Opacity')+': '+str(int((float(val) / 255) * 100))+'%') self.settingsChanged.emit() def handler_chColor(self): color = self.dlg_color.getColor(self.color) if color.isValid(): color.setAlpha(self.color.alpha()) self.color = color self.settingsChanged.emit() self.close() def getColor(self): return self.color def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) def closeEvent(self, e): self.clear() e.accept() def clear(self): return
def setPointsReplicasColor(self, color): self.pointsReplicasColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.pointsReplicasColor ) self.pointsReplicasColorBtn.setIcon( QIcon(pixmap) )
def createColorRamp(): return QgsGradientColorRamp(QColor(255, 0, 0), QColor(0, 0, 255))
def accept(self): self.settings.setValue("/Processing/dialogBase", self.saveGeometry()) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: self.setParamValues() if checkCRS and not self.alg.checkInputCRS(): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) if checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question( self, self.tr("Extent CRS"), self. tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) self.setInfo( self.tr('<b>Algorithm %s starting...</b>') % self.alg.name) if self.iterateParam: if runalgIterating(self.alg, self.iterateParam, self.feedback): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() else: command = self.alg.getAsCommand() if command: ProcessingLog.addToLog(ProcessingLog.LOG_ALGORITHM, command) if runalg(self.alg, self.feedback): self.finish() else: QApplication.restoreOverrideCursor() self.resetGUI() except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.bar.clearWidgets() self.bar.pushMessage("", "Wrong or missing parameter value: %s" % e.parameter.description, level=QgsMessageBar.WARNING, duration=5)
def testSizeMapUnitScale(self): # test sizeMapUnitScale and setSizeMapUnitScale # create a marker symbol with a single layer markerSymbol = QgsMarkerSymbol() markerSymbol.deleteSymbolLayer(0) markerSymbol.appendSymbolLayer(QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0), strokeColor=QColor(0, 255, 0), size=10)) markerSymbol.symbolLayer(0).setSizeMapUnitScale(QgsMapUnitScale(10000, 20000)) self.assertEqual(markerSymbol.sizeMapUnitScale(), QgsMapUnitScale(10000, 20000)) markerSymbol.setSizeMapUnitScale(QgsMapUnitScale(1000, 2000)) self.assertEqual(markerSymbol.sizeMapUnitScale(), QgsMapUnitScale(1000, 2000)) self.assertEqual(markerSymbol.symbolLayer(0).sizeMapUnitScale(), QgsMapUnitScale(1000, 2000)) # add additional layers markerSymbol.appendSymbolLayer(QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0), strokeColor=QColor(0, 255, 0), size=10)) markerSymbol.appendSymbolLayer(QgsSimpleMarkerSymbolLayer(QgsSimpleMarkerSymbolLayerBase.Star, color=QColor(255, 0, 0), strokeColor=QColor(0, 255, 0), size=30)) # should take first layer's map unit scale self.assertEqual(markerSymbol.sizeMapUnitScale(), QgsMapUnitScale(1000, 2000)) markerSymbol.setSizeMapUnitScale(QgsMapUnitScale(3000, 4000)) self.assertEqual(markerSymbol.sizeMapUnitScale(), QgsMapUnitScale(3000, 4000)) # all layers should have size unit set self.assertEqual(markerSymbol.symbolLayer(0).sizeMapUnitScale(), QgsMapUnitScale(3000, 4000)) self.assertEqual(markerSymbol.symbolLayer(1).sizeMapUnitScale(), QgsMapUnitScale(3000, 4000)) self.assertEqual(markerSymbol.symbolLayer(2).sizeMapUnitScale(), QgsMapUnitScale(3000, 4000))
def testQgsVectorGradientRampV2(self): # test QgsGradientStop stop = QgsGradientStop(0.9, QColor(200, 150, 100)) self.assertEqual(stop.offset, 0.9) self.assertEqual(stop.color, QColor(200, 150, 100)) self.assertEqual(QgsGradientStop(0.1, QColor(180, 20, 30)), QgsGradientStop(0.1, QColor(180, 20, 30))) self.assertNotEqual(QgsGradientStop(0.1, QColor(180, 20, 30)), QgsGradientStop(0.2, QColor(180, 20, 30))) self.assertNotEqual(QgsGradientStop(0.1, QColor(180, 20, 30)), QgsGradientStop(0.1, QColor(180, 40, 30))) # test gradient with only start/end color r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200)) self.assertEqual(r.type(), 'gradient') self.assertEqual(r.color1(), QColor(200, 0, 0, 100)) self.assertEqual(r.color2(), QColor(0, 200, 0, 200)) self.assertEqual(r.isDiscrete(), False) self.assertEqual(len(r.stops()), 0) self.assertEqual(r.count(), 2) self.assertEqual(r.value(0), 0.0) self.assertEqual(r.value(1), 1.0) self.assertEqual(r.color(0), QColor(200, 0, 0, 100)) self.assertEqual(r.color(1), QColor(0, 200, 0, 200)) self.assertEqual(r.color(0.5), QColor(100, 100, 0, 150)) # test gradient with stops r = QgsGradientColorRamp(QColor(200, 0, 0), QColor(0, 200, 0), False, [ QgsGradientStop(0.1, QColor(180, 20, 40)), QgsGradientStop(0.9, QColor(40, 60, 100)) ]) self.assertEqual(r.color1(), QColor(200, 0, 0)) self.assertEqual(r.color2(), QColor(0, 200, 0)) self.assertEqual(r.isDiscrete(), False) self.assertEqual(len(r.stops()), 2) self.assertEqual(r.count(), 4) self.assertEqual(r.value(0), 0.0) self.assertEqual(r.value(1), 0.1) self.assertEqual(r.value(2), 0.9) self.assertEqual(r.value(3), 1.0) self.assertEqual(r.color(0), QColor(200, 0, 0)) self.assertEqual(r.color(0.05), QColor(190, 10, 20)) self.assertEqual(r.color(0.1), QColor(180, 20, 40)) self.assertEqual(r.color(0.5), QColor(110, 40, 70)) self.assertEqual(r.color(0.9), QColor(40, 60, 100)) self.assertEqual(r.color(0.95), QColor(20, 130, 50)) self.assertEqual(r.color(1), QColor(0, 200, 0)) # test setters r.setColor1(QColor(0, 0, 200)) self.assertEqual(r.color1(), QColor(0, 0, 200)) self.assertEqual(r.color(0), QColor(0, 0, 200)) r.setColor2(QColor(0, 0, 100)) self.assertEqual(r.color2(), QColor(0, 0, 100)) self.assertEqual(r.color(1.0), QColor(0, 0, 100)) r.setStops([QgsGradientStop(0.4, QColor(100, 100, 40))]) s = r.stops() self.assertEqual(len(s), 1) self.assertEqual(s[0].offset, 0.4) self.assertEqual(s[0].color, QColor(100, 100, 40)) # test info r.setInfo({'key1': 'val1', 'key2': 'val2'}) self.assertEqual(r.info()['key1'], 'val1') self.assertEqual(r.info()['key2'], 'val2') # test creating from properties props = r.properties() fromProps = QgsGradientColorRamp.create(props) self.assertEqual(fromProps.color1(), QColor(0, 0, 200)) self.assertEqual(fromProps.color2(), QColor(0, 0, 100)) s = fromProps.stops() self.assertEqual(len(s), 1) self.assertEqual(s[0].offset, 0.4) c = QColor(s[0].color) self.assertEqual(c, QColor(100, 100, 40)) self.assertEqual(fromProps.info()['key1'], 'val1') self.assertEqual(fromProps.info()['key2'], 'val2') self.assertEqual(fromProps.isDiscrete(), False) # test cloning ramp cloned = r.clone() self.assertEqual(cloned.color1(), QColor(0, 0, 200)) self.assertEqual(cloned.color2(), QColor(0, 0, 100)) s = cloned.stops() self.assertEqual(len(s), 1) self.assertEqual(s[0].offset, 0.4) c = QColor(s[0].color) self.assertEqual(c, QColor(100, 100, 40)) self.assertEqual(cloned.info()['key1'], 'val1') self.assertEqual(cloned.info()['key2'], 'val2') self.assertEqual(cloned.isDiscrete(), False) # test discrete ramps # first with no stops d = QgsGradientColorRamp(QColor(200, 0, 0), QColor(0, 200, 0), True) self.assertEqual(d.isDiscrete(), True) self.assertEqual(d.color(0), QColor(200, 0, 0)) self.assertEqual(d.color(0.5), QColor(200, 0, 0)) self.assertEqual(d.color(1), QColor(0, 200, 0)) # then with stops d = QgsGradientColorRamp(QColor(200, 0, 0), QColor(0, 200, 0), True, [ QgsGradientStop(0.1, QColor(180, 20, 40)), QgsGradientStop(0.9, QColor(40, 60, 100)) ]) self.assertEqual(d.isDiscrete(), True) self.assertEqual(d.color(0), QColor(200, 0, 0)) self.assertEqual(d.color(0.05), QColor(200, 0, 0)) self.assertEqual(d.color(0.1), QColor(180, 20, 40)) self.assertEqual(d.color(0.5), QColor(180, 20, 40)) self.assertEqual(d.color(0.9), QColor(40, 60, 100)) self.assertEqual(d.color(0.95), QColor(40, 60, 100)) self.assertEqual(d.color(1), QColor(0, 200, 0)) # to gradient g = QGradient() r = QgsGradientColorRamp(QColor(200, 0, 0), QColor(0, 200, 0), False, [ QgsGradientStop(0.1, QColor(180, 20, 40)), QgsGradientStop(0.9, QColor(40, 60, 100)) ]) r.addStopsToGradient(g, 0.5) self.assertEqual(len(g.stops()), 4) self.assertEqual(g.stops()[0], (0.0, QColor(200, 0, 0, 127))) self.assertEqual(g.stops()[1], (0.1, QColor(180, 20, 40, 127))) self.assertEqual(g.stops()[2], (0.9, QColor(40, 60, 100, 127))) self.assertEqual(g.stops()[3], (1.0, QColor(0, 200, 0, 127))) # test that stops are ordered when setting them # first add some out-of-order stops r.setStops([ QgsGradientStop(0.4, QColor(100, 100, 40)), QgsGradientStop(0.2, QColor(200, 200, 80)), QgsGradientStop(0.8, QColor(50, 20, 10)), QgsGradientStop(0.6, QColor(10, 10, 4)) ]) s = r.stops() self.assertEqual(len(s), 4) self.assertEqual(s[0].offset, 0.2) self.assertEqual(s[0].color, QColor(200, 200, 80)) self.assertEqual(s[1].offset, 0.4) self.assertEqual(s[1].color, QColor(100, 100, 40)) self.assertEqual(s[2].offset, 0.6) self.assertEqual(s[2].color, QColor(10, 10, 4)) self.assertEqual(s[3].offset, 0.8) self.assertEqual(s[3].color, QColor(50, 20, 10)) # test continuous invert function r.invert() self.assertEqual(r.color(0), QColor(0, 200, 0)) self.assertEqual(r.color(1), QColor(200, 0, 0)) self.assertEqual(r.color(0.2), QColor(50, 20, 10)) # test discrete invert function r = QgsGradientColorRamp(QColor(255, 255, 255), QColor( 0, 0, 0), True, [ QgsGradientStop(0.33, QColor(128, 128, 128)), QgsGradientStop(0.66, QColor(0, 0, 0)) ]) self.assertEqual(r.color(0.2), QColor(255, 255, 255)) self.assertEqual(r.color(0.5), QColor(128, 128, 128)) self.assertEqual(r.color(0.8), QColor(0, 0, 0)) r.invert() self.assertEqual(r.color(0.2), QColor(0, 0, 0)) self.assertEqual(r.color(0.5), QColor(128, 128, 128)) self.assertEqual(r.color(0.8), QColor(255, 255, 255))
def initLexer(self): settings = QgsSettings() self.lexer = QsciLexerPython() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) loadFont = settings.value("pythonConsole/fontfamilytextEditor") if loadFont: font.setFamily(loadFont) fontSize = settings.value("pythonConsole/fontsizeEditor", type=int) if fontSize: font.setPointSize(fontSize) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR)))) self.lexer.setColor( QColor( settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR))), 1) self.lexer.setColor( QColor( settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR))), 2) self.lexer.setColor( QColor( settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR))), 5) self.lexer.setColor( QColor( settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR))), 8) self.lexer.setColor( QColor( settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR))), 9) self.lexer.setColor( QColor( settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR))), 15) self.lexer.setColor( QColor( settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR))), 12) self.lexer.setColor( QColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))), 4) self.lexer.setColor( QColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))), 3) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7) self.lexer.setColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13) self.lexer.setFont(font, 1) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.lexer.setFont(font, QsciLexerPython.UnclosedString) for style in range(0, 33): paperColor = QColor( settings.value("pythonConsole/paperBackgroundColorEditor", QColor(self.BACKGROUND_COLOR))) self.lexer.setPaper(paperColor, style) self.api = QsciAPIs(self.lexer) useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
class GraphSettings_Dlg(QDialog, Ui_Dialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.titleBoldBtn.hide() self.titleItalicBtn.hide() self.labelsBoldBtn.hide() self.labelsItalicBtn.hide() # remove fonts matplotlib doesn't load for index in range(self.titleFontCombo.count()-1, -1, -1): found = False family = unicode( self.titleFontCombo.itemText( index ) ) try: props = self.findFont( {'family':family} ) if family == props['family']: found = True except Exception: pass if not found: self.titleFontCombo.removeItem( index ) self.labelsFontCombo.removeItem( index ) self.initProps() self.titleColorBtn.clicked.connect(self.chooseTitleColor) self.labelsColorBtn.clicked.connect(self.chooseLabelsColor) self.pointsColorBtn.clicked.connect(self.choosePointsColor) self.pointsReplicasColorBtn.clicked.connect(self.choosePointsReplicasColor) self.linesColorBtn.clicked.connect(self.chooseLinesColor) self.linesThrendColorBtn.clicked.connect(self.chooseLinesThrendColor) def choosePointsColor(self): dlg = QColorDialog(self.pointsColor, self) if dlg.exec_(): self.setPointsColor( dlg.selectedColor() ) dlg.deleteLater() def setPointsColor(self, color): self.pointsColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.pointsColor ) self.pointsColorBtn.setIcon( QIcon(pixmap) ) def pointsProps(self): props = { 'marker' : 's', 'color' : self.pointsColor.name() } return props def setPointsProps(self, props): self.setPointsColor( props.get('color', 'black') ) def choosePointsReplicasColor(self): dlg = QColorDialog(self.pointsReplicasColor, self) if dlg.exec_(): self.setPointsReplicasColor( dlg.selectedColor() ) dlg.deleteLater() def setPointsReplicasColor(self, color): self.pointsReplicasColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.pointsReplicasColor ) self.pointsReplicasColorBtn.setIcon( QIcon(pixmap) ) def pointsReplicasProps(self): props = { 'marker' : 's', 'color' : self.pointsReplicasColor.name(), } return props def setPointsReplicasProps(self, props): self.setPointsReplicasColor( props.get('color', 'blue') ) def chooseLinesColor(self): dlg = QColorDialog(self.linesColor, self) if dlg.exec_(): self.setLinesColor( dlg.selectedColor() ) dlg.deleteLater() def setLinesColor(self, color): self.linesColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.linesColor ) self.linesColorBtn.setIcon( QIcon(pixmap) ) def linesProps(self): props = { 'color' : self.linesColor.name() } return props def setLinesProps(self, props): self.setLinesColor( props.get('color', 'black') ) def chooseLinesThrendColor(self): dlg = QColorDialog(self.linesThrendColor, self) if dlg.exec_(): self.setLinesThrendColor( dlg.selectedColor() ) dlg.deleteLater() def setLinesThrendColor(self, color): self.linesThrendColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.linesThrendColor ) self.linesThrendColorBtn.setIcon( QIcon(pixmap) ) def linesThrendProps(self): props = { 'color' : self.linesThrendColor.name(), } return props def setLinesThrendProps(self, props): self.setLinesThrendColor( props.get('color', 'red') ) def chooseTitleColor(self): dlg = QColorDialog(self.titleColor, self) if dlg.exec_(): self.setTitleColor( dlg.selectedColor() ) dlg.deleteLater() def setTitleColor(self, color): self.titleColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.titleColor ) self.titleColorBtn.setIcon( QIcon(pixmap) ) def chooseLabelsColor(self): dlg = QColorDialog(self.labelsColor, self) if dlg.exec_(): self.setLabelsColor( dlg.selectedColor() ) dlg.deleteLater() def setLabelsColor(self, color): self.labelsColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.labelsColor ) self.labelsColorBtn.setIcon( QIcon(pixmap) ) def titleFontProps(self): qfont = self.titleFontCombo.currentFont() qfont.setPointSize( self.titleSizeSpin.value() ) if self.titleBoldBtn.isVisible() and self.titleBoldBtn.isChecked(): qfont.setBold( True ) if self.titleItalicBtn.isVisible() and self.titleItalicBtn.isChecked(): qfont.setItalic( True ) # search for the best match props = self.qfontToProps( qfont ) props['color'] = self.titleColor.name() props['size'] = self.titleSizeSpin.value() return props def setTitleFontProps(self, props): if 'family' in props: index = self.titleFontCombo.findText( props['family'] ) if index >= 0: self.titleFontCombo.setCurrentIndex( index ) if 'size' in props: try: self.titleSizeSpin.setValue( int(props['size']) ) except ValueError: pass self.setTitleColor( props.get('color', 'black') ) self.titleBoldBtn.setChecked( props.get('weight', '') == 'bold' ) self.titleItalicBtn.setChecked( props.get('style', '') == 'italic' ) def labelsFontProps(self): qfont = self.labelsFontCombo.currentFont() qfont.setPointSize( self.titleSizeSpin.value() ) if self.labelsBoldBtn.isVisible() and self.labelsBoldBtn.isChecked(): qfont.setBold( True ) if self.labelsItalicBtn.isVisible() and self.labelsItalicBtn.isChecked(): qfont.setItalic( True ) # search for the best match props = self.qfontToProps( qfont ) props['color'] = self.labelsColor.name() props['size'] = self.labelsSizeSpin.value() return props def setLabelsFontProps(self, props): if 'family' in props: index = self.labelsFontCombo.findText( props['family'] ) if index >= 0: self.labelsFontCombo.setCurrentIndex( index ) if 'size' in props: try: self.labelsSizeSpin.setValue( int(props['size']) ) except ValueError: pass self.setLabelsColor( props.get('color', 'black') ) self.labelsBoldBtn.setChecked( props.get('weight', '') == 'bold' ) self.labelsItalicBtn.setChecked( props.get('style', '') == 'italic' ) def initProps(self): settings = QgsSettings() self.setTitleFontProps( self.settingsToDict( settings.value("/pstimeseries/titleProps", {}) ) ) self.setLabelsFontProps( self.settingsToDict( settings.value("/pstimeseries/labelsProps", {}) ) ) self.setPointsProps( self.settingsToDict( settings.value("/pstimeseries/pointsProps", {}) ) ) self.setPointsReplicasProps( self.settingsToDict( settings.value("/pstimeseries/pointsReplicasProps", {}) ) ) self.setLinesProps( self.settingsToDict( settings.value("/pstimeseries/linesProps", {}) ) ) self.setLinesThrendProps( self.settingsToDict( settings.value("/pstimeseries/linesThrendProps", {}) ) ) def accept(self): settings = QgsSettings() settings.setValue("/pstimeseries/titleProps", self.titleFontProps()) settings.setValue("/pstimeseries/labelsProps", self.labelsFontProps()) settings.setValue("/pstimeseries/pointsProps", self.pointsProps()) settings.setValue("/pstimeseries/pointsReplicasProps", self.pointsReplicasProps()) settings.setValue("/pstimeseries/linesProps", self.linesProps()) settings.setValue("/pstimeseries/linesThrendProps", self.linesThrendProps()) QDialog.accept(self) @classmethod def settingsToDict(self, s): r = {} for k,v in s.items(): r[ unicode(k) ] = unicode(v) if isinstance(v, str) else v return r @classmethod def qfontToProps(self, qfont): props = { 'family' : unicode(qfont.family()), 'stretch' : qfont.stretch(), 'weight' : qfont.weight() } if qfont.style() == QFont.StyleItalic: style = 'italic' elif qfont.style() == QFont.StyleOblique: style = 'oblique' else: style = 'normal' props['style'] = style if qfont.capitalization() == QFont.SmallCaps: props['variant'] = 'small-caps' return self.findFont(props) @classmethod def findFont(self, props): from matplotlib.font_manager import FontProperties, findfont # search for the best match font = FontProperties( fname=findfont( FontProperties(**props) ) ) props = { 'family' : font.get_name(), 'weight' : font.get_weight(), 'style' : font.get_style(), } return props
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) settings = QgsSettings() # Default font font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setMatchedBraceBackgroundColor( QColor( settings.value( "pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)))) self.setMatchedBraceForegroundColor( QColor( settings.value( "pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)))) #self.setWrapMode(QsciScintilla.WrapWord) #self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, # QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor( QColor( settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR)))) self.setSelectionBackgroundColor( QColor( settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR)))) # Show line numbers fontmetrics = QFontMetrics(font) self.setMarginWidth(1, fontmetrics.width("0000") + 5) self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setMarginsBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) self.setIndentationGuidesForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setIndentationGuidesBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) # Highlight current line caretLineColorEditor = settings.value( "pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR)) cursorColorEditor = settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR)) self.setCaretLineVisible(True) self.setCaretWidth(2) self.setCaretLineBackgroundColor(caretLineColorEditor) self.setCaretForegroundColor(cursorColorEditor) # Folding self.setFolding(QsciScintilla.PlainFoldStyle) foldColor = QColor( settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR))) self.setFoldMarginColors(foldColor, foldColor) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor( QColor( settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR)))) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) self.setIndentationGuides(True) # Autocompletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFonts(10) self.initLexer()
def testMatchToSymbols(self): """ Test QgsCategorizedSymbolRender.matchToSymbols """ renderer = QgsCategorizedSymbolRenderer() renderer.setClassAttribute('x') symbol_a = createMarkerSymbol() symbol_a.setColor(QColor(255, 0, 0)) renderer.addCategory(QgsRendererCategory('a', symbol_a, 'a')) symbol_b = createMarkerSymbol() symbol_b.setColor(QColor(0, 255, 0)) renderer.addCategory(QgsRendererCategory('b', symbol_b, 'b')) symbol_c = createMarkerSymbol() symbol_c.setColor(QColor(0, 0, 255)) renderer.addCategory(QgsRendererCategory('c ', symbol_c, 'c')) matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( None, QgsSymbol.Marker) self.assertEqual(matched, 0) style = QgsStyle() symbol_a = createMarkerSymbol() symbol_a.setColor(QColor(255, 10, 10)) self.assertTrue(style.addSymbol('a', symbol_a)) symbol_B = createMarkerSymbol() symbol_B.setColor(QColor(10, 255, 10)) self.assertTrue(style.addSymbol('B ', symbol_B)) symbol_b = createFillSymbol() symbol_b.setColor(QColor(10, 255, 10)) self.assertTrue(style.addSymbol('b', symbol_b)) symbol_C = createLineSymbol() symbol_C.setColor(QColor(10, 255, 10)) self.assertTrue(style.addSymbol('C', symbol_C)) symbol_C = createMarkerSymbol() symbol_C.setColor(QColor(10, 255, 10)) self.assertTrue(style.addSymbol(' ----c/- ', symbol_C)) # non-matching symbol type matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Line) self.assertEqual(matched, 0) self.assertEqual(unmatched_cats, ['a', 'b', 'c ']) self.assertEqual(unmatched_symbols, [' ----c/- ', 'B ', 'C', 'a', 'b']) # exact match matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Marker) self.assertEqual(matched, 1) self.assertEqual(unmatched_cats, ['b', 'c ']) self.assertEqual(unmatched_symbols, [' ----c/- ', 'B ', 'C', 'b']) # make sure symbol was applied context = QgsRenderContext() renderer.startRender(context, QgsFields()) symbol, ok = renderer.symbolForValue2('a') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#ff0a0a') renderer.stopRender(context) # case insensitive match matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Marker, False) self.assertEqual(matched, 2) self.assertEqual(unmatched_cats, ['c ']) self.assertEqual(unmatched_symbols, [' ----c/- ', 'C', 'b']) # make sure symbols were applied context = QgsRenderContext() renderer.startRender(context, QgsFields()) symbol, ok = renderer.symbolForValue2('a') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#ff0a0a') symbol, ok = renderer.symbolForValue2('b') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#0aff0a') renderer.stopRender(context) # case insensitive match matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Marker, False) self.assertEqual(matched, 2) self.assertEqual(unmatched_cats, ['c ']) self.assertEqual(unmatched_symbols, [' ----c/- ', 'C', 'b']) # make sure symbols were applied context = QgsRenderContext() renderer.startRender(context, QgsFields()) symbol, ok = renderer.symbolForValue2('a') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#ff0a0a') symbol, ok = renderer.symbolForValue2('b') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#0aff0a') renderer.stopRender(context) # tolerant match matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Marker, True, True) self.assertEqual(matched, 2) self.assertEqual(unmatched_cats, ['b']) self.assertEqual(unmatched_symbols, ['B ', 'C', 'b']) # make sure symbols were applied context = QgsRenderContext() renderer.startRender(context, QgsFields()) symbol, ok = renderer.symbolForValue2('a') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#ff0a0a') symbol, ok = renderer.symbolForValue2('c ') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#0aff0a') renderer.stopRender(context) # tolerant match, case insensitive matched, unmatched_cats, unmatched_symbols = renderer.matchToSymbols( style, QgsSymbol.Marker, False, True) self.assertEqual(matched, 3) self.assertFalse(unmatched_cats) self.assertEqual(unmatched_symbols, ['C', 'b']) # make sure symbols were applied context = QgsRenderContext() renderer.startRender(context, QgsFields()) symbol, ok = renderer.symbolForValue2('a') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#ff0a0a') symbol, ok = renderer.symbolForValue2('b') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#0aff0a') symbol, ok = renderer.symbolForValue2('c ') self.assertTrue(ok) self.assertEqual(symbol.color().name(), '#0aff0a') renderer.stopRender(context)
def setLexers(self): self.lexer = QsciLexerPython() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) loadFont = self.settings.value("pythonConsole/fontfamilytext") if loadFont: font.setFamily(loadFont) fontSize = self.settings.value("pythonConsole/fontsize", type=int) if fontSize: font.setPointSize(fontSize) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( self.settings.value("pythonConsole/defaultFontColor", QColor(self.DEFAULT_COLOR)))) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentFontColor", QColor(self.COMMENT_COLOR))), 1) self.lexer.setColor( QColor( self.settings.value("pythonConsole/numberFontColor", QColor(self.NUMBER_COLOR))), 2) self.lexer.setColor( QColor( self.settings.value("pythonConsole/keywordFontColor", QColor(self.KEYWORD_COLOR))), 5) self.lexer.setColor( QColor( self.settings.value("pythonConsole/classFontColor", QColor(self.CLASS_COLOR))), 8) self.lexer.setColor( QColor( self.settings.value("pythonConsole/methodFontColor", QColor(self.METHOD_COLOR))), 9) self.lexer.setColor( QColor( self.settings.value("pythonConsole/decorFontColor", QColor(self.DECORATION_COLOR))), 15) self.lexer.setColor( QColor( self.settings.value("pythonConsole/commentBlockFontColor", QColor(self.COMMENT_BLOCK_COLOR))), 12) self.lexer.setColor( QColor( self.settings.value("pythonConsole/singleQuoteFontColor", QColor(self.SINGLE_QUOTE_COLOR))), 4) self.lexer.setColor( QColor( self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(self.DOUBLE_QUOTE_COLOR))), 3) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6) self.lexer.setColor( QColor( self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7) self.lexer.setColor( QColor( self.settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13) self.lexer.setColor(QColor(Qt.red), 14) self.lexer.setFont(font, 1) self.lexer.setFont(font, 2) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.lexer.setFont(font, QsciLexerPython.UnclosedString) for style in range(0, 33): paperColor = QColor( self.settings.value("pythonConsole/paperBackgroundColor", QColor(self.BACKGROUND_COLOR))) self.lexer.setPaper(paperColor, style) self.setLexer(self.lexer)
def testPalettedClassDataFromLayer(self): # no layer classes = QgsPalettedRasterRenderer.classDataFromRaster(None, 1) self.assertFalse(classes) # 10 class layer path = os.path.join(unitTestDataPath('raster'), 'with_color_table.tif') info = QFileInfo(path) base_name = info.baseName() layer10 = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1) self.assertEqual(len(classes), 10) self.assertEqual(classes[0].value, 1) self.assertEqual(classes[0].label, '1') self.assertEqual(classes[1].value, 2) self.assertEqual(classes[1].label, '2') self.assertEqual(classes[2].value, 3) self.assertEqual(classes[2].label, '3') self.assertEqual(classes[3].value, 4) self.assertEqual(classes[3].label, '4') self.assertEqual(classes[4].value, 5) self.assertEqual(classes[4].label, '5') self.assertEqual(classes[5].value, 6) self.assertEqual(classes[5].label, '6') self.assertEqual(classes[6].value, 7) self.assertEqual(classes[6].label, '7') self.assertEqual(classes[7].value, 8) self.assertEqual(classes[7].label, '8') self.assertEqual(classes[8].value, 9) self.assertEqual(classes[8].label, '9') self.assertEqual(classes[9].value, 10) self.assertEqual(classes[9].label, '10') # bad band self.assertFalse(QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 10101010)) # with ramp r = QgsGradientColorRamp(QColor(200, 0, 0, 100), QColor(0, 200, 0, 200)) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1, r) self.assertEqual(len(classes), 10) self.assertEqual(classes[0].color.name(), '#c80000') self.assertEqual(classes[1].color.name(), '#b21600') self.assertEqual(classes[2].color.name(), '#9c2c00') self.assertEqual(classes[3].color.name(), '#854200') self.assertEqual(classes[4].color.name(), '#6f5900') self.assertEqual(classes[5].color.name(), '#596f00') self.assertEqual(classes[6].color.name(), '#428500') self.assertEqual(classes[7].color.name(), '#2c9c00') self.assertEqual(classes[8].color.name(), '#16b200') self.assertEqual(classes[9].color.name(), '#00c800') # 30 class layer path = os.path.join(unitTestDataPath('raster'), 'unique_1.tif') info = QFileInfo(path) base_name = info.baseName() layer10 = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer10.dataProvider(), 1) self.assertEqual(len(classes), 30) expected = [11, 21, 22, 24, 31, 82, 2002, 2004, 2014, 2019, 2027, 2029, 2030, 2080, 2081, 2082, 2088, 2092, 2097, 2098, 2099, 2105, 2108, 2110, 2114, 2118, 2126, 2152, 2184, 2220] self.assertEqual([c.value for c in classes], expected) # bad layer path = os.path.join(unitTestDataPath('raster'), 'hub13263.vrt') info = QFileInfo(path) base_name = info.baseName() layer = QgsRasterLayer(path, base_name) classes = QgsPalettedRasterRenderer.classDataFromRaster(layer.dataProvider(), 1) self.assertFalse(classes)
def saveSpritesSheet(icons, folder): sprites = {} for iconPath, sl in icons.items(): iconName = os.path.splitext(os.path.basename(iconPath))[0] sprites[iconName] = saveSymbolLayerSprite(sl) if sprites: height = max([s.height() for s, s2x in sprites.values()]) width = sum([s.width() for s, s2x in sprites.values()]) img = QImage(width, height, QImage.Format_ARGB32) img.fill(QColor(Qt.transparent)) img2x = QImage(width * 2, height * 2, QImage.Format_ARGB32) img2x.fill(QColor(Qt.transparent)) painter = QPainter(img) painter.begin(img) painter2x = QPainter(img2x) painter2x.begin(img2x) spritesheet = { NO_ICON: { "width": 0, "height": 0, "x": 0, "y": 0, "pixelRatio": 1 } } spritesheet2x = { NO_ICON: { "width": 0, "height": 0, "x": 0, "y": 0, "pixelRatio": 1 } } x = 0 for name, _sprites in sprites.items(): s, s2x = _sprites painter.drawImage(x, 0, s) painter2x.drawImage(x * 2, 0, s2x) spritesheet[name] = { "width": s.width(), "height": s.height(), "x": x, "y": 0, "pixelRatio": 1 } spritesheet2x[name] = { "width": s2x.width(), "height": s2x.height(), "x": x * 2, "y": 0, "pixelRatio": 2 } x += s.width() painter.end() painter2x.end() img.save(os.path.join(folder, "spriteSheet.png")) img2x.save(os.path.join(folder, "*****@*****.**")) with open(os.path.join(folder, "spriteSheet.json"), 'w') as f: json.dump(spritesheet, f) with open(os.path.join(folder, "*****@*****.**"), 'w') as f: json.dump(spritesheet2x, f)
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 testLabelMargin(self): """ Test rendering map item with a label margin set """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) layout.addLayoutItem(map) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin(QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters)) checker = QgsLayoutChecker('composermap_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin(QgsLayoutMeasurement(3, QgsUnitTypes.LayoutCentimeters)) checker = QgsLayoutChecker('composermap_label_cm_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setMapRotation(45) map.zoomToExtent(vl.extent()) map.setScale(map.scale() * 1.2) checker = QgsLayoutChecker('composermap_rotated_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # data defined map.setMapRotation(0) map.zoomToExtent(vl.extent()) map.dataDefinedProperties().setProperty(QgsLayoutObject.MapLabelMargin, QgsProperty.fromExpression('1+3')) map.refresh() checker = QgsLayoutChecker('composermap_dd_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
def __init__(self, parent=None): super(ShellOutputScintilla, self).__init__(parent) self.parent = parent self.shell = self.parent.shell self.settings = QgsSettings() # Creates layout for message bar self.layout = QGridLayout(self) self.layout.setContentsMargins(0, 0, 0, 0) spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding) self.layout.addItem(spacerItem, 1, 0, 1, 1) # messageBar instance self.infoBar = QgsMessageBar() sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.infoBar.setSizePolicy(sizePolicy) self.layout.addWidget(self.infoBar, 0, 0, 1, 1) # Enable non-ascii chars for editor self.setUtf8(True) sys.stdout = writeOut(self, sys.stdout) sys.stderr = writeOut(self, sys.stderr, "_traceback") self.insertInitText() self.refreshSettingsOutput() self.setReadOnly(True) # Set the default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) # Margin 0 is used for line numbers self.setMarginWidth(0, 0) self.setMarginWidth(1, 0) self.setMarginWidth(2, 0) #fm = QFontMetrics(font) self.setMarginsFont(font) self.setMarginWidth(1, "00000") self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor("#3E3EE3")) self.setMarginsBackgroundColor(QColor("#f9f9f9")) self.setCaretLineVisible(True) self.setCaretWidth(0) self.setMinimumHeight(120) self.setWrapMode(QsciScintilla.WrapCharacter) self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self) self.runScut.setContext(Qt.WidgetShortcut) self.runScut.activated.connect(self.enteredSelected) # Reimplemented copy action to prevent paste prompt (>>>,...) in command view self.copyShortcut = QShortcut(QKeySequence.Copy, self) self.copyShortcut.activated.connect(self.copy) self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self) self.selectAllShortcut.activated.connect(self.selectAll)
def testPartialLabels(self): """ Test rendering map item with a show partial labels flag """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.UsePartialCandidates, False) engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) layout.addLayoutItem(map) # default should always be to hide partial labels self.assertFalse(map.mapFlags() & QgsLayoutItemMap.ShowPartialLabels) # hiding partial labels (the default) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # showing partial labels map.setMapFlags(QgsLayoutItemMap.ShowPartialLabels) checker = QgsLayoutChecker('composermap_show_partial_labels', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
def testQgsGraduatedSymbolRenderer_2(self): """Test QgsGraduatedSymbolRenderer: Adding /removing/editing classes """ # Create a renderer renderer = QgsGraduatedSymbolRenderer() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) symbol.setColor(QColor(255, 0, 0)) # Add class without start and end ranges renderer.addClass(symbol.clone()) renderer.addClass(symbol.clone()) renderer.updateRangeLabel(1, 'Second range') renderer.updateRangeLowerValue(1, 10.0) renderer.updateRangeUpperValue(1, 25.0) renderer.updateRangeRenderState(1, False) symbol.setColor(QColor(0, 0, 255)) renderer.updateRangeSymbol(1, symbol.clone()) # Add as a rangeobject symbol.setColor(QColor(0, 255, 0)) range = QgsRendererRange(20.0, 25.5, symbol.clone(), 'Third range', False) renderer.addClassRange(range) # Add class by lower and upper renderer.addClassLowerUpper(25.5, 30.5) # (Update label for sorting tests) renderer.updateRangeLabel(3, 'Another range') self.assertEqual( dumpRangeLabels(renderer.ranges()), '(0.0 - 0.0,Second range,Third range,Another range,)', 'Added ranges labels not correct') self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'Added ranges lower/upper values not correct') # Check that clone function works renderer2 = renderer.clone() self.assertEqual(dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "clone function doesn't replicate renderer properly") # Check save and reload from Dom works doc = QDomDocument() element = renderer.save(doc, QgsReadWriteContext()) renderer2 = QgsGraduatedSymbolRenderer.create(element, QgsReadWriteContext()) self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "Save/create from DOM doesn't replicate renderer properly") # Check sorting renderer.sortByLabel() self.assertEqual( dumpRangeList(renderer.ranges(), labelsOnly=True), '(0.0 - 0.0,Another range,Second range,Third range,)', 'sortByLabel not correct') renderer.sortByValue() self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'sortByValue not correct') renderer.sortByValue(Qt.DescendingOrder) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)', 'sortByValue descending not correct') # Check deleting renderer.deleteClass(2) self.assertEqual(dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)', 'deleteClass not correct') renderer.deleteAllClasses() self.assertEqual(len(renderer.ranges()), 0, "deleteAllClasses didn't delete all")
def testBlockingItems(self): """ Test rendering map item with blocking items """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) map.setId('map') layout.addLayoutItem(map) map2 = QgsLayoutItemMap(layout) map2.attemptSetSceneRect(QRectF(0, 5, 50, 80)) map2.setFrameEnabled(True) map2.setBackgroundEnabled(False) map2.setId('map2') layout.addLayoutItem(map2) map3 = QgsLayoutItemMap(layout) map3.attemptSetSceneRect(QRectF(150, 160, 50, 50)) map3.setFrameEnabled(True) map3.setBackgroundEnabled(False) map3.setId('map3') layout.addLayoutItem(map3) map.addLabelBlockingItem(map2) map.addLabelBlockingItem(map3) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_blockers', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) doc = QDomDocument("testdoc") elem = layout.writeXml(doc, QgsReadWriteContext()) l2 = QgsLayout(p) self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext())) map_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map'][0] map2_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map2'][0] map3_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map3'][0] self.assertTrue(map_restore.isLabelBlockingItem(map2_restore)) self.assertTrue(map_restore.isLabelBlockingItem(map3_restore))
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setWrapMode(QsciScintilla.WrapWord) self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor('#2e3436')) self.setSelectionBackgroundColor(QColor('#babdb6')) # Show line numbers self.setMarginWidth(1, '000') self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor('#2e3436')) self.setMarginsBackgroundColor(QColor('#babdb6')) # Highlight current line self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#d3d7cf')) # Folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor('#eeeeec')) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setAutoCompletionCaseSensitivity(False) # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', 10)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont) self.initLexer()
QgsWkbTypes, ) from qgis.gui import ( QgsMapTool, QgsRubberBand, ) from ..pe_utils import (PLANET_COLOR) LOG_LEVEL = os.environ.get('PYTHON_LOG_LEVEL', 'WARNING').upper() logging.basicConfig(level=LOG_LEVEL) log = logging.getLogger(__name__) RB_STROKE = PLANET_COLOR RB_FILL = QColor(204, 235, 239, 100) # noinspection DuplicatedCode class PlanetExtentMapTool(QgsMapTool): extentSelected = pyqtSignal(object) def __init__(self, canvas): QgsMapTool.__init__(self, canvas) self.canvas = canvas self.extent = None self.dragging = False self.rubber_band = None self.select_rect = QRect()
def accept(self): super(AlgorithmDialog, self)._saveGeometry() feedback = self.createFeedback() context = dataobjects.createContext(feedback) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: parameters = self.getParamValues() if checkCRS and not self.alg.validateInputCrs(parameters, context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Layers do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return checkExtentCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_EXTENT_CRS) # TODO if False and checkExtentCRS and self.checkExtentCRS(): reply = QMessageBox.question( self, self.tr("Extent CRS"), self. tr('Extent parameters must use the same CRS as the input layers.\n' 'Your input layers do not have the same extent as the project, ' 'so the extent might be in a wrong CRS if you have selected it from the canvas.\n' 'Do you want to continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.alg.checkParameterValues(parameters, context) if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.btnRun.setEnabled(False) self.btnClose.setEnabled(False) buttons = self.mainWidget.iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.progressBar.setMaximum(0) self.lblProgress.setText(self.tr('Processing algorithm...')) # Make sure the Log tab is visible before executing the algorithm try: self.tabWidget.setCurrentIndex(1) self.repaint() except: pass self.setInfo( self.tr('<b>Algorithm \'{0}\' starting...</b>').format( self.alg.displayName()), escape_html=False) feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.alg.parameterDefinition( k).valueAsPythonString(v, context)) feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') feedback.pushInfo('') start_time = time.time() if self.iterateParam: self.buttonCancel.setEnabled( self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.alg, parameters, self.iterateParam, context, feedback): feedback.pushInfo( self.tr( 'Execution completed in {0:0.2f} seconds'.format( time.time() - start_time))) self.buttonCancel.setEnabled(False) self.finish(True, parameters, context, feedback) else: self.buttonCancel.setEnabled(False) self.resetGUI() else: command = self.alg.asPythonCommand(parameters, context) if command: ProcessingLog.addToLog(command) self.buttonCancel.setEnabled( self.alg.flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'. format(time.time() - start_time))) feedback.pushInfo(self.tr('Results:')) feedback.pushCommandInfo(pformat(results)) else: feedback.reportError( self.tr('Execution failed after {0:0.2f} seconds'. format(time.time() - start_time))) feedback.pushInfo('') self.buttonCancel.setEnabled(False) self.finish(ok, results, context, feedback) task = QgsProcessingAlgRunnerTask(self.alg, parameters, context, feedback) task.executed.connect(on_complete) QgsApplication.taskManager().addTask(task) except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.bar.clearWidgets() self.bar.pushMessage( "", self.tr("Wrong or missing parameter value: {0}").format( e.parameter.description()), level=QgsMessageBar.WARNING, duration=5)
def setLinesThrendColor(self, color): self.linesThrendColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.linesThrendColor ) self.linesThrendColorBtn.setIcon( QIcon(pixmap) )
def testReprojectionErrorsWhileRendering(self): # WKT of a polygon which causes reprojection errors while rendering # (apologies for the ridiculously complex wkt, but I can't find a way to reproduce with simplifiction) wkt = 'MultiPolygon (((16.93392988400009358 42.77094147300012139, 16.88493899800005238 42.72939687700012712, ' \ '16.80298912900011032 42.76349518400014915, 16.85816491000014139 42.78400299700011544, ' \ '16.93392988400009358 42.77094147300012139)),((17.38200931100010393 42.79783763200002511, ' \ '17.65894616000011297 42.74298737200008702, 17.74887129000009622 42.69456614800010641, ' \ '17.32374108200008322 42.79083893400003547, 17.38200931100010393 42.79783763200002511)),' \ '((16.768565300000148 42.97223541900014254, 17.03207441500009622 42.98261139500014849, ' \ '17.13184655000009116 42.96954987200014386, 17.20020592500009116 42.92177969000012183, ' \ '16.85141035200010151 42.90070221600008438, 16.65544681100004709 42.92625560099999404, ' \ '16.70679772200014668 42.96954987200014386, 16.63168379000003938 42.98261139500014849, ' \ '16.768565300000148 42.97223541900014254)),((17.05567467500011958 43.02895742400001211, ' \ '17.24024498800011429 43.02277252800014651, 17.74146569100011561 42.83926015800001608, ' \ '17.70736738400009358 42.88703034100014122, 17.65334906206413734 42.8909283361407887, ' \ '17.70158573400010482 42.91950022500007833, 17.81175988700005064 42.909862570000044, ' \ '17.85847538200005147 42.81697418200012351, 18.22413781700009849 42.62807098500009317, ' \ '18.43735477700010961 42.55921213800017711, 18.4371480710000526 42.4934022020000981, ' \ '18.49642988400009358 42.41632721600008438, 18.23894290500010129 42.55906810100005089, ' \ '18.21753991000014139 42.6201032570001388, 18.07601972700010151 42.65131256700003348, ' \ '18.0432235040000819 42.70205312700007028, 17.90162194100014403 42.75189850500014188, ' \ '17.8928328790000819 42.79083893400003547, 17.72095787900005348 42.8262393250000315, ' \ '17.7618921230000808 42.77871328300012976, 17.74870853000004445 42.77204010600017625, ' \ '17.21387780000011958 42.98261139500014849, 17.04615319100011561 42.9950625670000619, ' \ '17.00163821700004974 43.05149974200010377, 17.05567467500011958 43.02895742400001211)),' \ '((16.19467207100007045 43.07440827000000638, 16.254893425000148 43.06854889500006323, ' \ '16.08716881600014403 43.01146067900008063, 16.04883873800011429 43.06517161700004692, ' \ '16.19467207100007045 43.07440827000000638)),((16.56275475400011032 43.22898997600010773, ' \ '16.65951582100009887 43.21596914300012315, 16.72771243600001867 43.16461823100003414, ' \ '17.19336998800014271 43.12726471600016964, 16.67017662900013875 43.12547435099999404, ' \ '16.37159264400014536 43.19550202000006323, 16.49642988400006516 43.21808502800014651, ' \ '16.58326256600014403 43.18866608300005794, 16.52051842500006273 43.22898997600010773, ' \ '16.56275475400011032 43.22898997600010773)),((16.80681399800010922 43.34247467700005529, ' \ '16.89234459700011826 43.31220123900006058, 16.84620201900008851 43.27338288000005662, ' \ '16.62826582100012729 43.26373932500008834, 16.50074303500014139 43.28424713700003679, ' \ '16.42188561300008587 43.31757233300011478, 16.40577233200011165 43.33270905200011214, ' \ '16.45346113400009358 43.35317617400009738, 16.42628014400008851 43.39411041900011412, ' \ '16.44703209700008983 43.39484284100014122, 16.80681399800010922 43.34247467700005529)),' \ '((16.29818769600012729 43.40363190300011809, 16.30274498800008587 43.38727448100009099, ' \ '16.39144941500012465 43.34638092700005529, 16.348643425000148 43.33869049700003018, ' \ '16.20045006600014403 43.40704987200003018, 16.29818769600012729 43.40363190300011809)),' \ '((16.33415774800010922 43.50153229400014254, 16.3752547540000819 43.49017975500008504, ' \ '16.21143639400008851 43.49005768400009231, 16.26441491000014139 43.51288483300011478, ' \ '16.33415774800010922 43.50153229400014254)),((15.67888431100004709 43.64801666900014254, ' \ '15.74040774800010922 43.62750885600009099, 15.67204837300002396 43.63743724200010377, ' \ '15.60377037900013875 43.67470937700007028, 15.67888431100004709 43.64801666900014254)),' \ '((15.36736087300005238 43.79010651200015047, 15.39568118600007551 43.7724063170000619, ' \ '15.22779381600014403 43.87445709800014981, 15.24073326900014536 43.88076406500009341, ' \ '15.36736087300005238 43.79010651200015047)),((15.44271894600009887 43.89907461100013109, ' \ '15.35865319100014403 43.91937897300014981, 15.26124108200011165 44.01105377800003282, ' \ '15.38404381600008719 43.9701602230000077, 15.44271894600009887 43.89907461100013109)),' \ '((15.22575931100010393 44.06622955900014915, 15.25440514400008851 44.01788971600014122, ' \ '15.12183678500014139 44.09223053600005926, 15.06251061300008587 44.16193268400012073, ' \ '15.22575931100010393 44.06622955900014915)),((14.83545983200014007 44.15102773600013109, ' \ '14.85726972700010151 44.15204498900000374, 14.86915123800014271 44.14052969000006499, ' \ '14.83521569100008719 44.14166901200009363, 14.81983483200014007 44.15302155199999845, ' \ '14.82243899800005238 44.16868724200004692, 14.83545983200014007 44.15102773600013109)),' \ '((14.98511803500011297 44.09096914300012315, 15.21680748800008587 43.91278717700008372, ' \ '15.13331139400011693 43.92121002800003282, 15.19450931100004709 43.87262604400017096, ' \ '15.10661868600007551 43.92544179900015422, 14.84961998800014271 44.17560455900014915, ' \ '14.98511803500011297 44.09096914300012315)),((14.765961134000122 44.26504140800015819, ' \ '14.74854576900014536 44.26166413000014188, 14.73959394600012729 44.28017812700015554, ' \ '14.79167728000007287 44.27252838700003679, 14.765961134000122 44.26504140800015819)),' \ '((14.66138756600011561 44.30866120000014519, 14.6407983730000808 44.31183502800003282, ' \ '14.59506269600007045 44.34711334800006455, 14.643565300000148 44.32575104400011412, ' \ '14.66138756600011561 44.30866120000014519)),((14.81120853000004445 44.35004303600000242, ' \ '14.75619550900009358 44.36399974200004692, 14.76343834700008983 44.41535065300017493, ' \ '14.80323326900008851 44.40550364800004957, 14.81120853000004445 44.35004303600000242)),' \ '((14.27116946700002131 44.61253489800004957, 14.23259524800005238 44.62604401200012205, ' \ '14.2657983730000808 44.67951080900003547, 14.28044681100007551 44.67755768400009231, ' \ '14.27116946700002131 44.61253489800004957)),((14.84522545700008322 44.60053131700011875, ' \ '14.93824303500014139 44.59414297100001079, 15.07553144600007045 44.48407623900006058, ' \ '14.91114342500011958 44.54547760600014783, 15.04802493600004709 44.43943919500001982, ' \ '15.09669030000009116 44.41518789300000947, 15.04151451900014536 44.47662995000008834, ' \ '15.25440514400008851 44.34003327000000638, 15.165049675000148 44.36737702000006323, ' \ '15.22022545700008322 44.3127302100001117, 15.13086998800008587 44.33258698100003414, ' \ '15.17237389400014536 44.29913971600016964, 15.12875410200007309 44.31199778900018771, ' \ '15.08920332100009887 44.37421295800000109, 15.11719811300014271 44.38719310099999404, ' \ '15.04900149800010922 44.39468008000015686, 14.89747155000009116 44.49091217699999845, ' \ '14.91863040500010129 44.50454336100013109, 14.87696373800011429 44.55975983300005794, ' \ '14.73365319100008719 44.70319245000014519, 14.84522545700008322 44.60053131700011875)),' \ '((14.41000410200010151 44.60097890800001608, 14.52662194100011561 44.50372955900012073, ' \ '14.53435306100010393 44.48407623900006058, 14.42261803500008455 44.57387929900009738, ' \ '14.36304772200014668 44.57343170800000109, 14.38257897200014668 44.60325755399999537, ' \ '14.33578535200007309 44.71678294500010509, 14.39747155000009116 44.6856143250000315, ' \ '14.41000410200010151 44.60097890800001608)),((14.75326582100007045 44.84585195500012844, ' \ '14.74048912900011032 44.82050202000000638, 14.82243899800005238 44.77142975500005662, ' \ '14.84961998800014271 44.70319245000014519, 14.65788821700004974 44.79877350500014188, ' \ '14.7268172540000819 44.79877350500014188, 14.6858016290000819 44.8471540390000456, ' \ '14.75326582100007045 44.84585195500012844)),((14.47103925900006516 44.95392487200003018, ' \ '14.45191491000008455 44.79877350500014188, 14.47217858200011165 44.7079531920000619, ' \ '14.53435306100010393 44.63426341400010244, 14.51335696700007816 44.618841864000089, ' \ '14.42790774800005238 44.65656159100014122, 14.29420006600008719 44.9086367860001161, ' \ '14.30152428500011297 44.94342682500014519, 14.38738040500004445 44.90900299700003018, ' \ '14.39031009200004974 44.96039459800012139, 14.41138756600008719 44.95636627800014651, ' \ '14.27849368600004709 45.1133487000000315, 14.29957116000014139 45.16233958499999801, ' \ '14.35621178500014139 45.16925690300008966, 14.387705925000148 45.03904857000013351, ' \ '14.47103925900006516 44.95392487200003018)),((14.56332441500012465 45.24974192900008063, ' \ '14.62378991000011297 45.17548248900006058, 14.59742272200011826 45.16644928600005926, ' \ '14.66529381600011561 45.16181061400011743, 14.66529381600011561 45.08734772300006455, ' \ '14.74048912900011032 45.07306549700014386, 14.81495201900008851 44.97748444200009033, ' \ '14.70639082100009887 44.9467227230000077, 14.62891686300014271 44.97817617400004053, ' \ '14.62086022200008983 45.04559967700011214, 14.61695397200008983 45.02464427300007799, ' \ '14.51050866000014139 45.03217194200011875, 14.43873131600014403 45.07050202000006323, ' \ '14.4670516290000819 45.12409088700015047, 14.53012129000009622 45.13483307500014519, ' \ '14.53435306100010393 45.23753489800002114, 14.56332441500012465 45.24974192900008063)),' \ '((16.36947066200013978 46.54057118800012915, 16.63767134600004738 46.47447703100009164, ' \ '16.75508020000012266 46.38187286400001597, 16.83765913900006694 46.38187286400001597, ' \ '16.88923221800007468 46.29216257800014489, 17.05294315600005461 46.15346303300005104, ' \ '17.20859257000006437 46.11656606000003933, 17.27587528500004055 46.01202463800002818, ' \ '17.31680301900004793 45.99765859000002877, 17.29013798000011093 45.98463612900009423, ' \ '17.40620324700006449 45.94365671800015605, 17.59110152100009827 45.93621531200012953, ' \ '17.65652388500006964 45.84541982000014571, 17.80917606600013414 45.81441396100005647, ' \ '17.85806197100004056 45.77172922800004073, 18.21121870900006456 45.78537180600012846, ' \ '18.40438521300006869 45.74180857400001798, 18.57347049900010916 45.81668772400014689, ' \ '18.6556360270001278 45.90758656800015558, 18.7755253500000947 45.88283355700004051, ' \ '18.90130578600007993 45.93120269800006383, 18.87288374800004931 45.89523590100002082, ' \ '18.90699019400011593 45.86795074500018643, 18.85531376100007606 45.85735707600009903, ' \ '18.84497847500006174 45.8157058720000947, 18.96848514800012708 45.66873809800016204, ' \ '18.90357954900008508 45.57308502200005762, 18.94171675700005153 45.53892689999999277, ' \ '19.01809452300011571 45.56740061400002162, 19.10625451700005328 45.51164174500017623, ' \ '19.00961958800010621 45.49867095900005154, 19.00300500400010151 45.45536611000007099, ' \ '19.03742150900006891 45.42229319300010104, 18.97592655400006834 45.39495636000008005, ' \ '19.09199182100007874 45.34999786400005917, 19.12475467900009107 45.29811472600006539, ' \ '19.36308638500014467 45.24824696900010679, 19.40783817500010855 45.20313344400013023, ' \ '19.39068160000005037 45.16933705700016333, 19.22593713300008744 45.16194732700016345, ' \ '19.12186079900010327 45.195795390000157, 19.13767378700009658 45.14603098600004216, ' \ '19.04486291500009543 45.13724599300006446, 19.08227665200013234 45.08494944300004192, ' \ '19.0872375890000967 44.97710072800013847, 19.13167932100006396 44.95317454000003465, ' \ '19.06667036900009293 44.90568389900012392, 18.99142948400006503 44.9149339800001286, ' \ '19.01582076000008215 44.86563466400004074, 18.88962691200009658 44.86119049100013001, ' \ '18.78338016700013213 44.91374542300012251, 18.79175174900009893 45.00154368100008639, ' \ '18.73831831900008638 45.0159097290000858, 18.68405806500004473 45.08479441400000098, ' \ '18.64871138500012648 45.06267689999999959, 18.61667199700013953 45.09766184500010411, ' \ '18.54959598800010667 45.09476796500011631, 18.51703983500007666 45.05585561200003042, ' \ '18.23788374800011525 45.15745147700012296, 18.15365116400005263 45.0975584930001645, ' \ '18.00347945100011771 45.1493382780000303, 17.83573775200005684 45.0644338990000648, ' \ '17.68473921700012852 45.1639627080000281, 17.48185754400009273 45.11440500900012296, ' \ '17.49622359200009214 45.1416901650001563, 17.44775109900012922 45.13430043600014585, ' \ '17.44330692500011537 45.16205068000009248, 17.38243208800008688 45.1396231090000839, ' \ '17.26895064300006766 45.18954254200015441, 17.24548954300007608 45.15538442000017483, ' \ '17.18709517400012032 45.14856313100001728, 17.0363033440001459 45.23047027600007652, ' \ '17.00829471800011561 45.21615590500009318, 17.00829471800011561 45.24416453100009505, ' \ '16.94731652900014751 45.23568959600000028, 16.9243721930001243 45.28452382500016427, ' \ '16.81171757000004163 45.18122263700009, 16.52894413300009546 45.22225372400005483, ' \ '16.38921106000003647 45.11683380099999852, 16.31624393700010955 45.00123362300008978, ' \ '16.12152714000009723 45.09616322900008356, 16.02044803900011516 45.213933818000001, ' \ '15.79234826700013627 45.18980092400012438, 15.76361617000014803 44.97555043600003444, ' \ '15.7308533120001357 44.92723297200008403, 15.77343469200010873 44.84501576800015243, ' \ '15.71607385200013596 44.80320953400008932, 15.72847619600008784 44.76910308800002269, ' \ '15.80568078600006743 44.69665273000013883, 15.88877648900006534 44.72424794500012979, ' \ '15.96897831200004703 44.63924021400013942, 16.02830285600006732 44.62471913700009907, ' \ '16.04473596200011798 44.58937245700018082, 16.00608199000004106 44.54100331600012908, ' \ '16.11646285000011858 44.52146962500013672, 16.15966434700004584 44.41610138000002905, ' \ '16.13827030500004867 44.37760243800015303, 16.20286584400008678 44.35977406800010669, ' \ '16.18756962000011868 44.28241444999999032, 16.21578495300011014 44.20815541600011045, ' \ '16.32688928200008149 44.08237498000012522, 16.50103885900011846 43.99271637000008184, ' \ '16.67859908100004418 43.8406843060001421, 16.71260217300007866 43.77151540100005889, ' \ '17.03051558500007445 43.54847991900005866, 17.27050093600007585 43.46321380700000248, ' \ '17.28993127500007176 43.3034302780000786, 17.44206669100009321 43.15243174300015028, ' \ '17.6284119050001209 43.04657257100008394, 17.66272505700004558 42.96569895500012137, ' \ '17.63450972400008254 42.950402731000068, 17.51563561300008587 42.95888906500012183, ' \ '17.47087649800005238 43.01341380400010905, 17.50196373800014271 43.03099192900005221, ' \ '17.43360436300014271 43.01740143400009231, 17.46021569100011561 43.03099192900005221, ' \ '17.42611738400009358 43.06517161700004692, 17.4045516290000819 43.05149974200010377, ' \ '17.31625410200012993 43.12726471600016964, 17.11394290500004445 43.21320221600008438, ' \ '16.88062584700011826 43.40595123900006058, 16.62582441500009622 43.44904205900009231, ' \ '16.52466881600011561 43.51080963700009363, 16.39144941500012465 43.51080963700009363, ' \ '16.47339928500008455 43.5381533870001789, 16.43384850400013875 43.54975006700000506, ' \ '16.11768639400008851 43.52448151200003679, 16.17237389400014536 43.4896914730000077, ' \ '16.11312910200004467 43.47890859600009605, 15.95948326900011693 43.50397370000008834, ' \ '15.987315300000148 43.54490794500010509, 15.92530358200011165 43.55857982000004824, ' \ '15.91895592500009116 43.62872955900012073, 15.96631920700011165 43.64118073100003414, ' \ '15.90479576900014536 43.64801666900014254, 15.95297285200010151 43.65086497599999404, ' \ '15.95045006600008719 43.68854401200015047, 15.70630944100008719 43.76341380400005221, ' \ '15.6174422540000819 43.82550690300017493, 15.66309655000009116 43.81297435099999404, ' \ '15.67888431100004709 43.81928131700011875, 15.45508873800014271 43.92804596600014122, ' \ '15.14454186300011429 44.19546133000015686, 15.15219160200012993 44.23529694200014717, ' \ '15.11036217500011958 44.26434967700011214, 15.14063561300011429 44.28245677300013483, ' \ '15.17660566500009622 44.24994538000005662, 15.20777428500008455 44.27277252800014651, ' \ '15.19809004000012465 44.30166250200007028, 15.295258009000122 44.25067780199999845, ' \ '15.30274498800008587 44.29913971600016964, 15.26124108200011165 44.33258698100003414, ' \ '15.42448978000001603 44.26797109600006763, 15.52865644600009887 44.27179596600008438, ' \ '15.30795332100009887 44.35439687700007028, 15.00733483200014007 44.56972890800012976, ' \ '14.883799675000148 44.7236188820001388, 14.883799675000148 44.86147695500012844, 14.92164147200008983 ' \ '44.95880768400009231, 14.85279381600011561 45.09365469000000815, 14.65788821700004974 ' \ '45.19660065300017493, 14.57081139400008851 45.29364655200011214, 14.31153405000009116 ' \ '45.34398021000005485, 14.23259524800005238 45.14935944200000506, 14.17937259200007816 ' \ '45.13450755400005221, 14.19312584700008983 45.10561758000012844, 14.14389082100007045 ' \ '45.05939362200003018, 14.151377800000148 44.97748444200009033, 14.06885826900014536 ' \ '44.94953034100014122, 14.08383222700007309 44.9863955750000315, 14.04029381600014403 ' \ '45.03896719000015025, 14.0756942070000548 44.98371002800003282, 14.02051842500011958 ' \ '44.90110911700004692, 13.97266686300011429 44.90110911700004692, 13.99301191500009622 ' \ '44.88129303600014453, 13.97266686300011429 44.82664622599999404, 14.00001061300008587 ' \ '44.81305573100003414, 13.89014733200011165 44.83348216400010244, 13.91797936300014271 ' \ '44.77826569200009033, 13.90316816500009622 44.77240631700014717, 13.89698326900011693 ' \ '44.81305573100003414, 13.78711998800014271 44.87506745000008834, 13.84229576900008851 ' \ '44.88812897300006455, 13.79460696700010658 44.89496491100008768, 13.77409915500007287 ' \ '44.96381256700014717, 13.6232202480000808 45.07306549700014386, 13.61255944100014403 ' \ '45.11786530199999845, 13.72624759200004974 45.13450755400005221, 13.5959578790000819 ' \ '45.14541250200001343, 13.57545006600011561 45.26487864800007799, 13.60271243600001867 ' \ '45.28534577000012007, 13.57545006600011561 45.30646393400006389, 13.60954837300005238 ' \ '45.32013580900017757, 13.54127037900013875 45.34613678600005926, 13.50709069100014403 ' \ '45.51190827000000638, 13.62901778100007277 45.45898346000016943, 13.75929406800014476 ' \ '45.46316925100011019, 13.88900191200011136 45.42363678000005223, 13.98263960800005634 ' \ '45.47531321200001742, 13.97189091000012695 45.5142255660000643, 14.09291711400010172 ' \ '45.47391794800002174, 14.21869755100007637 45.49717234400004884, 14.37279667100006009 ' \ '45.47784535800009564, 14.4689148350000778 45.52559438100014688, 14.49857710800012001 ' \ '45.59618438800005435, 14.58094934100009255 45.66780792200010808, 14.66848921700008646 ' \ '45.53396596300005683, 14.79716353300005949 45.46518463200006011, 14.88160282300009385 ' \ '45.46978383400001178, 14.9226339110000481 45.51494903600017494, 15.13926151500010064 ' \ '45.43004465799999991, 15.32519331800011742 45.45283396399999276, 15.36136682100004691 ' \ '45.48203114900003641, 15.29666792800006192 45.52295888300012905, 15.2685559480001416 ' \ '45.60166208900012919, 15.37376916500011248 45.64021270800010655, 15.25501672300006817 ' \ '45.72346344000011698, 15.42906294700014769 45.77529490200011253, 15.45128381300008868 ' \ '45.81513743100013869, 15.67607629400006886 45.84169911700014666, 15.65943648300003588 ' \ '45.88882802400014782, 15.69798710100010908 46.0362092080000167, 15.58988000500005455 ' \ '46.11351715100001059, 15.62284956800010605 46.19170359400006021, 16.01920780400010358 ' \ '46.29882883700007312, 16.05961877400008575 46.33231516600015709, 16.0579651280001201 ' \ '46.37753204400003426, 16.2756262620000598 46.37316538500006402, 16.23490523300009158 ' \ '46.4933389280001137, 16.36947066200013978 46.54057118800012915))) ' geom = QgsGeometry.fromWkt(wkt) f = QgsFeature() f.setGeometry(geom) image = QImage(200, 200, QImage.Format_RGB32) painter = QPainter() ms = QgsMapSettings() crs = QgsCoordinateReferenceSystem.fromProj4( '+proj=ortho +lat_0=36.5 +lon_0=-118.8 +x_0=0 +y_0=0 +a=6371000 +b=6371000 +units=m +no_defs' ) self.assertTrue(crs.isValid()) ms.setDestinationCrs(crs) ms.setExtent(QgsRectangle(1374999.8, 3912610.7, 4724462.5, 6505499.6)) ms.setOutputSize(image.size()) context = QgsRenderContext.fromMapSettings(ms) context.setPainter(painter) context.setScaleFactor(96 / 25.4) # 96 DPI ct = QgsCoordinateTransform(QgsCoordinateReferenceSystem('epsg:4326'), crs, QgsProject.instance()) self.assertTrue(ct.isValid()) context.setCoordinateTransform(ct) context.setExtent( ct.transformBoundingBox(ms.extent(), QgsCoordinateTransform.ReverseTransform)) fill_symbol = QgsFillSymbol.createSimple({ 'color': '#ffffff', 'outline_color': '#ffffff', 'outline_width': '10' }) painter.begin(image) try: image.fill(QColor(0, 0, 0)) fill_symbol.startRender(context) fill_symbol.renderFeature(f, context) fill_symbol.stopRender(context) finally: painter.end() assert self.imageCheck('Reprojection errors polygon', 'reprojection_errors_polygon', image) #also test linestring linestring = QgsGeometry(geom.constGet().boundary()) f.setGeometry(linestring) line_symbol = QgsLineSymbol.createSimple({ 'color': '#ffffff', 'outline_width': '10' }) image = QImage(200, 200, QImage.Format_RGB32) painter.begin(image) try: image.fill(QColor(0, 0, 0)) line_symbol.startRender(context) line_symbol.renderFeature(f, context) line_symbol.stopRender(context) finally: painter.end() assert self.imageCheck('Reprojection errors linestring', 'reprojection_errors_linestring', image)
class DistroMap(object): def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisSettingsDirPath()).path() + "/python/plugins/distromap" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/distromap_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = DistroMapDialog() def confirm(self): # runs when OK button is pressed # initialise input parameters self.BASE_LAYER = self.dlg.ui.comboBase.currentItemData() self.SECONDARY_LAYER = self.dlg.ui.comboSecondary.currentItemData() self.SURFACE_LAYER = self.dlg.ui.comboSurface.currentItemData() self.LOCALITIES_LAYER = self.dlg.ui.comboLocalities.currentItemData() self.TAXON_FIELD_INDEX = self.dlg.ui.comboTaxonField.currentItemData()[0] self.GRID_LAYER = self.dlg.ui.comboGrid.currentItemData() self.X_MIN = float(self.dlg.ui.leMinX.text()) self.Y_MIN = float(self.dlg.ui.leMinY.text()) self.X_MAX = float(self.dlg.ui.leMaxX.text()) self.Y_MAX = float(self.dlg.ui.leMaxY.text()) self.OUT_WIDTH = self.dlg.ui.spnOutWidth.value() self.OUT_HEIGHT = self.dlg.ui.spnOutHeight.value() self.OUT_DIR = self.dlg.ui.leOutDir.text() try: self.getUniqueValues() except: message = "Could not get unique values from localities layer. " message += "Check that the localities layer and taxon identifier " message += "field are properly specified." QMessageBox.information(self.dlg,"Distribution Map Generator", message) return question = "This will generate " + str(self.UNIQUE_COUNT) question += " maps. Are you sure you want to continue?" reply = QMessageBox.question(self.dlg,'Distribution Map Generator', question, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) self.GRID_INDEX = QgsSpatialIndex() for feat in getLayerFromId(self.GRID_LAYER).getFeatures(): self.GRID_INDEX.insertFeature(feat) if reply == QMessageBox.Yes: try: self.process() except QgsCsException: return except Exception as ex: log(ex) return QMessageBox.information(self.dlg,"Distribution Map Generator", "Map processing complete.") self.dlg.ui.progressBar.setValue(0) QDialog.accept(self.dlg) else: return def initGui(self): # Create action that will start plugin configuration self.action = QAction( QIcon(self.plugin_dir + "/icon.svg"), u"Distribution Map Generator...", self.iface.mainWindow()) # connect the action to the run method self.action.triggered.connect(self.run) self.dlg.ui.buttonBox.accepted.connect(self.confirm) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu(u"&Distribution Map Generator", self.action) # Set colour for output background colour chooser: self.BACKGROUND_COLOUR = QColor(192,192,255) self.dlg.ui.frmColour.setStyleSheet("QWidget { background-color: %s }" % self.BACKGROUND_COLOUR.name()) def unload(self): # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&Distribution Map Generator", self.action) self.iface.removeToolBarIcon(self.action) def loadTaxonFields(self): self.dlg.ui.comboTaxonField.clear() try: layer=getLayerFromId(self.dlg.ui.comboLocalities.currentItemData()) provider=layer.dataProvider() except AttributeError: #Crashes without valid shapefiles log("Could not access the localities layer. Is it a valid vector layer?") return try: fieldmap=provider.fieldNameMap() for (name,index) in fieldmap.items(): self.dlg.ui.comboTaxonField.addItem(name,index) except: log("Could not load the field names for the localities layer.") def loadOutDir(self): #newname = QFileDialog.getExistingDirectory(None, "Output Maps Directory", self.dlg.ui.leOutDir.displayText()) newname = QFileDialog.getExistingDirectory(None, "Output Maps Directory") if newname != None: self.dlg.ui.leOutDir.setText(newname) def getCurrentExtent(self): extent = self.iface.mapCanvas().extent() # {"{0:.6f}".format() shows the float with 6 decimal places self.dlg.ui.leMinX.setText(str("{0:.6f}".format(extent.xMinimum()))) self.dlg.ui.leMinY.setText(str("{0:.6f}".format(extent.yMinimum()))) self.dlg.ui.leMaxX.setText(str("{0:.6f}".format(extent.xMaximum()))) self.dlg.ui.leMaxY.setText(str("{0:.6f}".format(extent.yMaximum()))) def getUniqueValues(self): layer = getLayerFromId(self.LOCALITIES_LAYER) self.UNIQUE_VALUES = layer.dataProvider().uniqueValues(int(self.TAXON_FIELD_INDEX)) self.UNIQUE_COUNT = len(self.UNIQUE_VALUES) def selectByAttribute(self, value): layer = getLayerFromId(self.LOCALITIES_LAYER) field_index = self.TAXON_FIELD_INDEX field_name = layer.fields()[int(field_index)].name() selected = [] filter = QgsExpression.createFieldEqualityExpression(field_name, str(value)) request = QgsFeatureRequest().setFilterExpression(filter) request.setSubsetOfAttributes([]) for feature in layer.getFeatures(request): selected.append(feature.id()) layer.selectByIds(selected) def selectByLocation(self): gridLayer = getLayerFromId(self.GRID_LAYER) selectLayer = getLayerFromId(self.LOCALITIES_LAYER) if gridLayer.crs() != selectLayer.crs(): QMessageBox.information(self.dlg,"Distribution Map Generator", "Localities layer and grid layers must have the same projection.") raise QgsCsException("Localities layer and grid layers must have the same projection.") selectedSet = [] feats = selectLayer.selectedFeatures() for f in feats: geom = QgsGeometry(f.geometry()) intersects = self.GRID_INDEX.intersects(geom.boundingBox()) for i in intersects: request = QgsFeatureRequest().setFilterFid(i) feat = next(gridLayer.getFeatures(request)) tmpGeom = QgsGeometry( feat.geometry() ) if geom.intersects(tmpGeom): selectedSet.append(feat.id()) gridLayer.selectByIds(selectedSet) def saveSelected(self): gridLayer = getLayerFromId(self.GRID_LAYER) # create memory layer outputLayer = QgsVectorLayer("Polygon", "taxon", "memory") outProvider = outputLayer.dataProvider() # add features outGrids = gridLayer.selectedFeatures() for grid in outGrids: outProvider.addFeatures([grid]) outputLayer.updateExtents() self.TAXON_GRID_LAYER = outputLayer def setBackgroundColour(self): col = QColorDialog.getColor() if col.isValid(): self.BACKGROUND_COLOUR = col self.dlg.ui.frmColour.setStyleSheet("QWidget { background-color: %s }" % self.BACKGROUND_COLOUR.name()) def printMap(self,taxon): # copy style from grid layer to output layer outstyle = tempfile.gettempdir() + os.sep + "output.qml" getLayerFromId(self.GRID_LAYER).saveNamedStyle(outstyle) self.TAXON_GRID_LAYER.loadNamedStyle(outstyle) # create layer set baseLayer = getLayerFromId(self.BASE_LAYER) if self.TAXON_GRID_LAYER.crs() != baseLayer.crs(): QMessageBox.information(self.dlg,"Distribution Map Generator", "All layers must have the same projection.") raise QgsCsException("All layers must have the same projection.") baseCrs = baseLayer.crs() if self.SECONDARY_LAYER != "None": secondaryLayer = getLayerFromId(self.SECONDARY_LAYER) if secondaryLayer.crs() != baseLayer.crs(): QMessageBox.information(self.dlg,"Distribution Map Generator", "All layers must have the same projection.") raise QgsCsException("All layers must have the same projection.") else: secondaryLayer = None if self.SURFACE_LAYER != "None": surfaceLayer = getLayerFromId(self.SURFACE_LAYER) if surfaceLayer.crs() != baseLayer.crs(): QMessageBox.information(self.dlg,"Distribution Map Generator", "All layers must have the same projection.") raise QgsCsException("All layers must have the same projection.") else: surfaceLayer = None lst = [] lst.append(self.TAXON_GRID_LAYER) if self.SURFACE_LAYER != "None": lst.append(surfaceLayer) if self.SECONDARY_LAYER != "None": lst.append(secondaryLayer) lst.append(baseLayer) ms = QgsMapSettings() ms.setLayers(lst) ms.setBackgroundColor(self.BACKGROUND_COLOUR) # set extent (xmin,ymin,xmax,ymax) rect = QgsRectangle(self.X_MIN,self.Y_MIN,self.X_MAX,self.Y_MAX) ms.setExtent(rect) # set output size outputSize = QSize(self.OUT_WIDTH,self.OUT_HEIGHT) ms.setOutputSize(outputSize) # create painter p = QPainter() p.setRenderHint(QPainter.Antialiasing) # create image (dimensions 325x299) img = QImage(outputSize, QImage.Format_ARGB32_Premultiplied) p.begin(img) # do the rendering r = QgsMapRendererCustomPainterJob(ms, p) r.start() r.waitForFinished() p.end() # save image outdir = self.OUT_DIR img.save(outdir+os.sep+str(str(taxon))+".png","png") def process(self): self.dlg.ui.progressBar.setMaximum(len(self.UNIQUE_VALUES)) # process all unique taxa getLayerFromId(self.LOCALITIES_LAYER).selectByIds([]) # use global projection #oldValidation = QSettings().value( "/Projections/defaultBehavior", "useGlobal", type=str ) #QSettings().setValue( "/Projections/defaultBehavior", "useGlobal" ) for taxon in self.UNIQUE_VALUES: self.selectByAttribute(taxon) self.selectByLocation() self.saveSelected() #load newly created memory layer QgsProject.instance().addMapLayer(self.TAXON_GRID_LAYER) try: self.printMap(taxon) except QgsCsException: #unload memory layer QgsProject.instance().removeMapLayers([self.TAXON_GRID_LAYER.id()]) self.TAXON_GRID_LAYER = None getLayerFromId(self.LOCALITIES_LAYER).removeSelection() getLayerFromId(self.GRID_LAYER).removeSelection() raise #unload memory layer QgsProject.instance().removeMapLayers([self.TAXON_GRID_LAYER.id()]) self.TAXON_GRID_LAYER = None self.dlg.ui.progressBar.setValue(self.dlg.ui.progressBar.value()+1) #restore saved default projection setting #QSettings().setValue( "/Projections/defaultBehaviour", oldValidation ) #clear selection getLayerFromId(self.LOCALITIES_LAYER).removeSelection() getLayerFromId(self.GRID_LAYER).removeSelection() # run method that performs all the real work def run(self): # first clear combo boxes so they don't get duplicate entries: self.dlg.ui.comboBase.clear() self.dlg.ui.comboSecondary.clear() self.dlg.ui.comboSurface.clear() self.dlg.ui.comboLocalities.clear() self.dlg.ui.comboGrid.clear() # populate combo boxes: self.dlg.ui.comboSecondary.addItem("None",None) self.dlg.ui.comboSurface.addItem("None",None) for layer in self.iface.mapCanvas().layers(): self.dlg.ui.comboBase.addItem(layer.name(),layer.id()) self.dlg.ui.comboSecondary.addItem(layer.name(),layer.id()) self.dlg.ui.comboSurface.addItem(layer.name(),layer.id()) #vector only layers: if type(layer).__name__ == "QgsVectorLayer": self.dlg.ui.comboLocalities.addItem(layer.name(),layer.id()) self.dlg.ui.comboGrid.addItem(layer.name(),layer.id()) self.loadTaxonFields() # define the signal connectors #QObject.connect(self.dlg.ui.comboLocalities,SIGNAL('currentIndexChanged (int)'),self.loadTaxonFields) self.dlg.ui.comboLocalities.currentIndexChanged.connect(self.loadTaxonFields) #QObject.connect(self.dlg.ui.btnBrowse,SIGNAL('clicked()'),self.loadOutDir) self.dlg.ui.btnBrowse.clicked.connect(self.loadOutDir) #QObject.connect(self.dlg.ui.btnExtent,SIGNAL('clicked()'),self.getCurrentExtent) self.dlg.ui.btnExtent.clicked.connect(self.getCurrentExtent) #QObject.connect(self.dlg.ui.btnColour,SIGNAL('clicked()'),self.setBackgroundColour) self.dlg.ui.btnColour.clicked.connect(self.setBackgroundColour) # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_()
def testQgsPresetSchemeColorRamp(self): # test preset color ramp r = QgsPresetSchemeColorRamp() self.assertEqual(r.type(), 'preset') # should be forced to have at least one color self.assertEqual(r.count(), 1) # test getter/setter r = QgsPresetSchemeColorRamp([ QColor(255, 0, 0), QColor(0, 255, 0), QColor(0, 0, 255), QColor(0, 0, 0) ]) self.assertEqual(r.colors(), [ QColor(255, 0, 0), QColor(0, 255, 0), QColor(0, 0, 255), QColor(0, 0, 0) ]) r.setColors([(QColor(255, 0, 0), '1'), (QColor(0, 255, 0), '2')]) self.assertEqual(r.colors(), [QColor(255, 0, 0), QColor(0, 255, 0)]) self.assertEqual(r.fetchColors(), [(QColor(255, 0, 0), '1'), (QColor(0, 255, 0), '2')]) # test value r = QgsPresetSchemeColorRamp([ QColor(255, 0, 0), QColor(0, 255, 0), QColor(0, 0, 255), QColor(0, 0, 0), QColor(255, 255, 255) ]) self.assertEqual(r.value(0), 0) self.assertEqual(r.value(1), 0.25) self.assertEqual(r.value(2), 0.5) self.assertEqual(r.value(3), 0.75) self.assertEqual(r.value(4), 1) self.assertTrue(not r.color(-1).isValid()) self.assertTrue(not r.color(5).isValid()) # test generated colors for i in range(5): self.assertEqual(r.color(r.value(i)), r.colors()[i]) # test creating from properties r.setColors([(QColor(255, 0, 0), '1'), (QColor(0, 255, 0), '2')]) props = r.properties() fromProps = QgsPresetSchemeColorRamp.create(props) self.assertEqual(fromProps.count(), 2) self.assertEqual(fromProps.fetchColors(), r.fetchColors()) # test cloning ramp cloned = r.clone() self.assertEqual(cloned.count(), 2) self.assertEqual(cloned.fetchColors(), r.fetchColors()) # test invert function r.invert() self.assertEqual(r.color(0), QColor(0, 255, 0)) self.assertEqual(r.color(1), QColor(255, 0, 0))
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 __init__(self, map_theme, layer, extent, tile_size, mupp, output, make_trans, map_settings, project): """ :param map_theme: :param extent: :param layer: :param tile_size: :param mupp: :param output: :param map_settings: Map canvas map settings used for some fallback values and CRS """ self.extent = extent self.mupp = mupp self.tile_size = tile_size driver = self.getDriverForFile(output) if not driver: raise QgsProcessingException( u'Could not load GDAL driver for file {}'.format(output)) crs = map_settings.destinationCrs() self.x_tile_count = math.ceil(extent.width() / mupp / tile_size) self.y_tile_count = math.ceil(extent.height() / mupp / tile_size) xsize = self.x_tile_count * tile_size ysize = self.y_tile_count * tile_size if make_trans: no_bands = 4 else: no_bands = 3 self.dataset = driver.Create(output, xsize, ysize, no_bands) self.dataset.SetProjection(str(crs.toWkt())) self.dataset.SetGeoTransform( [extent.xMinimum(), mupp, 0, extent.yMaximum(), 0, -mupp]) self.image = QImage(QSize(tile_size, tile_size), QImage.Format_ARGB32) self.settings = QgsMapSettings() self.settings.setOutputDpi(self.image.logicalDpiX()) self.settings.setOutputImageFormat(QImage.Format_ARGB32) self.settings.setDestinationCrs(crs) self.settings.setOutputSize(self.image.size()) self.settings.setFlag(QgsMapSettings.Antialiasing, True) self.settings.setFlag(QgsMapSettings.RenderMapTile, True) self.settings.setFlag(QgsMapSettings.UseAdvancedEffects, True) r = project.readNumEntry('Gui', '/CanvasColorRedPart', 255)[0] g = project.readNumEntry('Gui', '/CanvasColorGreenPart', 255)[0] b = project.readNumEntry('Gui', '/CanvasColorBluePart', 255)[0] if make_trans: self.bgColor = QColor(r, g, b, 0) else: self.bgColor = QColor(r, g, b) self.settings.setBackgroundColor(self.bgColor) if QgsProject.instance().mapThemeCollection().hasMapTheme(map_theme): self.settings.setLayers( QgsProject.instance().mapThemeCollection( ).mapThemeVisibleLayers( map_theme)) self.settings.setLayerStyleOverrides( QgsProject.instance().mapThemeCollection( ).mapThemeStyleOverrides( map_theme)) elif layer: self.settings.setLayers([layer]) else: self.settings.setLayers(map_settings.layers())
def setLabelsColor(self, color): self.labelsColor = QColor( color ) pixmap = QPixmap( 20,20 ) pixmap.fill( self.labelsColor ) self.labelsColorBtn.setIcon( QIcon(pixmap) )
def testInitialSizeSymbolMapUnits(self): """Test initial size of legend with a symbol size in map units""" point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') QgsProject.instance().addMapLayers([point_layer]) marker_symbol = QgsMarkerSymbol.createSimple({ 'color': '#ff0000', 'outline_style': 'no', 'size': '5', 'size_unit': 'MapUnit' }) point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol)) s = QgsMapSettings() s.setLayers([point_layer]) layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 80, 80)) map.setFrameEnabled(True) map.setLayers([point_layer]) layout.addLayoutItem(map) map.setExtent(point_layer.extent()) legend = QgsLayoutItemLegend(layout) legend.attemptSetSceneRect(QRectF(120, 20, 80, 80)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') layout.addLayoutItem(legend) legend.setLinkedMap(map) checker = QgsLayoutChecker('composer_legend_mapunits', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.assertTrue(result, message) # resize with non-top-left reference point legend.setResizeToContents(False) legend.setReferencePoint(QgsLayoutItem.LowerRight) legend.attemptMove(QgsLayoutPoint(120, 90)) legend.attemptResize(QgsLayoutSize(50, 60)) self.assertEqual(legend.positionWithUnits().x(), 120.0) self.assertEqual(legend.positionWithUnits().y(), 90.0) self.assertAlmostEqual(legend.pos().x(), 70, -1) self.assertAlmostEqual(legend.pos().y(), 30, -1) legend.setResizeToContents(True) legend.updateLegend() self.assertEqual(legend.positionWithUnits().x(), 120.0) self.assertEqual(legend.positionWithUnits().y(), 90.0) self.assertAlmostEqual(legend.pos().x(), 91, -1) self.assertAlmostEqual(legend.pos().y(), 71, -1) QgsProject.instance().removeMapLayers([point_layer.id()])
def testWidget(self): """Test widget operations""" widget = QgsFieldMappingWidget() for i in range(10): widget.appendField(QgsField(str(i))) self.assertTrue(widget.model().rowCount(QModelIndex()), 10) def _compare(widget, expected): actual = [] for field in widget.mapping(): actual.append(int(field.originalName)) self.assertEqual(actual, expected) _compare(widget, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) selection_model = widget.selectionModel() selection_model.clear() for i in range(0, 10, 2): selection_model.select(widget.model().index(i, 0), QItemSelectionModel.Select) self.assertTrue(widget.moveSelectedFieldsDown()) _compare(widget, [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]) selection_model.clear() for i in range(1, 10, 2): selection_model.select(widget.model().index(i, 0), QItemSelectionModel.Select) self.assertTrue(widget.moveSelectedFieldsUp()) _compare(widget, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) selection_model.clear() for i in range(0, 10, 2): selection_model.select(widget.model().index(i, 0), QItemSelectionModel.Select) self.assertTrue(widget.removeSelectedFields()) _compare(widget, [1, 3, 5, 7, 9]) # Test set destination fields widget.setSourceFields(self.source_fields) widget.setDestinationFields(self.destination_fields) mapping = widget.mapping() self.assertEqual(mapping[0].field.name(), 'destination_field1') self.assertEqual(mapping[1].field.name(), 'destination_field2') self.assertEqual(mapping[2].field.name(), 'destination_field3') self.assertEqual(mapping[0].originalName, 'destination_field1') self.assertEqual(mapping[1].originalName, 'destination_field2') self.assertEqual(mapping[2].originalName, 'destination_field3') # Test constraints f = QgsField('constraint_field', QVariant.Int) constraints = QgsFieldConstraints() constraints.setConstraint(QgsFieldConstraints.ConstraintNotNull, QgsFieldConstraints.ConstraintOriginProvider) constraints.setConstraint(QgsFieldConstraints.ConstraintExpression, QgsFieldConstraints.ConstraintOriginProvider) constraints.setConstraint(QgsFieldConstraints.ConstraintUnique, QgsFieldConstraints.ConstraintOriginProvider) f.setConstraints(constraints) fields = QgsFields() fields.append(f) widget.setDestinationFields(fields) self.assertEqual( widget.model().data(widget.model().index(0, 5, QModelIndex()), Qt.DisplayRole), "Constraints active") self.assertEqual( widget.model().data(widget.model().index(0, 5, QModelIndex()), Qt.ToolTipRole), "Unique<br>Not null<br>Expression") self.assertEqual( widget.model().data(widget.model().index(0, 5, QModelIndex()), Qt.BackgroundColorRole), QColor(255, 224, 178))
def initGui(self): # create action that will start plugin configuration self.action = QAction( QIcon(":icons/qgsazimuth.png"), "Azimuth and distance", self.iface.mainWindow(), ) self.action.setWhatsThis("Azimuth and distance") self.action.triggered.connect(self.run) self.bandpoint = QgsRubberBand(self.canvas, QgsWkbTypes.PointGeometry) self.bandpoint.setIcon(QgsRubberBand.ICON_CROSS) self.bandpoint.setColor(QColor.fromRgb(255, 50, 255)) self.bandpoint.setWidth(3) self.bandpoint.setIconSize(20) # add toolbar button and menu item self.iface.addPluginToMenu("&Topography", self.action) self.iface.addToolBarIcon(self.action) self.dock = Dock(self.iface.mainWindow()) self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dock) self.dock.hide() self.pluginGui = self.dock.widget() self.dock.closed.connect(self.cleanup) self.pluginGui.pushButton_vertexAdd.clicked.connect(self.addRow) self.pluginGui.pushButton_vertexInsert.clicked.connect(self.insertRow) self.pluginGui.pushButton_segListRowDel.clicked.connect(self.delRow) self.pluginGui.pushButton_segListLoad.clicked.connect(self.loadList) self.pluginGui.pushButton_segListClear.clicked.connect(self.clearList) self.pluginGui.pushButton_objectDraw.clicked.connect(self.addgeometry) self.pluginGui.pushButton_startCapture.clicked.connect(self.startgetpoint) self.pluginGui.pushButton_segListSave.clicked.connect(self.saveList) self.pluginGui.pushButton_useLast.clicked.connect(self.use_last_vertex) self.pluginGui.pickAngle1_button.clicked.connect(self.select_angle1) self.pluginGui.pickAngle2_button.clicked.connect(self.select_angle2) self.pluginGui.clearMarkers_button.clicked.connect(self.clear_markers) self.pluginGui.copyDiff_button.clicked.connect(self.copy_diff_offset) # self.pluginGui.table_segmentList.cellChanged.connect(self.render_temp_band) self.pluginGui.table_segmentList.setCurrentCell(0, 0) self.tool = GetCoordTool(self.canvas) self.tool.finished.connect(self.getpoint) self.tool.locationChanged.connect(self.pluginGui.update_startpoint) self.tool.locationChanged.connect(self.update_marker_location) self.angletool = LineTool(self.canvas) self.angletool.geometryComplete.connect(self.update_angle1) self.angletool.locationChanged.connect(self.update_marker_location) self.angletool2 = LineTool(self.canvas) self.angletool2.geometryComplete.connect(self.update_angle2) self.angletool2.locationChanged.connect(self.update_marker_location) self.pluginGui.azimuth1_edit.textChanged.connect(self.update_angle_calc) self.pluginGui.azimuth2_edit.textChanged.connect(self.update_angle_calc) self.pluginGui.lineEdit_magNorth.textChanged.connect(self.update_offsetlabel) self.pluginGui.radioButton_defaultNorth.toggled.connect(self.update_offsetlabel)