New answers tagged

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

I reproduced this in QGIS 2.14.2 on Ubuntu, both in Console and in a saved .py script. The issue you linked to has the answer - change your call from .geometry() to .geometryAndOwnership(). I tried that and it fixes the problem. According to the API docs this method is deprecated and you should use constGeometry() instead - but I find this also segfaults. ...


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


0

Maybe a little bit late but I had the same problem and I figured this out (assuming you want to close the first composer): activeComposer = iface.activeComposers() composer = activeComposer[0] composerWindow = composer.composerWindow() composerWindow.close()


0

Use QgsComposition.setPaperSize( width, height ). See https://qgis.org/api/classQgsComposition.html#a512d7c89fa0e76abb13b5395fae57069


0

Perhaps there is a solution to this on qtcentre.org: http://www.qtcentre.org/threads/32665-How-do-I-set-a-custom-page-paper-size-in-QPrinter (which can be easily ported to python) I think this is set up in the code line printer.setPaperSize(QSizeF(210,297), QPrinter.Millimeter)


1

I answer me myself. I don't like, but I only found this solution: I have used conditional function in label expression. "if" has 3 arguments (condition, label if true, label if not) This is the correct code from PyQt4.QtGui import QColor layer = iface.activeLayer() palyr = QgsPalLayerSettings() palyr.readFromLayer(layer) palyr.enabled = True ...


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


1

import os from PyQt4 import QtGui, uic from PyQt4.QtCore import pyqtSignal FORM_CLASS, _ = uic.loadUiType(os.path.join( os.path.dirname(__file__), 'my_dockwidget_base.ui')) class myDockWidget(QtGui.QDockWidget, FORM_CLASS): closingPlugin = pyqtSignal() def __init__(self, parent=None): """Constructor.""" super(myDockWidget, ...


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

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


0

Guess the answer was simpler than I thought. Had to insert everything into the run(self) function. So the following code works: def run(self): def test_print(): print 'It works!' self.dockwidget.pushButton.clicked.connect(test_print)


2

When you use QgsZonalStatistics, the results are are automatically added to the shapefile (look at Problem with calculating QGIS Zonal Statistics MEAN or Estadística zonal con PyQGIS: clase QgsZonalStatistics) vLayer = QgsVectorLayer("a_polygon.shp","a_polygon.shp","ogr") path = "test.tif" zoneStat = QgsZonalStatistics(vLayer, path,"", 1, ...


0

Apparently adding print(joinObject.memoryCache) ensures that all layers are cached. Not sure why but this seems to only work if you print the bool state of QgsVectorJoinInfo::memoryCache, otherwise only some layers are cached. Weird. Here is the code: shp = QgsMapLayerRegistry.instance().mapLayersByName( "Main" )[0] shpField = 'ID' root = ...


0

Not sure how to access it directly but you can read the .qgs project as a text file, search for <extent> and print the next 4 lines: myfile = open('path/to/project_file', "r") for line in myfile: if '<extent>' in line: for index in range(4): extent = myfile.next() print (extent).replace('\n', ' ')


1

Try this for current extent: bBox = qgis.utils.iface.mapCanvas().extent()


1

Thats what you need to add: import sys # where is the module sys.path.append("/Applications/QGIS.app/Contents/Resources/python/") sys.path.append('/Applications/QGIS.app/Contents/Resources/python/plugins') qpp = QgsApplication([], True) QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/PlugIns", True) QgsApplication.initQgis()


0

Hmm @GermánCarrillo's solution also worked for me. If you want to use ras1 and ras2 as input parameters then you can try the following: import processing ras1 = "H:/pyQGIS/DATA_U6/mdt_483.tif" ras2 = "H:/pyQGIS/DATA_U6/mdt_508.tif" merj = processing.runalg("gdalogr:merge", ras1 + ";" + ras2, False, False, 4,"H:/pyQGIS/DATA_U6/mdt_mosaico.tif")


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


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


1

Eugh, I guess one method is to: Search the children of Main_group, then Search the children of Sub_Group_1 and then Search the children of Sub_Group_1A. Basically repeating the loops, I'm hoping there is a much nicer and efficient way of accessing those layers but for now, here's the code I used: root = QgsProject.instance().layerTreeRoot() for child ...


0

It will allow specifying parameters which are supported by OGR but not (yet) by processing to allow full control for not yet supported features. GDAL(OGR) is a separate library and application. It is often shipped bundled with QGIS but developed independently. Its tools accept a range of parameters which are normally mapped to processing parameters. But ...


1

The return value of processing.runalg is a dictionary containing key, map pairs where the keys are defined by the algorithm. In the case of gdalogr:warpreproject there is one output with the name OUTPUT created which points to the location where the result is. To access it, you can use the following code: processing.load(reproj['OUTPUT']) About \ and / ...


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


1

Not sure about the examples in the "QGIS Python Programming Cookbook" but in the PyQGIS Developer Cookbook, we have the following example mapRenderer = iface.mapCanvas().mapRenderer() c = QgsComposition(mapRenderer) c.setPlotStyle(QgsComposition.Print) x, y = 0, 0 w, h = c.paperWidth(), c.paperHeight() composerMap = QgsComposerMap(c, x ,y, w, h) ...


1

I think the problem lies with using EPSG:3722. When I use this CRS, the reproject algorithm runs successfully but does not produce an output. Try changing this to another CRS and see if you get an output. If so then it means your code works and there's a problem with using EPSG:3722.


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

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.


1

Adding onto above (not enough points to comment) map.setMapUnits(QGis.UnitTypes.Meters) Does not work for me (version 2.14). I must reference meters with the index for that unit type, noted here in the API Docs. Using this works for me (0 = meters). map.setMapUnits(0)


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


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


2

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


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


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

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

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


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


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


0

Here the solution I found: I used a very small buffer (100 meters) around my points coordinates in order to create a geometry. Then I used the command Intersect from the Geo-processing Tools. The saved shape file reports each intersection between the two geometries in a different raw as I wanted.


0

I now use the function intersection. Returns a geometry representing the points shared by this geometry and other. This function gives me the desired result. See: QgsGeometry::intersection


1

When you intend to run PyQGIS scripts out of QGIS, you need to initialize a QgsApplication so that it loads data providers and other resources. The following code snippet should work: from qgis.core import * from PyQt4.QtGui import QApplication app = QApplication([]) QgsApplication.setPrefixPath("C:\\OSGeo4W\\apps\\qgis\\", True) # Adjust prefix path ...


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


1

There is a workaround using the processing.runalg() method, described in this post: Using in-memory vector layer with QGIS processing / SEXTANTE. EDIT: the script I copied was for vector clipping (not raster). I replaced it by GDAL's Clip raster by extent algorithm which does precisely what you want. You need to use the path to your raster as an input (and ...


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

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]


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


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 !


1

I would add a function which populates the year comboBox each time a feature is selected. For this you'll need to add a line in init to call the function: self.dlg.comboBoxName.activated.connect(self.populate_years()) And then something like: def populate_years(self): years = [] layerName = str(self.dlg.comboBox.currentText()) ...



Top 50 recent answers are included