Hot answers tagged

5

I use following intro for stand-alone applications: # the_app.py import os import sys from qgis.core import * from PyQt4.QtGui import * def main(): QgsApplication.setPrefixPath(os.environ['QGIS_PREFIX'], True) QgsApplication.initQgis() # app specific code ... QgsApplication.exitQgis() sys.exit(result) if __name__ == ...


5

There are 2 main reasons why a two raster with the same extent and the same pixel size have different size : 1) the pixel depth 2) the compression in your case, dividing by 2 might produce a float while your input is integer (e.g. unsigned 8bit). Furthermore, the input could be compressed while the output is not. For full control on the output type, you ...


4

Saving this in a Python file and using it in the --code arg should do what you need: from PyQt4.QtCore import * from PyQt4.QtGui import * import os from qgis.core import * from qgis.gui import * from qgis.utils import iface for comp in iface.activeComposers(): print comp folder = r"C:\temp" title = "testing" printer = QPrinter() ...


4

Great answer by @SIGIS! You could also use the following to set your current layer, set the expression and load the Attributes Table with the selected features: layer = qgis.utils.iface.activeLayer() exp = QgsExpression( "\"population\"< 2000" ) ids = [i.id() for i in layer.getFeatures(QgsFeatureRequest(exp))] layer.setSelectedFeatures(ids) ...


4

There's various way how to do it and depends on what you want. Solution 1 : with selection assuming you've already select your features : # My layer test Layer=QgsVectorLayer("path/to/shapefile.shp","Display name", "ogr") # list of selected features selected_features = [ feature for feature in layer.selectedFeatures()] Solution 2 : with the querie ...


3

You're close! The setGroupVisible function requires (int, boolean) as parameters (i.e. the integer you provided for your group as 0). Try the following: root = QgsProject.instance().layerTreeRoot() group1 = root.insertGroup(0, "PGB") legend = iface.legendInterface() legend.setGroupVisible(0, False)


3

Steven Kays answer in pyqgis. Just select the lines in your layer before running the script. The script does not support the linemerging so it can not work on layer with multilinestring #!python # coding: utf-8 # https://gis.stackexchange.com/questions/173127/generating-equal-sized-polygons-along-line-with-pyqgis from qgis.core import QgsMapLayerRegistry, ...


2

I solve the similar problem this way: from qgis.core import * from qgis.gui import * layer = QgsVectorLayer(self.shpFilePath, "Track", "ogr") crs = layer.crs() crs.createFromId(4326) layer.setCrs(crs) QgsMapLayerRegistry.instance().addMapLayer(layer)


2

The error QPixmap: Must construct a QApplication before a QPaintDevice seems to be related to the fact you don't declare a QApplication before your try/except statement. The other issue about try except is only about Python. You can manage error correctly with: try: # To be sure it fails import processing1 except Exception, e: print type(e), ...


2

Something like that exists only for the QGIS Processing Toolbox where you can look up the history/log in the corresponding menu entry. All other interactions are afaik not logged.


2

The example code above should work (coincidently with or without the 'grid.updateFeature(feature)'). The problem was in my actual code I was trying to pass Numpy datatypes and rather than throwing an TypeError, changeAttributeValue() just silently failed. Always remember to check your variable types when debugging!


2

The problem probably could be here: . . . out_rst.SetGeoTransform(g_x_min, g_pixelWidth, 0, g_y_max, 0, -g_pixelHeight) . . . because 'SetGeoTransform' method needs a list as parameter. Try out this: . . . out_rst.SetGeoTransform( [ g_x_min, g_pixelWidth, 0, g_y_max, 0, -g_pixelHeight ] ) . . . I hope that it helps Editing Note: I tried to ...


2

I think ideally layers which cover the same area should be in the same CRS before you load it in your application (i.e. re-save vectors and reproject rasters). This is important when conducting spatial analysis. But if it's just for displaying, you could use the following code to set the CRS for all loaded layers and the map projection (change the EPSG code ...


2

Thanks to @detlev for the idea of looking at the layer source: iface.activeLayer().dataProvider().dataSourceUri() gives u'/vsigzip/J:\\GIS\\Data\\OSMM\\6417514-NH2708-5i6.gz|layername=TopographicArea' It turns out that GML files are stored in a virtual file system vsigzip (http://erouault.blogspot.co.uk/2012/05/new-gdal-virtual-file-system-to-read.html) ...


2

This is only half an answer as the following code can be used to import waypoints, routes and tracks but not route_points or track_points (these seem to be replaced by the tracks layer). import os path = "path/to/gpx/folder" names = ["waypoint", "route", "track", "route_point", "track_point"] for dirpath, subdirs, files in os.walk(path): for f in ...


2

I finally found a solution. 1) Qgis does not provide a simple function to compute loxodromic bearing or distance ; the measureLine and bearing functions (and the measuring tool of the graphical interface) provide the orthodromic figures ((great circle); if no ellipsoid is set to QgsDistanceArea or if the flag ellipsoidalEnabled is False, the same functions ...


2

If you look at QgsZonalStatistics.Mean it's part of an enumeration - it's actually the integer 4. You're calling it as if it's a function. Try removing the brackets:- zoneStat = QgsZonalStatistics (polygonLayer, rasterFilePath, 'pre-', 1, QgsZonalStatistics.Mean) zoneStat.calculateStatistics(None) Note that these values are done as powers of two; to get ...


2

You initiate newGeom as GEOMETRYCOLLECTION, but in the loop you combine geometries. combine is the geometric union operation and as such has a much greater job than simply adding a geometry to a collection. It must check topological relationship on a low level, and if objects are disjoint it aggregates them to MultiPolygon geometries. When I interpret your ...


2

Perhaps you could use something like the following (untested) which uses the glob function to search for rasters in a given directory (you may need to import glob): def function(): myarray = np.array(src_ds.GetRasterBand(1).ReadAsArray()) rows = src_ds.RasterYSize cols = src_ds.RasterXSize BufferDistance = 15 IndexingSquare = ...


2

To get information on the changed features use signal committedGeometriesChanges. This gives you the feature id and new geometry of any changed feature of the layer you connect a handler to. As an example: def feedback(layerId, changedGeometries): for k, v in changedGeometries.items(): # v contains geometry and it's further usage is up to you ...


1

I'm not sure what low level I/O conflict was taking place, but the shapefile was in a folder that was set to sync with a cloud storage provider. I was writing to file at least every 30 seconds and the sync utility was dutifully attempting to keep up. It seems this would occasionally cause QgsFeatureIterator to grab a bad chunk of data and, after looking at ...


1

The code looks fine, but I'd expect the performance to get worse over time. Each time round the inner loop, you're combining the current feature's geometry with the union of all the previous matching features' geometries. At the start you'll have one simple geometry. Each time round the loop, the geometry gets more complex, so each time round the loop it ...


1

You can also use triple-quoted strings, this means you can leave your double quotes and single quotes (apostrophes) un-escaped. Can make things a little tricky to maintain, so if you can, leave one space padding at the start and end, like so expr = QgsExpression(""" "my_field" like '%something%' """)


1

Try something like this: expr = QgsExpression( " \"myField\"= 'valueILookFor' " ) or expr = QgsExpression( " \"myField\" LIKE 'valueILookFor' " ) Have to be careful with the quotes. Also, you can just use u'string instead of ur'string'.


1

Try using contrast enhancement to stretch the gray scale across a specified interval. # create a single band gray scale renderer with gray scale stretched # across the interval [0..66] renderer = QgsSingleBandGrayRenderer(rasterlayer.dataProvider(), 1) ce = QgsContrastEnhancement(rasterlayer.dataProvider().dataType(0)) ...


1

This error ImportError: cannot import name QPyNullVariant It indicates that the SIP API version is not set to version 2. When you write standalone python scripts, make sure that the very first import is import qgis The SIP API Version always needs to be set before any other PyQt code is executed. The qgis import takes care of that.


1

An exemple to complete snaileaters's anwser : def print_informations(layerTreeNode, checkstate): '''print some informations when a group or a layer is checked''' if checkstate: if layerTreeNode.nodeType() == 0: print "Group " + layerTreeNode.name() else: if layerTreeNode.nodeType() == 1: print ...


1

Here is some code to generate a histogram diagram for two layer attributes "attribute_1" and "attribute_2": def setHistogram(layer): # Set histogram and diagram settings: hist = QgsHistogramDiagram() ds = QgsDiagramSettings() dColors = {'attribute_1': QColor("cyan"), 'attribute_2': QColor("red")} ...


1

The problem is that the method is outdated since qgis 2.10 (or so). According to the QGIS API you directly have to use the .setRenderer() method.


1

This page has a good example of doing rule based renderer via python: Rule-based renderer The rule-based renderer styles features using a list of rules, defined by expressions. The rules are processed sequentially, with the first matching rule used to render a feature. The example below defines a new rule-based renderer for different ...



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