53

You can run a QGIS Processing algorithm in standalone (no GUI) mode in this way: import sys from qgis.core import ( QgsApplication, QgsProcessingFeedback, QgsVectorLayer ) # See https://gis.stackexchange.com/a/155852/4972 for details about the prefix QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis() ...


17

Finally found the proper way of running processing algorithms in PyQGIS standalone scripts. This answer is based on answers to Problem with import qgis.core when writing a stand-alone PyQGIS script and to Error: Algorithm not found, which is in turn based on a Qgis-dev mailing-list discussion. I suggest you to follow the work flow given in Problem with ...


17

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


14

I think Nathan W's answer is out of date. I was able to run QGIS (version 2.6) python scripts from the command line (Nathan's option 4) using the following commands. man qgis qgis -nologo --project /path/foo.qgs --code /path/foo.py


11

To complement Luigi's answer, this is how you can use the Layer Tree View for adding a legend (also known as Table of Contents or ToC) to your application. After you create your canvas in your standalone PyQGIS application, you need to create a QgsLayerTreeView. For that, you need a model, and for the model you need the layer tree root. Additionally, you ...


11

To avoid "layer is not valid" errors you should carefully set your QGIS prefix path. The prefix path must be set to let QGIS know where to find resources such as data providers and the reference system database. If you look at your QGIS installation, you should be able to access lib/qgis/plugins on Unix (or just plugins on Windows), relative to the ...


10

Yes - processing.run accepts a "feedback" argument, which must be an instance of a QgsProcessingFeedback subclass. If you construct your own feedback object to pass to this function, you can connect to the progressChanged signal and handle progress reports: def progress_changed(progress): print(progress) f = QgsProcessingFeedback() f.progressChanged....


10

On the one hand, QgsMapCanvas is a class. You can always create new canvas objects from it (as you did already in your second attempt). On the other hand, iface.mapCanvas() is an instance, an object of the class QgsMapCanvas. iface.mapCanvas() is initialized when you load QGIS app with GUI (Python should be enabled to use it), and refers to the main canvas ...


7

Being very keen on the TDD paradigm, I've spent some time putting together a dummy-interface (based on some code fragments I found on the internet) which enables calling QGIS and QGIS-plugins standalone. The interface I came up with looks as follows and I used it for all my unit-tests since: # coding=utf-8 """QGIS plugin implementation. .. note:: This ...


7

yes, see for example: GRASS and Python On scripting GRASS GIS: Building location-independent command line tools Python Scripts For GRASS GIS Using Python scripts that call GRASS modules or access GRASS layers from outside the GRASS.app with Mac OS X: a little summary How to access vector coordinates in GRASS GIS from python?


7

Update for Nathan's option 4: (Windows, QGIS 2.18 Las Palmas) To print QGIS help document, qgis --help To open QGIS, load a project, then, run a python script. qgis --nologo --project c:/path/to/projfile.qgs --code c:/path/to/code.py These commands should run on OSGeo4W Shell without problems. Edit QGIS 3.18 also works. Always use this command to see all ...


7

This answer is based on answers to Problem with import qgis.core when writing a stand-alone PyQGIS script and to How can I access `processing` with Python?. I suggest you to follow the work flow given in Problem with import qgis.core when writing a stand-alone PyQGIS script to enable your QGIS libraries in your OSGeo4W Shell. Once you have your QGIS ...


7

If you keep getting non valid layers, even defining them correctly, you're probably missing the QGIS prefix definition in your script (in case that you work out of QGIS). qgis_prefix="/usr" QgsApplication.setPrefixPath(qgis_prefix, True) QgsApplication.initQgis() If you work on Windows, your qgis_prefix should be something like this: qgis_prefix="C:\...


7

Add two following lines before qp = QgsProject.instance(): qgs = QgsApplication([], False) qgs.initQgis() then, add the next line to the end of the script: qgs.exitQgis() An additional warning: You should convert ImageExportSettings() into PdfExportSettings() since you export the layout to pdf. Otherwise, you will get this error: QgsLayoutExporter....


6

This code works in my Python Console: from qgis.core import QgsRasterLayer from PyQt4.QtCore import QFileInfo def StringToRaster(raster): # Check if string is provided fileInfo = QFileInfo(raster) path = fileInfo.filePath() baseName = fileInfo.baseName() layer = QgsRasterLayer(path, baseName) QgsMapLayerRegistry.instance()....


6

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


6

Start with: symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) renderer = QgsSingleSymbolRendererV2(symbol) Now you have 10 types of fill: Simple fill, QgsSimpleFillSymbolLayerV2 Gradient fill, QgsGradientFillSymbolLayerV2 Centroid fill, QgsCentroidFillSymbolLayerV2 Line pattern fill, QgsLinePatternFillSymbolLayer Point pattern fill, ...


6

When defining a new memory layer, you need to include one of the following as the data source: Point - For a point layer. LineString - For a line layer. Polygon - For a polygon layer. So in your case, you should replace: mem_layer = QgsVectorLayer("Lines?crs=epsg:4326&index=yes", "duplicated_layer", "memory") with mem_layer = QgsVectorLayer("...


6

The following script generates a simple form. You can use it in your standalone PyQGIS application to display attributes for a given feature. You can also specify fields to be displayed (or not to be displayed). from qgis.PyQt.QtWidgets import * class FeatureForm(QWidget): def __init__(self, layer, feature, only=None, exclude=None): ...


5

Non-valid layers are most of the times due to a wrong QGIS prefix definition. Please try with: qgis_prefix="C:\\Program Files\\QGIS Wiena\\apps\\qgis" QgsApplication.setPrefixPath(qgis_prefix, True) Which should go right before this line: QgsApplication.initQgis() Now your tested layers should be valid.


5

Based on this Very old help you want to use your IStandaloneTableCollection IStandaloneTableCollection pColl = ArcMap.Document.FocusMap as IStandaloneTableCollection; IStandaloneTable pThisTable = pColl.StandaloneTable[0]; // the first table pColl.RemoveStandaloneTable(pThisTable); ArcMap.Document.UpdateContents(); //update ...


5

It seems you need to set the QGIS prefix path, as I explain in Loading raster layer using PyQGIS? and Failed to create memory layers in QGIS application on Linux


5

I tested your code and stripped the problem down to the paths you are using. The error seems to be the forward slashes (/) that confuse your windows python installation. You should use backslashes on windows and use them as escaped symbol (eg. double backslash \). I updated your code with the paths of my system (an OSGeo4W64 installation), you can change ...


5

My GDAL_DATA environment variable was wrong, it had a line break (\n) at the end causing my error. I fixed it by forcefully changing the environment variable to remove the line break. QgsApplication.instance().initQgis() appears to add line breaks to the end of all my environment paths. I have patched this by replacing the line break in each variable ...


5

To use native algorithms in a standalone application, you need to add the provider using: QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) It would be like this: from qgis.analysis import QgsNativeAlgorithms import processing from processing.core.Processing import Processing Processing.initialize() QgsApplication.processingRegistry()....


5

You can execute the following code in the Python Console of QGIS. from PyQt5.QtCore import QVariant # Step 1 : Adding the Area field layer = QgsVectorLayer("C:/Users/ja/Inne/Desktop/treningowawarstwa.shp", "your_layer", "ogr") provider = layer.dataProvider() area_field = QgsField("Area", QVariant.Int) provider....


4

To copy all contents of a plugin folder to QGIS plugins folder, you can use a batch script below (see code comments starting with rem). What the script does in short is to copy contents of the plugin folder from a path to the QGIS plugin path. However, if the folder already exists, it overwrites it. @echo Off set PLUGIN_PATH="%USERPROFILE%\.qgis2\python\...


4

This should be enough to get the extent of your Shapefile: layerPath = path_dir + "Input district shapefile\\" + "District.shp" extent = QgsVectorLayer( layerPath, '', 'ogr' ).extent() The result is a QgsRectangle object, which has xMinimum(), xMaximum(), yMinimum(), and yMaximum() methods.


4

Struggled a bit for last 2 days. Abandoned XML approach. Able to accomplish first 2 tasks. Need to check how I can accomplish setting WFS,WCS parameters Create .qgs file dynamically Add Legend and Layers to the .qgs file and save Set WFS,WCS parameters in the .qgs file code below from xml.dom.minidom import Document import string import os import sys ...


4

I had to make minor changes to the script provided by @gcarrillo to include the OSGEO4W64 path (I had to re-install QGIS via the OSGEO4W64 installer as I used the standalone installer initially) and to include double-slashes. Here is the final script and many thanks to everyone for their help: import os, sys, glob # Prepare the environment from qgis.core ...


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