New answers tagged

0

One method could be to set flags when requesting data such as ignoring geometry data of features and only focusing on retrieving data for a single attribute field. Also I think there might be a typo in your expression as you included "AND" at the very end of your expression. You could try testing the following to see if it makes any difference: table1 = ...


1

You could use the following to change the first page of your layout to A3 landscape: layout = QgsProject.instance().layoutManager().layoutByName('Example') pc = layout.pageCollection() pc.page(0).setPageSize('A3', QgsLayoutItemPage.Orientation.Landscape)


1

you need change this property in the page layout, not in pdf setting. I add a proof of concept: page = QgsLayoutItemPage(layout) page.setPageSize('A3')


1

Now I found the solution It's not a problem with my code It's problem in my PyCharm with pyEnv. To solve this problem you can check path of your Python File and Check your Python interpreter.


0

Run this from console, click anywhere onto the map. To deactivate it, click another tool eg Pan class MapTool(QgsMapTool): def __init__(self, iface, canvas): super(MapTool, self).__init__(canvas) def canvasReleaseEvent(self, event): point = self.toMapCoordinates(event.pos()) print (point.x(),"/",point.y()) tool=MapTool(...


0

#active layer is a point layer: feat = next(iface.activeLayer().getFeatures())#get first feature geo= QgsGeometry.asPoint(feat.geometry())#get the geometry of the feature pxy=QgsPointXY(geo) print (pxy.x(),pxy.y())


0

You can use the polygonize tool and click the green arrow on the right hand side of the input layer parameter, this will force the tool to iterate over all the lines in your layer. Afterwards you will have to merge the results back. Cheers.


1

You could use something like the following: # Get group group = QgsProject.instance().layerTreeRoot().findGroup('Drawings') # Iterate group to get list of layer names layers = [layer.name() for layer in group.children()]


1

You need to install this Python module in the Python that QGIS uses. I use Windows so I have a .bat that opens a cmd. (change OSGEO4W_ROOT using your path) @ECHO OFF set OSGEO4W_ROOT=D:\OSGeo4W64 set PATH=%OSGEO4W_ROOT%\bin;%PATH% set PATH=%PATH%;%OSGEO4W_ROOT%\apps\qgis\bin @echo off call "%OSGEO4W_ROOT%\bin\o4w_env.bat" call "%OSGEO4W_ROOT%\bin\...


1

Solved thanks to Andreas Müller by adding: sys.path.insert(0, os.path.expanduser('~/') + 'path/to/scripts/folder') to the main script before importing modules.


1

With QGIS 3, extract from https://qgis.org/api/api_break.html setMapUnits() was removed. The map units are dictated by the units for the destination CRS. You now only need map.setDestinationCrs(QgsCoordinateReferenceSystem(srid))


1

You're not actually using your "ms" variable anyway, so setting the layers there has no effect... What you need to do is call map.setLayers(). See https://qgis.org/pyqgis/3.8/core/QgsLayoutItemMap.html#qgis.core.QgsLayoutItemMap.setLayers


3

You need to use string formatting in order to loop on each road type. Therefore, change the following line layer.selectByExpression('"RoadMntnc"= road', QgsVectorLayer.SetSelection) to layer.selectByExpression('"RoadMntnc"= \'{0}\''.format(road), QgsVectorLayer.SetSelection)


1

I had the same error with QGIS 3, by writing multiple times to a vector layer with "qgis:zonalstatistics" processing function. The layer wasn't in the registry: registryLayers = QgsProject.instance().mapLayers().keys() legendLayers = [ layer.layerId() for layer in QgsProject.instance().layerTreeRoot().findLayers() ] layersToRemove = set( registryLayers ) - ...


0

In addition to Jonny's answer and TheGrudges's comment to that: It's still not fixed in PyCharm 2019.2


0

The answer above from cm1 works well with PyCharm 2018. However, with PyCharm 2019 (2019.1 and 2019.2) it won't work anymore. See also PyCharm 2019 is not working with QGIS anymore


2

I figured out another solution (QGIS 3.4): startup.py from PyQt5.QtCore import QSettings,QStandardPaths from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QLabel, QWidget, QSplashScreen,QApplication import os try: s = QSettings() s.setValue("PythonPlugins/BufferSelection",True) except: pass try: widgets= QApplication.allWidgets() ...


0

Make sure you are catching the feature object which is passed by the featureIdentified signal, and using it when you define your self.identify slot function like this: def identify(self, feat): geom = feat.geometry().constGet()[0] end_point = QgsPointXY(geom[-1]) X = end_point.x() Y = end_point.y() # do something with end_point, X, or Y ...


0

Your layer's coordinate system is probably a Geographic one (meaning Ellipsoidal here), therefore the distance calculated in degree dimension. To solve this issue, first you have to a pick a proper Projected coordinate system, and save the layer in that coordinate system (Save as, change CRS). You can find a proper Projected coordinate system at https://...


4

The $length expression function states that The length calculated by this function respects both the current project's ellipsoid setting and distance unit settings. For example, if an ellipsoid has been set for the project then the calculated length will be ellipsoidal, and if no ellipsoid is set then the calculated length will be planimetric. ...


1

Use addMapLayer(layer,False), which will add a layer without showing it memlay = QgsVectorLayer("Point","myLayer", "memory") QgsProject.instance().addMapLayer(memlay, False) #False is the key sgroup.addLayer(memlay) Then you can simply add it to an existing group without cloning etc.


0

I posted a similar message earlier in the “add comment” section, and was suggested to re-post this as an answer. Deleting the \Roaming\QGIS folder worked a while, but the very same problems came back after I turned on all my plugins under the Plugins -> Manage and Install Plugins - > Installed. At this point I realized the problems may be related to the ...


0

Finally I found the answer in Add layer to a QGIS group using Python from Germán Carrillo (many thanks). Thankfully you don't have to clone etc your layers which results in strange behaviour. def create_slayer(tiep, lname, sgroup): memlay = QgsVectorLayer(tiep,lname, "memory") QgsProject.instance().addMapLayer(memlay, False) #False was the key ...


0

To install this python module or any other you can follow this flow. Create a .bat (py3_qgis.bat) with this lines, (change your QGIS 3 path) @ECHO OFF :: QGIS path set OSGEO4W_ROOT=D:\OSGeo4W64 set PATH=%OSGEO4W_ROOT%\bin;%PATH% set PATH=%PATH%;%OSGEO4W_ROOT%\apps\qgis\bin @echo off call %OSGEO4W_ROOT%\bin\o4w_env.bat call qt5_env.bat call py3_env.bat ...


0

There's a workaround to add a layer in a group. You need to add to the layer tree and then move it in your chosen group.


1

There are a few problems with your code. Firstly, when you iterate over the items in your layout, you are trying to assign multiple label objects to a single variable. That 'labels' variable will only return one label object. In order to collect all the label objects so you can iterate over them again, you need to store them in a list instead. Secondly, ...


1

As ndawson explained in his comment, the startRender and stopRender implementations of the base class need to be called in the overrides. The following code now works, without the need to reimplement the renderFeature function. from qgis.core import QgsWkbTypes, QgsSymbol, QgsFeatureRenderer, QgsRendererAbstractMetadata, QgsApplication from qgis.gui import ...


1

With Joseph's insight this is what worked. input_uri = 'file:////media/path/points.csv?delimiter=,&xField=long&yField=lat&crs=espg:103172&spatialIndex=no&subsetIndex=no&watchFile=no' output_uri = '/media/spath/out_paths.shp' lyr = QgsVectorLayer(input_uri, 'New CSV','delimitedtext') params = { 'DATE_FORMAT' : '', 'GROUP_FIELD' : '...


2

Assuming you have only one print layout active, you could use the following to get all labels and the text they contain: labels = QgsProject.instance().layoutManager().layouts()[0].items() for x in labels: if isinstance(x, QgsLayoutItemLabel): print(x) #To print the text inside the labels print(x.text())


2

I think the problem is how you are accessing your feature geometry. Try using the constGet() method to access the feature geometry like this: geom = f.geometry().constGet() first_vertex = QgsPoint(geom[0]) print(first_vertex.z()) This should return a valid z value. By the way, I would recommend using the QGIS algorithm 'Drape (set z-value from raster)' ...


2

A little digging and I found what works. layers = QgsProject.instance().mapLayersByName('point') layer_select = layers[0] # first layer named LAYER_NAME. layers = QgsProject.instance().mapLayersByName('line') layer_to_select = layers[0] # first layer named LAYER_NAME. for f in layer_select.selectedFeatures(): geom = f.geometry() to_select = [] ...


1

RQGIS only works with QGIS2, and I assume that you have already installed QGIS3. Hence, use RQGIS3, you can find it under https://github.com/jannes-m/RQGIS3. So far, it is not on CRAN due to an RStudio issue under Linux/Mac.


1

Try using processing toolbox function "Snap geometries to layer" or try using spatial index


0

Aren't your path incorrect? I believe you would want something like "gdal_translate -b 1 " raster_input_dir + "/" + raster_filename + " " + outputDir + "/" + lyr.name() + "test.ecw"


0

For implementing a custom contrast enhancement for raster images you need to define several things. Assuming you have a raster with a QgsSingleBandPseudoColorRenderer and you want a QgsSingleBandPseudoColorRenderer, to implement a custom contrast enhancement for the raster images you need a color list of colors (as ColorRampItem objects) generated on a ...


1

It works fine this way: try: processing.run('native:shortestpathpointtopoint', params) except: QMessageBox.critical(None, '...', '...!')


1

Off course after I've asked the question I know the answer. After using Searchcursor I still have to iterate through it. Changed the last line in the else to this and it works: with arcpy.da.SearchCursor(inl, '*', where_clause=ftext) as feats: featureIterator = [] for f in feats: ...


0

I've been struggling with something similar, and here is my understanding of how the imports work: With 'import comDef' and 'from comDef import * ' is looking for the comDef python module (comDef.py file) in the Libs folder for that instance of python. QGIS has it's own Python instance, so in the case of QGIS3 on my Windows PC this location is here: "C:\...


1

You could use the following example which puts your code in a function and then a button is created on a toolbar which is connected to the function. You can test this using the Python Console: def loadMap(): if not 'MapMyIndia' in [layer.name() for layer in QgsProject.instance().mapLayers().values()]: urlWithParams = 'type=xyz&url=https://a....


1

Your Windows path is incorrect, it should be: C:/Users/You/AppData/Roaming/QGIS/QGIS3/startup.py This would explain why you are not receiving any error messages because you should be. If you have a small number of simple functions, it might be better to store them all in your startup.py so you can just load this single file: from qgis.core import ...


1

Here is a function to convert a QgsRasterLayer to a numpy array without GDAL through using the block method of the QgsRasterDataProvider(link): from numpy import array def convertRasterToNumpyArray(lyr): #Input: QgsRasterLayer values=[] provider= lyr.dataProvider() block = provider.block(1,lyr.extent(),lyr.width(),lyr.height()) for i in ...


2

As per Joseph's request please find attached alternative version to allow the script to run in GNU Parallel. It assumes QGIS3 and Debian. The method I have found best is to design it as follows: convert the internal file calls in the python code to arguments create an OS script wrapper (e.g. bash) to run the python code (to make sure it can be run without ...


3

Similar to what @Joseph pointed out in the comments, in the lines where you set a and b did you mean to use "f" instead of "feature"? Try the updates below: for feature in selected_feature: a = feature['parkeer_approx'] b = parking_capacity[feature.id()-int(1)]['parking_capacity'] feature["parkeer_approx"] = a - b layer.updateFeature(...


2

when trying to run a script outside of the python console you must define iface and processing by adding from qgis.utils import iface from qgis.core import (QgsProcessing) import processing Should run now outside the python console from the processing toolbox


5

The easiest way to do this would be to return the FlagNoThreading flag for your algorithm, and disable background processing. def flags(self): return super().flags() | QgsProcessingAlgorithm.FlagNoThreading


4

I have found and fixed the final errors. I tried changing how each algorthim parameter got its value. By changing the code below: inputfield = QgsProperty.fromField("InputPointID") targetfield = QgsProperty.fromField("TargetPointID") To this: inputfield = QgsProperty.fromValue("InputPointID") targetfield = QgsProperty.fromValue("TargetPointID") It has ...


1

I also found my scripts worked fine in the QGIS 3 Python Console, but when run in standalone PyQIS v3 they do not work. I found it does not accept strings as inputs and the only workaround is to keep trying the different field types the algorithm accepts as inputs (like you suggested using QgsVectorLayer), but even then, depending on the algorithm, it still ...


4

You can try this approach: The basic workflow is: -Lookup index values of fields in your attribute table. -Create a dictionary containing the field indexes as the keys and the attribute information as the values. -Call changeAttributeValues() on the layer data provider, passing another dictionary containing a feature id as the key and the attribute map ...


1

Like this to address only the selected features: fids = join_layer.selectedFeatureIds() request = QgsFeatureRequest() request.setFilterFids(fids) with edit(join_layer): for feature in join_layer.getFeatures(request): feature.setAttribute(feature.fieldNameIndex('Postcode'), feature['HomePostcode']) join_layer.updateFeature(feature) ...


0

In the code source you can read The extension argument allows for specifying a file extension associated with the parameter (e.g. "html"). Use fileFilter for a more flexible approach which allows for multiple file extensions. Only one of extension or fileFilter should be specified, if both are specified then fileFilter takes precedence. Hence, you have to ...


Top 50 recent answers are included