New answers tagged

0

The solution was in this link: https://code.visualstudio.com/docs/editor/integrated-terminal And in this paragraph the solution: Terminal profiles The terminal's shell defaults to $SHELL on Linux and macOS and PowerShell on Windows. Terminal profiles can be used to configure either the default or secondary shells by running the Terminal: Select Default ...


8

I guess you want to move a box' centroid position to another point if it has a common attribute with the point. I assume ID_PARENT and CODE are unique values. Use this script: box_layer = QgsProject.instance().mapLayersByName('box')[0] point_layer = QgsProject.instance().mapLayersByName('point')[0] dpr = box_layer.dataProvider() for box in box_layer....


4

One example: lyr = iface.activeLayer() feats = [f for f in lyr.getFeatures()] #List all features #names = [f['KOMMUNNAMN'] for f in feats] #List values in KOMMUNNAMN field #['Kiruna', 'Pajala', 'Gällivare', 'Jokkmokk', 'Boden'] fieldindex = lyr.fields().indexFromName('KOMMUNNAMN') attrMap = {} for f in feats: attrMap[f.id()] = {fieldindex:f['...


0

I had the same issue: I clicked on "file/Reload all from disk", it works ...


4

The method mapLayersByName() returns a list. To return a layer object you need to index the list to access its first element (assuming there is only one layer by that name in your project) e.g. layer = QgsProject.instance().mapLayersByName(layer_name)[0] if layer.geometryType() == 1:#Line geometry layer.loadNamedStyle('path\\to\\style_file.qml')


3

A perfect comment from @Jochen Schwarze: When I do a=QVariant(42), str(a) I get something like '<PyQt5.QtCore.QVariant object at 0x00000274E6B760B8>' and not '42' because just with the str() you may not get the desired output. >>> a = QVariant(42) >>> str(a) '<PyQt5.QtCore.QVariant object at 0x000001700D003BA0>' As a ...


3

A solution using CSV First recipe not useful in your case. It exports project bookmarks to CSV within QGIS (change path to file if you want to use it). In your case, you should better look at 2nd recipe that read your CSV and add it. I got a remaining issue about refreshing corresponding bookmark panel in the GUI. You also need to be aware there are 2 entry ...


1

I was unable to figure the proper syntax for looping through the text file via the QGIS console. STEP 1: I revisited my code to export from Arc to write directly to xml formatted as the QGIS Spatial Bookmarks Manager expects: import arcpy import xml.etree.ElementTree as ET srcPath = "D:\\SomeFolder\\Data\\" srcFile = "MyMap.mxd" arcpy....


0

After searching other answers I was able to find this bit of code, which is a way of creating a new layer in memory. new_layer = layer.materialize(QgsFeatureRequest().setFilterFids([1,2])) QgsProject.instance().addMapLayer(new_layer)


5

For my example, I took the QGIS plugin Plugin Builder 3 (link). After install of this plugin, a new repository is made in : \QGIS\QGIS3\profiles\default\python\plugins\pluginbuilder3 (here is the default profile default, it can be an other). If you look in the __init__.py : def classFactory(iface): """Load PluginBuilder class from file ...


3

If you can import manually via the QGIS Spatial Bookmarks Manager, then you can import the same bookmark file using this line: QgsApplication.bookmarkManager().importFromFile("path/to/bookmark.xml")


3

This may not be the best and smartest solution, but a working one. Let's assume there is a point layer 'points', see image below. Idea 1. Using the "Minimum bounding geometry" geoalgorithm. Proceed with Plugins > Python Console > Show Editor and paste the script below import processing # providing the point layer's name layer_name = "...


5

You should use rstyle method of legend. It returns reference to QgsLegendStyle object for legend components. Then, you can add spacing using setMargin function. Documentation for rstyle and setMargin. legend.rstyle(QgsLegendStyle.Group).setMargin(QgsLegendStyle.Top, 10) # Top side, 10 mm


1

Two solutions : If you want to use a PNG as icon you can go to property of your layer, then symbology (1), then click on the simple marker (2), then click on the list wich contain simple marker (3) and choose : Raster image marker. Click on the ... box and choose your png file. If you want to use a SVG as icon you can go to property of your layer, then ...


3

It's supported meanwhile (since 3.0): lay = iface.activeLayer() field_aliases = [field.alias() for field in lay.fields()] https://qgis.org/pyqgis/3.2/core/Field/QgsField.html#qgis.core.QgsField.alias


5

QgsVectorLayer class has featureAdded signal. First, you need to connect it to a new method which has one parameter (feature_id here) which grabs the newly added feature id. In edit mode, this id is a negative value. I have no experience on "Actions" in "Layer Properties", but you can get the feature (QgsFeature object) that is being ...


3

You have to specify the layer (feature class) name in the path string. layer_name = "countries" layer = QgsVectorLayer("path.gdb|layername=" + layer_name, "Countries", "ogr") QgsProject.instance().addMapLayer(layer)


0

One approach to do it. Check if in memory layer, run processing script to save your "in memory" layer, change memory layer datasource and save your project. In your case, you need to adapt my code to reuse infos like datasource path and layer name after your writeAsVectorFormat export project = QgsProject.instance() project_dir_path = project....


6

First, check if layer is an instance of QgsVectorLayer. layer = ... print(type(layer)) If so, then, you have to add the following method to your processing algorithm class to be able to add temporary layers to the "Layers Panel". def flags(self): return super().flags() | QgsProcessingAlgorithm.FlagNoThreading Then use this:: layer = ... ...


1

Try: QgsProject.instance().addMapLayer(layer, False) QgsProject.instance().layerTreeRoot()(0, layer) The first command registers the layer. The second adds it to the layer panel. I am not entirely sure why this works, but I always do it..


2

You can load the result of "native:centroids" into memory and then manipulate your .gpkg file. This has the advantage that you can also build in some checks before you overwrite your original source file. Something like this: # load layers from file source_path = os.path.join(<YOUR GEOPACKAGE PATH>) + "|layername=<POLYGON LAYER>&...


6

Use layer.fields().indexFromName("expr_f_1"). Because: Virtual fields are a pure QGIS concept. The data provider does not know the slightest bit about their existence. Virtual fields are just put "on top of" the real data, their values are temporarily regenerated by QGIS every time they are required somewhere. You may want to read ...


4

In QGIS 3, QgsVectorLayerUtils.getValues returns all values from a specified field name or expression. You can use to sum values in one field in that way: layer = iface.activeLayer() v = QgsVectorLayerUtils.getValues(layer, 'field_name')[0] v = list(filter(None, v)) s = sum(v) NOTE: NULL is None is False (both have different objects in the memory). NULL == ...


1

Use the Raster Calculator to replace anything above 32760 with 32767. Then set 32767 as the nodata value. The expression in the calculator would be: (raster1>32760)*32767+(raster1<32761)*raster1 which will either be the value of the raster or 32767, depending on whether it is greater than 32760.


5

For 'START_POINT' parameter (and 'END_POINT' parameter if necessary), use this: 'START_POINT': f"{startlon},{startlat} [EPSG:4326]", 'END_POINT': f"{endlon},{endlat} [EPSG:4326]" I guess, processing.run should be located in for loop. import processing layer_anfang = QgsProject.instance().mapLayersByName("MVG_2016_Wetter_Januar"...


3

Since QGIS 3.18, no need for third party to geocode from Nominatim or Google Maps (not demonstrated below as you need an API key) as there is a class dedicated for this purpose in PyQGIS Below, a recipe for Nominatim import json from qgis.core import ( QgsNominatimGeocoder, QgsGeocoderContext, QgsCoordinateTransformContext, ...


2

I usually have this problem when input and output path are the same. The error caused by the temp.shp file already exists in the output directory while the processing algorithm is saving the result. You should use a different directory or file name. According to the note in QGIS source code, it comes from OGR. My guess is that while the output file is being ...


0

My solution is: # -*- coding: utf-8 -*- from qgis.PyQt.QtCore import QCoreApplication from qgis.core import (QgsProcessing, QgsFeatureSink, QgsProject, QgsDatumTransform, QgsCoordinateTransformContext, QgsCoordinateTransform, ...


5

IMHO the issue with non-ASCII characters shall not arise anymore, due to improvements that were done in software since 2017 year. Perhaps the problem was about the PyQGIS's version or OS settings. Nowadays the geoding of 'Hacettepe Üniversitesi' object works well with both GeoPy (as was mentioned by @ivan) and "GeoCoding" Plugin using PyQGIS. ...


6

You can find the page type (if exists) with the following code : project = QgsProject.instance() composition = QgsPrintLayout(project) document = QDomDocument() template_file = open("C:/Users/Thysma/Documents/Stage/Composeurs/A4 Portrait.qpt") template_content = template_file.read() template_file.close() document.setContent(template_content) ...


2

You can try to use the following expression in a virtual field aggregate( layer:=@layer, aggregate:='count', expression:=geom_to_wkt($geometry), filter:=geom_to_wkt($geometry) = geom_to_wkt(geometry(@parent)) ) Then, duplicates are where the field calculated > 1


0

to change reference point of an item in the layout. for your example, you need to replace legend.setReferencePoint(QgsLayoutItem.LowerLeft) with : legend.setReferencePoint(6) # 6 is for the lowerLeft position you can change 6 with 0 to 8 with 0 for upperLeft(default reference point) / 4 : Middlecenter / 8 : LowerRight


3

You did not use setters for some content. There is maybe other remaining issues shp_uri ='C:/yyy.shp' shp = QgsVectorLayer(shp_uri, 'yyy.shp','ogr') QgsProject.instance().addMapLayer(shp) csv_uri="file:///C:/xxx.csv?delimiter=," csv = QgsVectorLayer(csv_uri, "Output","delimitedtext") QgsProject.instance().addMapLayer(csv) ...


0

Ok I'll give up, I tried everything I can think of. I deleted the object, I send the deleteLater signal to the metaObject of the task and so on. Nothing seems to work. I used QThreads, QgsTasks as custom classes and now I tried to use QgsTask.fromFunction, nothing is working. As soon as the layer is returned, the db connection is never closed. This is the ...


4

General advice: try via the QGIS GUI to achieve what you want then see how to implement it in PyQGIS. It's what I've done here. You do not need to use any code in particular, just using an expression for fill color style is enough. Without caring about using PyQGIS first, just try manually the following: On your layer you want to select, just set the fill ...


4

That cyan color is probably The Atlantic Ocean. Try the following way. It worked for me. test_data = 'testdata/airports.shp' canvas = QgsMapCanvas() vlayer = QgsVectorLayer(test_data, "test", "ogr") canvas.setCanvasColor(Qt.white) canvas.enableAntiAliasing(True) tms = 'type=xyz&url=https://tile.openstreetmap.org/{z}/{x}/{y}.png&...


2

You can set datum transformations using the project QgsCoordinateTransformContext accessible via QgsProject.instance().transformContext() For Proj 5, you get existing list from QgsProject.instance().transformContext().sourceDestinationDatumTransforms() For Proj 6+, you get existing list from QgsProject.instance().transformContext().coordinateOperations() ...


3

You can create a specific widget for a specific field to add to the attribute form when it appear. This solution is based on this code by Alexandre Neto and the accepted answer of this post, How to set and configure a value relation edittype in QGIS 2.14? by Matthias Kuhn. Here is the code : my_vector_layer = iface.activeLayer() #layer you want to add ...


3

You can offer a zip file with your plugin anyway over any platform. The user should then use in the "manage and Install Plugin" Dialog the option "Install from ZIP". To provide a ZIP just zip the folder with your plugin in it.


1

Not sure why you expect a standalone DBF. By default, if you export to a DBF file, you will lose the geometry along the transformation. You may transform the geometry as an "ordinary" attribute e.g like a WKT geometry column to keep the info (in your case line.geometry().asWkt() is a way to get it) You can find below a standalone recipe to do the ...


1

You can set the map extent based on your line layer like this : ms = QgsMapSettings() context = QgsRenderContext.fromMapSettings(ms) ms.setLayers([line_layer]) rect = QgsRectangle(ms.fullExtent()) rect.scale(1.2) ms.setExtent(rect) map.setExtent(rect) layout.addLayoutItem(map) Then when you add the legend you can compare the extent of your layers with your ...


12

You can add the CSV file, structured as below, as a layer using the following script: import numpy as np c = np.genfromtxt('C:/path/to/file.csv', delimiter=',') # check delimiter lats = c[:,0][1:] lons = -c[0][1:] # remove minus if you get a mirrored result data = c[1:,1:] crs = "EPSG:4326" # change if crs is different layer = QgsVectorLayer(&...


0

thanks to @KadirŞahbaz. It was question of upgrading to newest version of QGIS.


1

To do Jenks breaks directly, import a suitable Python library. Here's an example of some overlapping normal distributions. from jenkspy import jenks_breaks import numpy as np import matplotlib.pyplot as plt a=np.random.randn(1000)+1 b=np.random.randn(1000)+5 c=np.random.randn(1000)+12 d = np.concatenate([a,b,c]) histdata = plt.hist(d,100) breaks = ...


5

I used this code by Alexandre Neto and this answer to Value map from database in QGIS 3 to provide my answer. Here is a code that works for me : layername = "test_data" layer = QgsProject.instance().mapLayersByName(layername)[0] field = "bezirk" list_values = {"Bezirk 1":1, "Bezirk 2":2} def field_to_value_map(...


0

A solution I have tested in QGIS : Produce a line layer with the tool polygonstolines In your legend add this layer and errase the department and region layer. Activate the filter to show legend only for item inside atlas item (see capture under)


4

You can also use this structure: uri ="file:///" + Path + "/" + name + "?delimiter=,&crs=epsg:25831&xField=Easting&yField=Northing"


5

in your uri variable, Path/name is a literal string, not the variables Path and name. Try: uri ="file:///{}/{}?delimiter={}&crs=epsg:25831&xField={}&yField={}".format(Path, name, ",", "Easting", "Northing")


4

You need to change 'uiFileContent' to ''. The role of uiFileContent is to provide the name of the Qt Designer UI file if you are using a custom form (see https://github.com/qgis/QGIS/blob/2d1aa68f0d044f2aced7ebeca8d2fa6b754ac970/src/gui/vector/qgsvectorlayersavestyledialog.cpp#L171 to see from code where my affirmation comes from). If you don't have one, the ...


1

I am working on a simple plugin that allows to zoom to a specific coordinates and draw a mark with an annotation pop up (image below) : 1st : You have to declare a global List that will contain the markers drawn in the scene: Markers = [] 2nd : Function to delete Marker Point: def Delete_Marker(canvas): canvas = iface.mapCanvas() global Markers ...


Top 50 recent answers are included