Hot answers tagged

7

You can define a function which adds the project filename as an attribute and connect this function with the event that adds features. You can use the following code, change the name of the field to whatever you choose (I used Name) and paste it into the Python Console. Now whenever you add a new feature, the field will be populated with the current project ...


6

My solution involves a PyQGIS script that is faster and more effective than a workflow involving snapping (I gave it a try too). Using my algorithm I've obtained these results: You can run the following code snippets in sequence from within QGIS (in the QGIS Python console). At the end you get a memory layer with the snapped routes loaded into QGIS. ...


5

I did it in ArcGIS, surely can be implemented using QGIS or simply python with package capable of reading geometries. Make sure that roads represent network, i.e. intersect each other at the ends only. You are dealing with OSM, I suppose it is the case. Convert proximity polygons to lines and planarise them, so they become a geometric network as well. ...


4

cur.execute(sql) rows = cur.fetchall() for row in rows: print row or for one record: row = cur.fetchone() print row


3

I would use a Line Edit widget. Inside your run() function put something like: self.selectedLayer = self.iface.activeLayer() # Adjust this to your situation self.selectedLayer.selectionChanged.connect( self.printSelectedArea ) Then define your printSelectedArea function: def printSelectedArea( self ): area=0 for f in ...


3

In order to solve this question, we need to use timers or something that delays the execution of the script, so the canvas can reflect the layer arrangement at the time the map is exported. In other words, if you don't use timers you'll end up with 3 PNG images with the same content because everything will happen too fast. In the QGIS map, set the map ...


3

It's not a bug. It's a feature. :D Check boxes in the layer tree have three states (see Qt docs): Qt::Unchecked 0 Qt::PartiallyChecked 1 (some children are checked and some are not) Qt::Checked 2 Therefore, the setVisible() function expects a Qt.checkState value, not a boolean value. By chance, it seems that False is ...


3

You can enable automatic updates of feature attributes with the following PyQGIS script. In this example, say you have a polygon layer named myPolygons, which has, among others, fields named area and perimeter. Copy and paste the code into the QGIS Python Console. # Initialize required variables myLayer = QgsMapLayerRegistry.instance().mapLayersByName( ...


3

I think if you want to change attributes using the dataProvider() method, it must retrieve the written table before you can edit it (i.e. the attributes of the new feature must be saved beforehand). Instead, you can just directly change the attributes without having to access the dataProvider(): layer = qgis.utils.iface.activeLayer() for f in ...


3

I got it to work on my GNU/Linux machine by replacing this code block from your script: QgsApplication.setPrefixPath('/usr', True) QgsApplication.initQgis() by this one: qgisApp = QgsApplication([], True) QgsApplication.setPrefixPath('/usr', True) QgsApplication.initQgis() The first line of this code block initializes the QgsApplication class, making ...


3

I have done a similar stuff, mine does work. Check it out. It is for 2.14 qgis. If you are locked you should probably check http://docs.qgis.org/2.2/en/docs/pyqgis_developer_cookbook/raster.html (see the version number on the link) from PyQt4.QtCore import QSize from PyQt4.QtGui import QPainter, QImage, QColor from PyQt4.QtCore import QFileInfo from ...


3

There is a handy option in the QgsLayerTreeGroup class that you can use: findGroup. It traverses the whole tree. So, in your case, this would be enough: root = QgsProject.instance().layerTreeRoot() subGroup1A = root.findGroup('Sub_Group_1A') for child in subGroup1A.children(): if isinstance(child, QgsLayerTreeLayer): child.layerName()


3

Some vector formats are read-only in QGIS. So, first check if your Cropped layer is read-only: Cropped.isReadOnly() If not, then you could use this code snippet to delete all features whose Name attribute value is already in the roads list (note the handy function to delete all those features in a single step): features = Cropped.getFeatures() ids = [ ...


3

It's a known issue, which will be fixed when QGIS moves to QGIS 3.0 development (since the fix could potentially break existing plugins). To work around it, you need to force a copy of the geometry: geom = QgsGeometry( lay.getFeatures().next().geometry() ) Technical explanation below: Calling just geom = lay.getFeatures().next().geometry() results ...


2

You need to use layer.source() to get the paths of the rasters which is required by the zonal_stats module. Your code should look like: from rasterstats import zonal_stats layers = QgsMapLayerRegistry.instance().mapLayers().values() for layer in layers: stats = zonal_stats("/home/myshape.shp", layer.source())


2

The following documentation resources should ease your PyQGIS development experience: A diagram of the main PyQGIS relationships (by Thomas Gratier): https://raw.githubusercontent.com/webgeodatavore/qgis-class-diagram/master/diagramme_principal.png Searchable documentation of PyQGIS classes (by SourcePole): http://geoapis.sourcepole.com For example, the ...


2

Okaaayy I found ! the problem comes from the Qgis browser... the thing where you can explore your folders and stuff... If the folder you want to delete is opened in there it wont delete it... so I just need to find a way to ensure that the folder is not opened in the browser !


2

I realize you're asking for a QGIS method, but bear with me for an arcpy answer: roads = 'clipped roads' # roads layer hexgrid = 'normal-hexgrid' # hex grid layer sr = arcpy.Describe('roads').spatialReference # spatial reference outlines = [] # final output lines points = [] # participating grid vertices vert_dict = {} # vertex dictionary hex_dict = {} # ...


2

If you were to split the road line into segments where each segment was completely contained by the hexagon, your decision on which hexagon line segments to use would be whether the distance from the split road segment's centroid to each hexagon side's midpoint was less than half the diameter of the hexagon (or less than the radius of a circle that fits ...


2

(Ok then!) To add a few more details: UTM coordinates are usually positive, and limited to a certain range. In your case (WGS84 / UTM zone 37N (EPSG:32637)), x range is 166021.4431 to 833978.5569, and y range is 0 to 9329005.1825. Your coordinates seems widely out of bounds, although technically not impossible (that's what put me on the track). Moreover, ...


2

Look at QgsExpressionContextUtils (https://qgis.org/api/classQgsExpressionContextUtils.html). The method you need is QgsExpressionContextUtils.setProjectVariable, e.g. QgsExpressionContextUtils.setProjectVariable('myvar','hello world')


2

Works! from threading import Timer class RepeatedTimer(object): def __init__(self, interval, function, *args, **kwargs): self._timer = None self.interval = interval self.function = function self.args = args self.kwargs = kwargs self.is_running = False self.start() def _run(self): ...


2

Because you need to load manually the layer on the Map View of QGIS. For example, in my case of the next shapefile: I ran your script (slightly modified to be tested on my system): from qgis.analysis import QgsGeometryAnalyzer lyr =iface.mapCanvas() layer = lyr.currentLayer() ...


2

Perhaps something like the following? layer = qgis.utils.iface.activeLayer() for feature in layer.getFeatures(): attrs = feature.attributes() for i, j in list(enumerate(attrs)): print "value" + str(i + 1) + " = " + str(j)


2

To print the field value you need to provide the field name or index: Field Name: for feature in LYR.getFeatures(): print feature['myFieldName'] Field Index (first field starts at zero): for feature in LYR.getFeatures(): print feature[1] # this is the second field in the table


2

I suppose backslashes need escaping in Python but forward slashes should work also with Windows nowadays. And you can't warp directly into ECW. Test with gdalwarp shows that: gdalwarp -of ECW test.tif test.ecw Output driver `ECW' not recognised or does not support direct output file creation. The following format drivers are configured and support direct ...


2

I noticed your comment on a previous post just now. You need use warpreproject, not warpproject. import processing processing.alghelp("gdalogr:warpreproject") ALGORITHM: Warp (reproject) INPUT <ParameterRaster> SOURCE_SRS <ParameterCrs> DEST_SRS <ParameterCrs> NO_DATA <ParameterString> TR <ParameterNumber> ...


2

This actually doesn't require scripting. You can use print composer and atlas serial printing for that. It allows to iterate both over geographical features or also over layers or visibility preset groups. See http://www.qgis.org/en/site/forusers/visualchangelog212/index.html#feature-data-defined-control-over-map-layers-and-style-presets for more details.


2

These two code statements will provide the table path to the db name: print iface.activeLayer().dataProvider().dataSourceUri().split('|')[0] or print lyr.dataProvider().dataSourceUri().split('|')[0]


2

The algorithm expects (in the first argument) the input raster paths using a semicolon as separator. Don't add any blank space after the semicolon. Your script could be just 2 lines long now: import processing merj = processing.runalg('gdalogr:merge','H:/pyQGIS/DATA_U6/mdt_483.tif;H:/pyQGIS/DATA_U6/mdt_508.tif', False, False, ...



Only top voted, non community-wiki answers of a minimum length are eligible