New answers tagged

1

I prefer adding rasters described from the QGIS docs which I've incorporated into your script in addition to importing a couple more required classes: import glob, os from PyQt4 import QtGui from PyQt4.QtCore import QFileInfo rast_path = "/home/user/Desktop/data/gsi/output" rasters = glob.glob(os.path.join(rast_path, "*le.tif")) print(rasters) for raster ...


0

Here is probably the best solution I have found, it has made very easy thanks to http://www.qgistutorials.com/en/docs/running_qgis_jobs.html. First thing you need to do is create a batch file, call it "launch", and enter the following Then you create your GIS Standalone Python script, hopefully, this is more complex than mine, but this is just to show you ...


1

To set "Draw line only inside polygon" using python I used props['draw_inside_polygon'] = '1'


2

I am running a batch file first. call "C:\OSGeo4W64\bin\o4w_env.bat" set PATH=%PATH%;C:\OSGeo4W64\apps\qgis\bin


3

Here is how I solved the issue, it’s a bit of work, but you can now import the modules without hassle, I created a Python Script, that uses the module subprocess, to write an osgeo4w command called ‘python-qgis’ Its nothing complicated, here it is I called it NotePadPlus.py (No real reason for calling it that) I then call this script from the osgeo4w ...


1

I’m facing the same problem. I have not found a real solution, but I found out, that in content of the build in variable __name__ changes. It is “qgis.user” one time and “startup” the other. So you can work around the problem by: import qgis if __name__=="qgis.user": qgis.utils.iface.actionShowPythonDialog().trigger() print "Welcome chump"


0

The Leaflet html file is not a GIS layer and cannot be added to QGIS via pyQGIS. The html does reference various kinds of GIS layers, e.g. geojson, wfs, wms which may be loaded to QGIS via pyQGIS. There are many examples of this on this site and on the web how to add these layers to QGIS via pyQGIS. Load a GeoJSON layer with QGIS's Python module http:...


2

Not sure how to modify the interface of such scripts but you could use an example script like the following where the Enter_field parameter has a default string of ID and if a field name matches this, it prints this field name otherwise it will print the one that is selected in the Or_select_field parameter: ##Example=name ##Input_layer=vector ##...


2

Your escaping isn't write quite right. It should be: (\"accdate\" >= '1990-01-01' AND \"accdate\" <= '1992-12-31') (You have some extra "s) Also note that: iter = lyr.getFeatures(request) ids = [i.id() for i in iter] lyr.setSelectedFeatures(ids) selected_feats = lyr.selectedFeatures() Is quite inefficient. Try: iter = lyr.getFeatures(request) ...


2

The general logic for setting border color is: # black polygon with red border symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) layer_style = {} layer_style['color'] = '0, 0, 0' layer_style['size'] = '2.5' layer_style['color_border'] = '255, 0, 0' symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style)


1

This worked for me from A note on configuring your IDE on Windows and tere is available information for Eclipse and Pydev, I just like using Pyscripter If you used the OSGeo4W Installer, you can find this under the bin folder of your OSGeo4W install. Look for something like C:\OSGeo4W\bin\qgis-unstable.bat. For using Pyscripter IDE, here’s what you have ...


3

The widgets which you are referring to are leftovers from Qt3. QGIS at the moment is based on Qt4 (which exists since 2005 and has seen end of life in December 2015) and is soon to be updated to Qt5 (2016/2017). Ten years ago, when it was about moving applications from Qt3 to Qt4, a Qt3Support module has been introduced to ease the migration. However, ...


2

I now found a solution to my problem, although it's not the most elegant one. I got access to the elements by calling the actions() method of the view menu: vm = iface.viewMenu() panels = [i for i in vm.actions() if i.title() == 'Panels'][0] toolbars = [i for i in vm.actions() if i.title() == 'Toolbars'][0] Unfortunately the plugin will be used in ...


8

There are a couple of different approaches to that: Start a new project iface.newProject() Add a layer Whenever a new layer gets added to the mapcanvas, the welcome page will disappear Change the configuration In contrast to the other two approaches, this changes the configuration of the QGIS installation permanently. # 0: Welcome page # 1: Most ...


1

Presuming iter is something like iter=iface.activeLayer.getFeatures(), behind the loop name_dot contains the name of the last feature returned by the feature iterator. This must be passed to the QgsExpression via string formatting like expr = QgsExpression('"name"=\'%s\'' % name_dot) (Field names in double quotes, string in single quotes) Here is a ...


1

When a canvas changes its extent a extentsChanged signal is emitted. When you connect this signal to a method (called slot), then you are able to run this method whenever the extent changes. To deploy this mechanism I altered your code in the following way. # Declare a global variable to hold the reference to QGIS canvas canv = None # here comes your ...


1

In the print composer, enable atlas and use point layer as atlas coverage layer. Set the map item to be controlled by atlas, and choose the fixed scale Back in the QGIS's main window, for each layer that you want to filter according to a certain distance to the point use the rule based symbology and use the following rule within($geometry, buffer(@...


3

As mentioned in the comment, you could create a model from the Processing Toolbox but if you want to create a script, you could use the following which creates the start_lat field and updates it for each layer (comments are included which hopefully will help): # Import required module to create field from PyQt4.QtCore import QVariant # For each layer in ...


0

Not sure about connecting your plugin to the Python Console but you could just incorporate your script inside your plugin so that it can be executed from the interface. For example, if you have a push button with the objectName pushButton, you could add the following to your plugin_name.py file: def script(): # your_code self.dockwidget.pushButton....


-1

Seems like there might be an issue when you: Save the output as a temporary file and Check the Open output file after running algorithm option. I would suggest saving the output as a normal file instead of a temporary one, works for me.


3

Not sure why you are getting that error, here is another option to add the column using psycopg2: import psycopg2 conn = psycopg2.connect("dbname = 'dbName' port = '5432' user = 'postgres' host = 'serverName' password = '********'") cur = conn.cursor() sqlQuery = "ALTER TABLE tableName ADD COLUMN newColumnName numeric;" cur.execute(sqlQuery) conn.commit() ...


0

You can also create a Vector Grid To Create the Vector Grid using the extents of the Vector Layer, we use: processing.runalg('qgis:vectorgrid', extent, step_x, step_y, type, output) from https://docs.qgis.org/2.8/en/docs/user_manual/processing_algs/qgis/vector_creation_tools.html#create-grid Here is the code on how to achieve the desired result, please ...


0

You can use the following dialog if you need only style: QgsRendererV2PropertiesDialog Usage: dlg = QgsRendererV2PropertiesDialog(layer, QgsStyleV2.defaultStyle(), embedded=False) dlg.setMapCanvas(canvas) dlg.exec_()


2

after adding some print statements after each line I managed to work out that it's symbol.changeSymbolLayer(0, symbol_layer): bool QgsSymbolV2::changeSymbolLayer( int index, QgsSymbolLayerV2* layer ) { QgsSymbolLayerV2* oldLayer = mLayers.value( index ); if ( oldLayer == layer ) return false; if ( !layer || !layer->...


1

I will reply myself. This is not a direct aproach, but a workaround that it works: import subprocess subprocess.call(["spatialite_tool", "-i", "-shp", "/xxxx/xxxxx/xxxxx/xxxxx/PARCELA_xxxxx", "-d", "/home/xxx/xxxx/xxxxx/villar.sqlite", "-t", "Parcelas", "-g", "Geometry", "-c", "UTF-8","-s","3042", "--type", "MULTIPOLYGON"])


0

1) Yes and more see the doc 2) To retrieve output 2 possibilities : if you specify a path of the output it will set it as you mentiion it. ex : processing.runalg("qgis:union",layer1,layer2,"C:\path\to\your\shp") Second solution set the path None and it will write for you in the temp but you need to get it in a variable like so. The variable will be a ...


4

It looks like your issue might be caused by as simple syntax error. The correct syntax is if __name__ == '__main__': (with double underscores around main) That if statement is essentially used to check whether the file is being executed as a standalone script or if it has been imported by some other python script. Anything inside the if statement will only ...


1

I'd assumed the prefix path was correct because I didn't need to set it in the console version. Using print app.showSettings() showed me this was a false assumption. When running from R, it printed as: Application state: QGIS_PREFIX_PATH env var: Prefix: /usr/lib/R/bin Plugin Path: /usr/lib/R/bin/lib/qgis/plugins Package Data Path: /usr/...


0

Try using the following: from PyQt4.QtGui import QDockWidget, QMenu, QToolBar main_window = iface.mainWindow() # To get "Panels" (in fact, we echoed their title) print([i.windowTitle() for i in main_window.findChildren(QDockWidget)]) # To get "Toolbars" (in fact, we echoed their title) print([i.windowTitle() for i in main_window.findChildren(QToolBar)]) # ...


2

Your issue is in the URL. I retrieved the "right" one from https://data.gov.uk/dataset/flood-map-for-planning-rivers-and-sea-flood-zone-2 INTERFACE%3DENVIRONMENT--86ec354f-d465-11e4-b09e-f0def148f590 seems to act as a token for authentication to WMS service. Try below code (tested on my machine) urlWithParams = 'contextuaWMSLegend=0&crs=EPSG:27700&...


1

Just now only I find that while reading a line from a text file, \n will be there at the right end. I checked that value which was read from text file by using 'print' command. In print command, the \n is not displayed a character. Hence I confused. Now the problem has been solved by using rstrip() function.


1

There's a couple of methods which I use (note that it may not be the most efficient solution): (using Combo Box) - Add the following line before you populate your combo box: self.dockwidget.comboBox.clear() Then when you add a new layer, close your plugin and open it again, the combo box should be re-populated with the new additions. (using ...


1

You may not be calling the correct algorithm. first you are looking at the qgis merge processing.alghelp("qgis:mergevectorlayers") later on you're calling a non-existing saga algorithm processing.runandload("saga:mergeshapeslayers", files.pop(0), ";".join(files), out) the saga merge algorithm is called "saga:mergelayers"


2

Not sure if there is a plugin for this but you could run the following code in your Python Console which: Creates a new memory layer (you can define the type and crs). Iterates through each layer in the ToC and adds the attribute fields. Fetches all selected features in each layer and writes it to the memory layer. Saves the memory layer as a shapefile (...


3

I figured it out! It was something very small. Basically, the layers you would like to see displayed on the canvas is provided through canvas.setLayerSet(list_of_layers). # total list of layers actually displayed on map canvas canvas_layers = [] # load vector layers for files in os.listdir(source_dir): # load only the shapefiles if files.endswith("...


1

from qgis.core import * import gdal import qgis.utils QgsApplication.setPrefixPath("C:\OSGeo4W64\apps\qgis", True) qgs = QgsApplication([], True) qgs.initQgis() print QgsApplication.showSettings() layer = QgsVectorLayer('C:\Users\path to your shape\CB.shp', 'CB', 'ogr') if not layer.isValid(): print "Layer failed to load!" else: print "...


2

It is best to not include spaces when defining your parameters: ##Networking=group ##lIn=vector #lOut=output vector from qgis.core import * v = processing.getObject(lIn) #[...the rest...] If you run the above code now (notice I commented out the output vector since nothing is being passed to it), it should run without errors.


1

Yes, it is possible by using a QgsFeatureRequest with 'setFilterRect' method. The argument of this method is a QgsRectangle object obtained for visible part of Map Canvas with its 'extent' method (QgsMapCanvas class). I tried out my approach with this code: layer = iface.activeLayer() mapcanvas = iface.mapCanvas() rect = mapcanvas.extent() request = ...


0

I'm using Ubuntu 14.04, QGIS 2.8.1-Wien and python2.7. Feature.attributeMap() does not work. After much struggles with the undocumented way of implementing new ArcProperter's, here is my working solution. Also serves as a rogue documentation. class SpeedFieldProperter(QgsArcProperter): """ (attributeIndex, defaultSpeed=2.71828, ...


1

You need to import it in this way in the header of the corresponding Python file: from qgis.core import QgsRasterBandStats If you have other classes being imported from qgis.core, you can list them: from qgis.core import class1, class2, ..., QgsRasterBandStats


1

To Create the Vector Grid using the extents of the Vector Layer, we use: processing.runalg('qgis:vectorgrid', extent, step_x, step_y, type, output) from https://docs.qgis.org/2.8/en/docs/user_manual/processing_algs/qgis/vector_creation_tools.html#create-grid Here is the code on how to achieve the desired result, please note this will work on all vector ...


2

I have this function to remove a group and all his layers. I think is nearly what you want. def removeGroup(name): root = QgsProject.instance().layerTreeRoot() group = root.findGroup(name) if not group is None: for child in group.children(): dump = child.dump() id = dump.split("=")[-1].strip() ...


0

This should do it: class PointTool(QgsMapToolEmitPoint): def __init__(self, canvas): QgsMapToolEmitPoint.__init__(self, canvas) def canvasReleaseEvent(self, mouseEvent): qgsPoint = self.toMapCoordinates(mouseEvent.pos()) print('x:', qgsPoint.x(), ', y:', qgsPoint.y()) As your question is possibly a duplicate to this post.


2

Is Python a requirement? If I understand what you want, you can do this in the QGIS UI, in the raster layer properties:


7

I found this other thread which was helpful How do I set layer transparency in QGIS 2.0 with Python? It seems like there should be a shorter and more efficient way, but I tested this and it works: print 'Start' active_layer = qgis.utils.iface.mapCanvas().currentLayer() raster_transparency = active_layer.renderer().rasterTransparency() ltr = ...


4

It sounds like a profiling tool might be of interest. However in the scenario you gave, it's possible that the GUI signal doesn't trigger python code. But this might help with python plugins (which includes processing and plugin manager, which are also written in python) Luckily python 2.7 comes with a profiler (actually, two - profile and cProfile) In ...


2

Default values are accessible via the data provider, so this may work for simple cases: provider = activeLayer.dataProvider() newFeature.setAttribute(0, provider.defaultValue(0))


1

Guess it was easier than I thought, I just had to create a list of QgsMapLayers from a group I want excluded in the QgsMapLayerComboBox: root = QgsProject.instance().layerTreeRoot() other_group = root.findGroup('Other group') layers = [] for group in other_group.children(): for layer in group.children(): layerList = QgsMapLayerRegistry.instance()...


1

Accessing R symbols in packages that are syntactically invalid in Python can be done through __dict__. Here: r_as = methods.__dict__['as'] See the documentation for rpy2: http://rpy2.readthedocs.io/en/version_2.8.x/robjects_rpackages.html#importing-r-packages


1

As I noted in my comment, try: uri.setConnection("host_name","5432","database_name", None, None, authConfigId = "4zoa91a") This plugin has an example using this method: https://github.com/bstroebl/DataDrivenInputMask/blob/master/ddmanager.py



Top 50 recent answers are included