New answers tagged

0

You can directly produce features of concentric buffers as polygons by using linspace method from numpy python module. As you have in your attributes table 1440 features, I know that, in your case, polygon sides number is 360 for each one of your concentric buffers. Algorithm for extracting points for each polygon features is easily inferred; as it can be ...


2

You have another function for doing this: from processing import execAlgorithmDialog params = {} # A dictionary to load some default value in the dialog execAlgorithmDialog('qgis:extractbyattribute', params)


2

That's no how you call processing.run. You should check out the official QGIS documentation Basicaly, processing.run expects the algorithm identifier, and a dictionnary containing the processing parameters. This should work: processing.run( "qgis:mergevectorlayers", { "LAYERS": filelist, "OUTPUT": "P:/GIS/Basemapping/Topographic ...


2

The following script writes all fields from vector layers into a CSV file. Perhaps you have to make some changes, it is just a quick idea how to start: import csv group = QgsProject.instance().layerTreeRoot().children() layers = [ item.layer() for item in group ] #list of all layers for layer in layers: if layer.type()==0: #check if layertype is vector ...


1

In this case I found that I can use setTransformOriginPoint before my setRotation line to specify the point of rotation. self.rubberband.setTransformOriginPoint((self.rect.width()),(self.rect.height())) self.rubberband.setRotation(mapRotation) I thought it should be half hight, width bit that spun it off centre (code below) self....


2

If you use itertools python module and print all possibilities for intersections, you will have 2 points (0 as type geometry) and 4 MultiLineString geometries (1 as type geometry). You are only interested in MultiLineString geometries and target polygon id (in my case it was 0) for determining features indices of your "blue" polygons. So, with following ...


1

# Your layer named dimensioning layer_dimensioning = QgsProject.instance().mapLayersByName("dimensioning")[0] # Provider in order to access your layer features provider_layer_dimensioning = layer_dimensioning.dataProvider() result = processing.run("qgis:explodelines", {'INPUT':temp_lines,'OUTPUT':'memory:'})["OUTPUT"] # Start edition layer_dimensioning....


0

Have you tried the Line Intersections tool in QGIS? I've used this tool to create intersections for my road centerline layer, as well as to create intersection points between railroads and road centerlines. The documentation kinda sucks, and I ran the tool manually, but it created points at the intersection of two line segments crossing, not where they met ...


1

The error is not in the scripts themselves but in the structure created. Having a folder called myplugin and a file also called myplugin. QGIS cannot distinguish between them when reloading. When changing the script name, the reload worked correctly. myplugin ├── _init__.py ├── myplugin_main.py ├── myplugin_algorithm.py └── ...


1

This is my answer: layer = iface.activeLayer() feature = layer.getFeatures() d = QgsDistanceArea() d.setSourceCrs(layer.crs(), QgsProject.instance().transformContext()) d.setEllipsoid(QgsProject.instance().ellipsoid()) for feat in feature: print((d.convertLengthMeasurement(d.measureLength(feat.geometry()),1))*1000)


1

As @KadirSahbaz suggested I added import processing at the beginning. The code below works. from qgis import processing from qgis.processing import alg from qgis.core import QgsFeature, QgsWkbTypes, QgsField, QgsFields, QgsPointXY, QgsGeometry, \ QgsCoordinateReferenceSystem, QgsProcessingMultiStepFeedback, QgsVectorFileWriter, QgsVectorLayer, \ ...


1

It looks like your issue lies in the way you've tried to format your output and write it to your file. First, instead of opening the file in binary writing ('wb') mode, try standard writing mode ('w'). Once you've done that, there's no need to encode your output string - just use output_file.write(msgout). Note that this doesn't explicitly specify an ...


1

In the Postgres DB, you can define the constraint to cascade the deletions: when you delete from table tray, it also deletes from tableB. This instruction should be set on the foreign table CREATE TABLE tableB ( id serial PRIMARY KEY, trayId integer REFERENCES tray (trayId) ON DELETE CASCADE ); Alternatively, you can do this yourself. Before ...


2

['blnFl'] is a list which includes one string item. A list which includes an item returns always True in if clause. Add next line before if ['blnFl'] is True: blnFl = self.parameterAsBool(parameters, "blnFl", context) And change if ['blnFl'] is True: as if blnFl is True: blnFl = self.parameterAsBool(parameters, "blnFl", context) if blnFl is True: ......


1

If you use just QgsDistanceArea.measureLength(feat), you get an error: first argument of unbound method must have type 'QgsDistanceArea'. That means you need to create an object of QgsDistanceArea d = QgsDistanceArea() Then you need to set ellipsoid. Use QgsEllipsoidUtils::acronyms() to get a list of all known ellipsoid acronyms. If you don't set ellipsoid,...


1

One way could be, d = QgsDistanceArea() d.setEllipsoid('WGS84') layer = iface.activeLayer() feature = layer.getFeatures() for feat in feature: print( d.convertAreaMeasurement( d.measureLength(feat.geometry()), 1 ) )


0

You can use BulkVectorExport plug-in to save layers in your project to CSV (or to other output formats). In this case all columns are written to the text file, but you can use the Python sources of the plug-in to customize. Look for run function in bulkvectorexport.py, the QgsVectorFileWriter.writeAsVectorFormat function (in line 204) has an attributes ...


2

If you want to write all the values of the ycoord field into a .txt file, you can execute the following code in the Python Console of QGIS (change the parameters with your own): layer = iface.activeLayer() # your layer features = layer.getFeatures() # features of your layer with open('C:/Users/v.bre/Downloads/ycoord.txt','w') as my_file: # Change the path ...


2

I definitely recommend using the QGIS custom widgets. You should have a Qt Designer packaged with your QGIS installation which has these custom widgets available to drag and drop into a dialog like any other Qt widget. The following is for Windows (I'm not sure about other operating systems). Start typing Qt into the Windows search bar and select from the ...


3

I've changed names of variables to be more eligible/legible for other readers. def getPointFromFeature(self, featureID, layer): expr = QgsExpression("Id = '"+featureID+"'") selection = self.selectionByExpr(layer, expr) geom = selection[0].geometry() # removed asPoint() return geom def getDistances(self, point_geom, river_geom): d = ...


1

Firstly, you can extract selected polygons to memory, secondly convert them to lines, then explode the lines. This script works in QGIS 3.8, but it doesn't in QGIS 3.4.13: import processing layer = iface.activeLayer() selected = processing.run("native:saveselectedfeatures", {'INPUT':layer, 'OUTPUT':'TEMPORARY_OUTPUT'})["OUTPUT"] temp_lines = ...


1

Quite a bit more searching later, and I believe the answer is no. However I'm most of the way through implementing the above algorithm, and I believe it will work as written.


2

Try using something like the following where it is based on the new processing syntax. Create a Vector Layer input parameter in your modeler, set it so that it is not mandatory (i.e. it will be optional) and then use this as the input to the script. The script should check if the input is empty where it will create a dummy shapefile otherwise would use the ...


1

Replace the last line of your code with the last line of the following code. fet = QgsFeature() pt = QgsPointXY(92.5,22.5) points.append(pt) pt = QgsPointXY(93.5,22.5) points.append(pt) pt = QgsPointXY(93.5,23.5) points.append(pt) fet.setGeometry(QgsGeometry.fromMultiPolygonXY([[points]]))


2

Would extent() work? canvas = iface.mapCanvas() extent = canvas.extent() print(extent) Taking it one step further you can break the QgsRectangle object into its components: xmax = extent.xMaximum() ymax = extent.yMaximum() xmin = extent.xMinimum() ymin = extent.yMinimum()


1

You need to set a data-defined property. Unfortunately, the only such property you can set at the symbol level is the width. So, to set a data defined color, you must use the setDataDefinedProperty method of the QgsSymbolLayer In your case, you have only one symbol layer, so get it using symbol.symbolLayers()[0] layer = iface.addVectorLayer("/Users/usr/...


3

This line is causing the error msgout = '%s, %s \n' % (point["pcds"], layer.name()) Without seeing the data, I'm assuming your point file doesn't have a column named 'pcds' Renaming it to the correct column should solve the error.


1

You don't need iface to zoom to a layer. It's sufficient to set the map canvas extent as the layer extent. ... canvas.setExtent(vlayer.extent()) project.write(project_path)


2

The error is related with (0.5)*(extent.width). You try to multiply a float (0.5) by a method (extent.width). width doesn't call the method. To call a method, you have to use parentheses. So it has to be extent.width(). Also center.x and center.y have to be center.x() and center.y(). You used all in original code correctly, but missed in the next one. Try ...


1

I have found a solution. Loading the layer using QgsDataSourceUri loads the layer using the correct attribute table, and allows editing and saving of geometries: uri = QgsDataSourceUri() uri.setConnection({HOST},{PORT}, {DB}, {UID}, {PWD}) uri.setUseEstimatedMetadata(1) uri.setSrid("27700") uri.setWkbType(QgsWkbTypes.Polygon) uri.setDataSource({SCHEMA},{...


1

I know this is an old question but a new plugin has been created to take care of this issue. https://plugins.qgis.org/plugins/polystrip/ I am not the creator and do not take credit for the plugin.


3

The following minimal example is in a somewhat similar format to the post you linked to which should work for QGIS 3: # Interpolate points using QgsTinInterpolator pathToFile = "path/to/input.shp" layer = QgsVectorLayer(pathToFile, 'input','ogr') layer_data = QgsInterpolator.LayerData() layer_data.source = layer layer_data.zCoordInterpolation = False index ...


1

Could you try something like this for python file? C:\PROGRA~1\QGIS3~1.4\apps\Python37\python.exe c:/Users/user/Desktop/xx/run.py


3

You need to set the environment variables to run the QGIS python outside. In this case my QGIS installation is in D:\QGIS, so you should only change OSGEO4W_ROOT. @ECHO OFF set OSGEO4W_ROOT=D:\QGIS call "%OSGEO4W_ROOT%\bin\o4w_env.bat" call "%OSGEO4W_ROOT%\bin\qt5_env.bat" call "%OSGEO4W_ROOT%\bin\py3_env.bat" path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH% ...


2

To refresh all layers, you can use the following command : iface.mapCanvas().refreshAllLayers() In your case : self.iface.mapCanvas().refreshAllLayers() The following script work (I write out of a function) : from qgis.utils import iface layer_edit = [ 'Enveloppe concave', 'Sortie SQL','Channel'] for layers in QgsProject.instance().mapLayers().values()...


1

Add from qgis.utils import iface line to import section. Remove self.addParameter(QgsProcessingParameterVectorLayer('addlayer', 'myLayer', ...) line. And change all parameters['addlayer'] into iface.activeLayer().


1

import requests lyr = iface.activeLayer() count = lyr.featureCount() reqData = { "jsonrpc":"2.0", "method":"generateStrings", "params":{"apiKey":"myapikeygoeshere", "n":count, "length":20, "characters":"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", "replacement":True},...


2

absolutePath method of QgsProject gives you folder in where the project is. When concatenating folder and file name, you can use os.path.join to get rid of OS differences. import os project_path = QgsProject.instance().absolutePath() shapefile_path = os.path.join(project_path, "COB.shp") layer = iface.addVectorLayer(shapefile_path, "COB", "ogr")


4

You can use field_names = [field.name() for field in layer.fields()] to get field names or other field properties (length, type, comment, ...). If you just need names, it's sufficient to use field_names = layer.fields().names()


2

List field names - .dataProvider() method layer = qgis.utils.iface.activeLayer() # get active layer if not already set prov = layer.dataProvider() field_names = [field.name() for field in prov.fields()] for count, f in enumerate(field_names): print("{} {}".format(count, f)) Note: using layer.pendingFields() doesn't seem to work in QGIS 3 This fails: ...


3

You are missing the pyrsgis python module, which must be required by that plugin. Please execute either CMD, PowerShell, or Windows Terminal as Admininstrator. Ensure QGIS is completely closed. CD into the OSGeo4W python environment (C:\OSGEO4W\apps\Python37\) CD C:\OSGeo4W\apps\Python37 Issue the following python/pip command to install pyrsgis: .\...


1

For those who'd like to try the code above for the PyQGIS3 version, here is my adaptation (it works for the 'active layer' if run from the console ...). # provide file name index and field's unique values from random import randrange layer = iface.activeLayer() fni = layer.fields().indexFromName('nom') unique_values = layer.uniqueValues(fni) # fill ...


1

I think you should consider a new approach: not defining the output name inside the model (even if you think now that it will always be related to the input) if not using batch mode. This allows you to be flexible on the definition of the output name and use the Input name or use a new one if you need to. It is quite easy to give the output the name of the ...


1

The only solution I have found so far is to use the plugin Sort and Number. First get latitude and longitude for each point using Add Geometry Attributes then use the plugin. Input ycoord as 1st field and xcoord as 2nd field. This will had a column with the row number.


3

You need to append a forward slash in your dir so that it looks like: dir = "C:/Users/user/Desktop/xyz_data/" And as you figured out, you need three forward slashes when defining the file url: "file:///..."


2

One way of adding paint effects is to add another symbol layer for it. Here is a code snippet to produce following polygon. #Add layer coords = [(20, 60), (32, 60), (32, 70), (20, 70), (20, 60)] polygon = QgsGeometry.fromPolygonXY( [[ QgsPointXY( pair[0], pair[1] ) for pair in coords ]] ) layer = QgsVectorLayer("Polygon?crs=EPSG:4326", "polygon_0", "...


1

The missing piece was that I needed to initialise Processing like this: import sys from qgis.core import QgsApplication ## ADDED: # not sure why this can't just be an environment variable setting sys.path.append(r"C:\OSGeo4W64\apps\qgis\python\plugins") # Supply path to qgis install location QgsApplication.setPrefixPath("C:\\OSGeo4W64\\apps\\qgis", True) ...


0

You should use context variable @map_scale which will give you the scale of the current map being rendered. Also, worth noticing in recent QGIS, what are called labels callouts, which might solve your issue in an easier way:


2

Use the special value QgsProcessing.TEMPORARY_OUTPUT as the output parameter value, and the rest will all be taken care of for you. e.g. clipped_layer = processing.run("gdal:clipvectorbyextent", {'INPUT': id, 'EXTENT': canvasExtent, 'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT})['OUTPUT']


0

Case when "FID_Net"=minimum("class", "FID_Net") Then "FID_Net" Else 0 End This problem has been solved by using this expression on Qgis field calculator. But it takes about an hour to analyze 78000 field rows of data, if I know the sql syntax it would be easy to analyze in just few seconds.


Top 50 recent answers are included