New answers tagged

0

One dirty workaround would be to: Try to delete the file If it doesn't work, add it to a list of files to delete later try: os.remove(filename_to_delete) except PermissionError as e: with open('files_to_delete.txt', 'a') as list_file: # Append to the list list_file.write(filename_to_delete + '\n') At the next opportunity (click of ...


3

You might have some luck playing with the feature rendering order, ordering by is_selected() (though it is not always straightforward...) Alternatively, since the selection is only a color - and not a full style - is to change the size of the selected feature. It works well if all features have the same width. Click the epsilon icon beside the width, select ...


1

Change QgsMapLayerRegistry to QgsProject and fromPolyline to fromPolylineXY. fromPolyline expects QgsPoint but asPoint method returns QgsPointXY instances. Use like this: layers = iface.mapCanvas().layers() p_lyr = layers[0] l_lyr = layers[1] epsg = p_lyr.crs().postgisSrid() uri = "LineString?crs=epsg:" + str(epsg) + "&field=id:integer&...


1

QgsGeometry.fromPolyline want a list of QGSPoints, you are passing QGSPointXY's. Convert them with QGSPoints(thexypoint) So change the line: feat.setGeometry(QgsGeometry.fromPolyline([p.geometry().asPoint(), minDistPoint])) to: feat.setGeometry(QgsGeometry.fromPolyline([QgsPoint(p.geometry().asPoint()), QgsPoint(minDistPoint)]))


4

Try using format and IN operator like: list_of_sites = ('Arvika' , 'Avesta' , 'Arboga') #Note the tuple () and not list [] processing.run("qgis:selectbyexpression", {'INPUT':'C:/GIS/data/testdata/ak_riks.shp', 'EXPRESSION':'"KOMMUNNAMN" IN{0}'.format(list_of_sites), 'METHOD':0}) You can also list ids and select by them: lyr =...


1

My professor got in touch with a colleague who suggested that the issue was with the datatype. I changed the assignment code to this, and it solved the problem: attr_vals = np.array([[*coords, QVariant(randint(1, 5))] for coords in self._defined_points]) # set output field values for i in range(attr_vals.shape[0]): # if you're concerned, the order here does ...


0

QGIS methods that comment sample and identify query data from images stored on physical or network. Is it possible to iterate over all pixels in a raster layer from a WMS service ? Certainly it should be possible This question was answered here, you will see an option Reading data from raster layer obtained via WMS in QGIS


0

Thank you! I found a more poor solution: editing the name of one of the field of shapefile to "NAME" that is the default field take by the writer of the QgsVectorFileWriter.writeAsVectorFormat.


3

You can make it in one layer without any script and an additional layer for visualization purpose. Open "Layer Styling" (F7) Click plus button to add a new symbol layer Select the first symbol layer Set Symbol layer type to Centroid Fill Result:


2

If you want to extract the centroid as a new file, you can use centroid tool from Processing toolbox -> Vector geometry -> Centroids or from Vector toolbar menu -> Geometry Tools -> Centroids Run the tool and your will get the centroid of each polygon


1

I believe corvus is correct, by setting the attributes after you have added the feature you are updating the variable feat not the copy of that which was added to the sink I would try something like: feat = QgsFeature() feat.setGeometry(... feat.setAttributes(... self._sink.addFeature(feat)


3

No need for python. Copy-paste layer, Layer symbology - centroid fill:


1

What if you try the following code: layer = QgsVectorLayer("Point", "Test", "memory") crs = QgsCoordinateReferenceSystem("epsg:26912") layer.setCrs(crs) provider = layer.dataProvider() provider.addAttributes([QgsField('ID', QVariant.Int), QgsField('X', QVariant.Double), QgsField('Y', QVariant.Double)]) layer....


2

First, make sure you use a projected CRS There are 2 ways to calculate the area using the field calculator. using area which is always planimetric in the SRS of this geometry. From QGIS help: This differs from the calculations performed by the $area function, which will perform ellipsoidal calculations based on the project's ellipsoid and area unit ...


0

datasourceOptions are passed as a list of OGR creation options for the format. There are 2 ways: writeAsVectorFormatV2() and writeAsVectorFormat(). The first one is more neat in my opinion: options = QgsVectorFileWriter.SaveVectorOptions() options.driverName = "KML" options.fileEncoding = 'utf-8' options.datasourceOptions = ["NameField=ulica&...


1

You can add the combobox to a dialog window. After closing the dialog, print prints the selected items. from qgis.PyQt import QtGui from qgis.core import * planet_list = ["Venus", "Earth", "Mars", "Jupiter", "Pluto"] items = QgsCheckableComboBox() items.addItems(planet_list) dlg = QDialog() layout = ...


1

give the following code a go. I've changed the logic round a bit but it seems to work for me using the python window in QGIS 3.10 . When geopackage is true it saves out the 'in memory' layer, then uses the index of the field 'active' to set the default value to true. I don't know why, but if you set the default value for the field on the in memory layer ...


0

You need to install the event filter on the canvas' viewport. Event filters do not work as expected with mouse events on classes derived from QAbstractScrollArea (QgsMapCanvas, QGraphicsView, QTextEdit, etc...) Replace your code with the following, and it should work. class MyPlugin: def __init__(self, iface: QgisInterface): self.iface = iface ...


1

to_real is a function belonging to Field Calculator. Its Python equivalent is float. I assume newfieldname already exists in the attribute table. Use this script: csv = QgsProject.instance().mapLayersByName('nameoflayer')[0] with edit(csv): csv.addAttribute(QgsField('newfieldname', QVariant.Double)) for feature in csv.getFeatures(): # OR csv....


2

After a lot of changes in my terrible inefficient code, it's now working with all geometry types. I could add some caching to make it a little bit faster, but for the moment it's ok. import itertools, math, re from qgis.core import qgsfunction,QgsGeometry,QgsWkbTypes,QgsPointXY def createCustomLine(vertices,param): geom = QgsGeometry.fromPolylineXY(...


0

Your script has the definition of the processing algorithm class but in order for it to do something you need to instantiate the Trees class and use it. Add this at the end of the file and then run it: trees = Trees() feedback = QgsProcessingFeedback() context = QgsProcessingContext() parameters = {} #add your parameters here trees.initAlgorithm() trees....


8

Below a code with a simple QDialog with 2 comboBoxes (specialized for QGIS to display layers and fields) : class MyDialog(QDialog): def __init__(self, parent=None): super(MyDialog, self).__init__(parent) self._combo_lyr = QgsMapLayerComboBox(self) self._combo_fld = QgsFieldComboBox(self) self.layout = QVBoxLayout() ...


3

Below the code for select all solution lines between 0 (excluded) and maxdistance (excluded too). All POSSIBILITY features are inserted inside a spatial index (QgsSpatialIndex). A filter, thanks to the spatial index, with a maxdistance square around the feature of the layer STOP is applied for speed the process and select (intersects) only POSSIBILITY ...


0

The problem is due to the "Select by Expression" line that gives nothing (None)... for o in object: layer.selectByExpression('\"YOUR FIELD\"=\'%s\'' % o) QgsVectorFileWriter.writeAsVectorFormat(layer, filename + o + '.dxf', 'utf-8', layer.crs(), driverName='DXF', onlySelected=True, skipAttributeCreation=True) These lines should ...


3

Use the following script. Specify folder canvas = iface.mapCanvas() layer = iface.activeLayer() ids = layer.allFeatureIds() scale = 25000 delay = 250 # 250 milisecond folder = "/path/to/folder/" def prepare(): if ids: fid = ids.pop() canvas.zoomToFeatureIds(layer, [fid]) canvas.zoomScale(scale) canvas.refresh() ...


2

You forget some parameters, here is the documentation for joinattributebylocation You must add the parameters : METHOD:[0] DISCARD_NONMATCHING:False And the parameter PREDICATE should be PREDICATE:[0] if you only want intersects Edit: If you've already launched the algorithms with the GUI you can copy the Python code using the processing History (Ctrl+Alt+...


0

The easiest way to change the output layer name in your script would be to edit the output parameter and change 'Output layer' to whatever you want e.g. self.addParameter( QgsProcessingParameterFeatureSink( self.OUTPUT, self.tr('My output') ) )


0

Simple version updated for QGIS3 import processing listLayers = QgsProject.instance().mapLayersByName('Points') processing.runAndLoadResults("native:mergevectorlayers", {'LAYERS':listLayers, 'CRS':3006, 'OUTPUT':'TEMPORARY_OUTPUT'})


1

I found the solution looking at this site: https://issues.qgis.org/issues/21109 By default I have "clip features" checked. This function apply a limit of calcs to only the objects (or part of them) on the screen. So disabling this I solved. To obtain something like the image attached I used a simble composed like this Where the first character ...


1

Found the solution. Turned out that the algorithm_id from documentation is not correct, as hovering over the algorithm name in the QGIS Processing Toolbox revealed that the algorithm is named: 'native:joinbynearest'. Didn't know that trick before so I always looked up the algorithm_id in the online documentation.


1

It seem that QGIS import the data correctly, if it look different it's because it's not symbolized (QGIS use random color on default symbology without any label) , you will need to do it manually or to find some pre-made QGIS style file to achieve the look you're after. If you happens to read and understand french (or are not put off by automated translation)...


3

This question was answered here Getting Layer Properties of QGIS on standalone application using PyQGIS API It seems that the layer properties dialog is not accessible via PyQGIS but its individual parts are. For example, try this on a vector layer, especially as you point out the symbol layer = iface.activeLayer() d = QgsLayerPropertiesWidget(...


0

Use zip and enumerate: import os in_folder = '/home/bera/GIS' files = ['b1.tif', 'b2.tif', 'b3.tif', 'b4.tif'] files = [os.path.join(in_folder, f) for f in files] out_folder = '/home/bera/GIS/out' for e, (r1,r2) in enumerate(zip(files,files[1:]),1): outraster = os.path.join(out_folder,'Out_{0}_{1}.tif'.format(e,e+1)) processing.run("gdal:...


1

I'm not really up on Python, but I see you're not including the full path to the FME executable. Could that be the issue? i.e. it can't find FME It's also good practice to do if you have multiple FME versions installed (I know a lot of users who do that) because depending on the PATH the wrong version might get run.


2

QgsMapLayerRegistry has been depreciated as of QGIS 3 as per this answer QGIS API Documentation The way to do this using QGIS 3.# is as follows: First add the in memory layer to the project QgsProject.instance().addMapLayer(myMemoryLayer) Then remove the map layer from the project QgsProject.instance().removeMapLayer(myMemoryLayer.id())


4

If a line has only two vertices or all vertices are collinear, delaunayTriangulation returns an empty geometry. I don't know how to control collinearity, but you can check how many vertices a line has. lines=QgsProject.instance().mapLayersByName("lines")[0] for line in lines.getFeatures(): n = len(list(line.geometry().vertices())) delaunay ...


1

What I believe is, (I may be wrong) that this happens because when you run a plugin the scripts are compiled and the files created, with extension .pyc are saved in the py_cache folder of your plugin. But is Python supposed to be an interpreted language? Yes, but when you import a module, in this case os, that module is compiled in the .pyc file. In the ...


7

You can flip them using Python: import re layer = iface.activeLayer() #Click layer in table of contents unflipped_field = 'wktstring' #Change flipped_field = 'wktflipped' #Change. This text field will be calculated with edit(layer): for f in layer.getFeatures(): #For each row in the attribute table oldval = f[unflipped_field] #Fetch unflipped ...


0

This workaround works when you don't have to compose a lot of maps because each time you have to manually configure your legend. For me this was eventually too time-consuming and error prone. Another (quite complicated but more automated) way to replace the icons in the legend is to go to "layer properties / legend". There you check "text on ...


1

Try this code: linelyr = QgsProject.instance().mapLayersByName('Single parts')[0] #Change to match you layername lineidfield = 'id' #Change pointlyr = QgsProject.instance().mapLayersByName('New scratch layer')[0] #Change pointidfield = 'id' #Change max_distance = 500 #Change. It is the maximum distance to search for points to snap to d = {} #Dictionary to ...


Top 50 recent answers are included