New answers tagged

3

My answer will be nearly the same as the previous one but you can avoid to loop all the settings and only obtain PostgreSQL connexions with from PyQt4.QtCore import QSettings s = QSettings() s.beginGroup("PostgreSQL/connections") print s.allKeys() print s.value("GEODEMO/username") s.endGroup()


5

From the documentation Using PyQGIS in custom application, you need to add the paths to where QGIS is installed and load its providers before you can use its features and tools: from qgis.core import * # supply path to where is your qgis installed QgsApplication.setPrefixPath("/path/to/qgis/installation", True) # load providers QgsApplication.initQgis() ...


1

For a standalone application (without an interface) [Wien 2.8.1] use: canvas.scene().removeItem(vertexMarker) Found in PyQgis Developer Cookbook/ Rubberbands and vertex markers


4

To get the information you want, you need to use the QSettings class. This uses a hierarchical structure, like the Windows registry. If you have the latest version of QGIS, you can see this hierarchy using Settings>Options>Advanced The following code works from the Python Console. I've not tried this from a plugin or outside of QGIS, so some additional work ...


2

Below should work. The key part is the assignment d[(mainArray == 0)] = 0 setting all the items to zero in a new array where mainArray is zero. Sounds like your rasters might be spatial so the projection setting stuff is important too. Cheers. # # ----- create output raster # outfilename = outputFolder + '/zeros.tif' driver = ...


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")} ...


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 = ...


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)


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 ...


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 ...


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 ...


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 ...


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

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) ...


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() ...


0

I managed to get it working by updating the .spec file to copy the missing qgis plugin folder into the .exe bundle. I also had to add a check in the code to see if i'm running bundled so I can choose the correct path to the bundled qgis_plugins folder. I assume a better long term fix would be to make this into a runtime hook but for now this is sufficient.


0

The code was correct; I had to refresh the layer: layer.triggerRepaint()


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

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

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'.


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

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 ...


0

For QGIS 2.8.2 with Processing plugin 2.9.0: processing.runalg("qgis:joinattributesbylocation", layer1, layer2, u'contains', 1, 'sum', 1, None) For QGIS 2.12.2 with Processing plugin 2.12.2: processing.runalg("qgis:joinattributesbylocation", layer1, layer2, u'contains', 0, 1, 'sum', 1, None) (note the extra parameter for "precision")


0

Try this from the QGIS standard Python console: import IPython; IPython.__version__


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, ...


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

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 ...


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.


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.


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 ...


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), ...


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__ == ...


0

I believe the issue is that your table "dbo.My_View" is not defined in a GEOMETRY_COLUMNS table in the MSSQL database. If you use OGR2OGR or Qgis to import a layer into MSSQL, that will automatically create the table for you. Once you have it, fill out the proper values for the table you are trying to add to QGIS. In this case, "dbo.My_View". Once you ...


0

Perhaps more updated answer from Rob Lodge from qgis.core import QgsRasterTransparency print 'Start' active_layer = l = qgis.utils.iface.mapCanvas().currentLayer() raster_transpareny = active_layer.renderer().rasterTransparency() ltr = QgsRasterTransparency.TransparentSingleValuePixel() tr_list = [] ltr.min = 0 # Or another value ltr.max = 0 # Or ...



Top 50 recent answers are included