I want to create geopackage file using PyQGIS (for example database.gpkg) with one layer (named &quot;myLayer&quot;). I've tried this writer=QgsVectorFileWriter(fileName,'UTF-8',layerFields,QgsWkbTypes.Unknown,QgsProject.instance().crs(),'GPKG',newLayer='myLayer')  but got an error ('newLayer' is an unknown keyword argument). I can't use writeAsVectorFormatV2 because I need to create file first and than add it to QGIS.
57955
How to add layers (vector or raster to an existing GeoPackage)? While loading an existing layer of a GeoPackage is quite trivial: path = '/home/matteo/geopackage.gpkg|layername={}'.format('admin') iface.addVectorLayer(path, 'admin', 'ogr')  I couldn't find information about adding them via PyQGIS.
88469
I'm making a plugin were i want to get the min and max value of a raster. When i tried the following code in the qgis python console it worked fine but in my plugin code i get the following error   ver = provider.hasStatistics(1, QgsRasterBandStats.All)  NameError: global name 'QgsRasterBandStats' is not defined   The code i m using is:      layer = self.iface.activeLayer()     renderer = layer.renderer()     provider = layer.dataProvider()     extent = layer.extent()      ver = provider.hasStatistics(1, QgsRasterBandStats.All)      stats = provider.bandStatistics(1, QgsRasterBandStats.All,extent, 0)      minum= stats.minimumValue     maxim = stats.maximumValue      self.dlg.lineEdit.addItems(minum)      self.dlg.lineEdit_2.addItems(maxim)       It look like QgsRasterBandStats isn't included in my python plugin. How can i include this?
26400
I am using Quantum GIS and the PostGIS dbms. I am able to call the PostGIS layer into QGIS but i am unable to add feature to it. I am using the method of adding features to a Shapefile but still it is not getting reflected in the layer, and I don't know how to save it to the PostGIS database if I am able to add the feature to the PostGIS layer.  I may not have used some technical term for this problem because i don't know what to call it, I am expressing the problem in my own terms.
5106
I am having trouble loading csv files into layers using QgsVectorLayer().  I know this looks like a repeat, but I have carefully read     and    but still cannot get it work.  An example of my data file, test.csv:  Index,y,x 0,37.7646618,-122.4960858 1,37.777494,-122.416311 2,37.717707,-122.3997056 3,37.732284,-122.498118 4,37.749998,-122.392333   My code:  import os import urllib  import pathlib from qgis.core import QgsVectorLayer  local_path = 'C:\dev\FCMS_conflation\data\TMC_nodes.csv' node_layer = 'test'  abspath = os.path.abspath(local_path) params = {'delimiter': ',',           'decimalPoint': '.',           'xField': longitude,           'yField': latitude}  uri = "%s?%s" %(pathlib.Path(abspath).as_uri(), urllib.unquote(urllib.urlencode(params)))  layer = QgsVectorLayer(uri, node_layer, "delimitedtext")   The formatted URI looks like:  [] uri &gt;&gt;&gt; 'file:///C:/dev/FCMS_conflation/data/TMC_nodes.csv?decimalPoint=.&amp;delimiter=,&amp;xField=longitude&amp;yField=latitude'   I have tried many variations of the parameters, including the crs and type. But no matter what I try, I cannot create a valid layer.  [] layer.isValid() &gt;&gt;&gt; False   I have verified that I can add the file using the QGIS gui. I even tried using the uri provided by layer.metadata from within the Python plugin.   I am using QGIS 2.10.1 on Windows 7 64-bit machine.
53340
I have just installed QGIS 2.6 and have installed the OpenLayers plugin. It lists the OpenLayers plugin in the installed tab, however, I can't add a layer to my project as it does not give the option to add an OpenLayers layer as previous versions do.  Does anyone know what is going wrong here?
89942
Shapefiles can mix simple POLYGONs and MULTIPOLYGONs in the same data source. Spatial databases like PostGIS and SpatiaLite are strict, and will not put a POLYGON in a MULTIPOLYGON geometry column.  I've gotten used to using  to fix this issue. But now I am trying to use GeoPandas to do some file processing, including converting from shapefile to GeoPackage (with a bunch of stuff in the middle), and I am running into this error:  gdf.to_file("garbage.gpkg", "GPKG")   ValueError: Record's geometry type does not match collection schema's     geometry type: 'MultiPolygon' != 'Polygon'   Is there a GeoPandas equivalent to ST_Multi that I can use to fix the geometry before saving to the GeoPackage or SpatiaLite format?
70042
The following piece of code works well in QGIS 2.x, however it does not work in QGIS 3.x.  myDir = 'd:/work/output_folder/' layers = iface.legendInterface().layers() pipe = QgsRasterPipe() for layer in layers:  extent = layer.extent()  width, height = layer.width(), layer.height()  renderer = layer.renderer()  provider=layer.dataProvider()  crs = layer.crs().toWkt()   pipe.set(provider.clone())  pipe.set(renderer.clone())  opts = ["COMPRESS=LZW"]   file_writer = QgsRasterFileWriter(myDir + layer.name() + ".tif")  file_writer.setCreateOptions(opts)  file_writer.writeRaster(pipe,       width,          height,          extent,          layer.crs())   This is the error I get when I run the code:  Traceback (most recent call last):   File "C:\PROGRA~1\QGIS3~1.0\apps\Python36\lib\code.py", line 91, in runcode     exec(code, self.locals)   File "&lt;input&gt;", line 1, in &lt;module&gt; AttributeError: 'QgisInterface' object has no attribute 'legendInterface'   Does someone know what has replaced 'legendInterface' in the new version or what other changes I might have to make to get this to run in QGIS 3.0?
44481
When saving a project file (.qgs), which when executed is automatically loaded with qgis.bat, there's another .qgs file which appears in the same directory of the original project file, although this one is not loaded with the qgis.bat file:    This is just out of curiosity but is the latter designed to be a backup of the original .qgs file?
93617
I need to build an app to analyze some raster layers in QGIS. I thought it was possible to just write code in python (2.7.6) (IDLE) and let it automatically open QGIS, load some layers, do a distance matrix, export that and load this file with python and use that information in the app. Is something like this possible? I have a mac running OSX10.9.1, using python 2.7.6 because I constantly got errors when using python 3.
18698
I have a password protected ArcGIS-FeatureServer Service, the service provides 25 layers.  Using "Add Layer --> Add ArcGIS-FeatureServer-Layer" works like it should.  Is there any way to add these kind of layers with PyQGIS? I could not find a documentation or example anywhere.  How to Add a normal WFS layer with PyQGIS is well documented.  For ArcGIS MapServer it is super-easy:  iface.addRasterLayer("url='my_featuere_layer_url' layer='0'", "mylayer", "arcgismapserver")   But the provider "arcgismapserver" is not documented anywhere, just found an example after some search, so I expect that there is a similar solution for ArcGIS-FeatureServer.
40109
I am looking for an example for using the  package to write a cover letter, with names and addresses on a spreadsheet. The package comes with an example, but you have to manually enter all the data.
84144
Is there a way to choose the field delimiter when exporting a CSV with geometry as wkt in QGIS?  I have a shapefile with donut holes and I'd like to export it as a CSV. It's for a partner whose DB doesn't support spatial data.  I followed  to add a WKT field to my exported file (when exporting to csv, add GEOMETRY=AS_WKT in the "Layer" field, but the exported field delimiter is a comma:   The problem is that each coordinate pairs of my polygons (and I suspect it will be the same for lines) are separated by a comma too so I can't import the data back into QGIS  With point shapefile, it works like a charm.  Does anyone know if I can choose my field delimited when exporting to CSV? Choose a semicolon for instance?  I search on the web and QGIS's documentation but didn't find anything.
12452
I am trying to automate various tasks in ArcGIS Desktop (using ArcMap generally) with Python, and I keep needing a way to add a shapefile to the current map. (And then do stuff to it, but that's another story).  The best I can do so far is to add a layer file to the current map, using the following ("addLayer" is a layer file object):  def AddLayerFromLayerFile(addLayer):  import arcpy  mxd = arcpy.mapping.MapDocument("CURRENT")  df = arcpy.mapping.ListDataFrames(mxd, "Layers")[0]  arcpy.mapping.AddLayer(df, addLayer, "AUTO_ARRANGE")  arcpy.RefreshActiveView()  arcpy.RefreshTOC()  del mxd, df, addLayer   However, my raw data is always going be shapefiles, so I need to be able to open them. (Equivalently: convert a shapefile to a layer file without opening it, but I'd prefer not to do that).
62098
Is QgsMapLayerRegistry going to be availabe in pyqgis with QGIS3  When I typed it into the QGIS python console (2.99), python seems to recognize it because it auto-completes qgis.core.QgsMapLayerRegistry, but then gives an error that it's not there:  Traceback (most recent call last):   File "/usr/lib/python3.5/code.py", line 91, in runcode     exec(code, self.locals)   File "&lt;input&gt;", line 1, in &lt;module&gt; AttributeError: module 'qgis.core' has no attribute 'QgsMapLayerRegistry'   I tried this with two versions of QGIS 2.99 (one in 01/07 and on in 06/17). Both versions give the same error. import doesn't work either:  &gt;&gt;&gt;from qgis.core import QgsMapLayerRegistry Traceback (most recent call last):   File "/usr/lib/python3.5/code.py", line 91, in runcode     exec(code, self.locals)   File "&lt;input&gt;", line 1, in &lt;module&gt; ImportError: cannot import name 'QgsMapLayerRegistry'   Is QgsMapLayerRegistry removed in QGIS3?
77484
I'm writing a generic script which involves writing shapefiles to a directory which are then merged together. After writing the files out to the Output folder, I'm trying to get the saga:mergeshapeslayers algorithm to merge all the files in the Output folder. I have used the Model Builder and although it is helpful to an extent, I find that it is used for specific purposes whereas I am attempting to make a script for generic purposes.   Code:  ##Test=name ##Select_folder=folder ##Result=output vector  import os import glob  path_1 = Select_folder path = path_1 os.chdir(path)  def function():      output = glob.glob(path_1 + './*.shp')     x = 0      while output[x]:         for fname in glob.glob("*.shp"):             outputs_1 = processing.runandload("qgis:fieldcalculator", output[x], 'Number', 1, 10, 0, True, 1 , "C:\Users\Me\Desktop\Output\\"  + fname)             multiple_0 = glob.glob("*.shp")             x = x + 1          if x + 1 &gt; len(output):             processing.runalg("saga:mergeshapeslayers", output[0], ";".join(multiple_0) , Result)             break         else:             continue  if path_1:     function() else:    pass
101212
I'm trying to establish a Postgres connection using QgsCredentials as described here:    The only problem is that I cannot establish a working connection unless I "physically" add the layer to the map canvas (which I don't want because I only want a connection to the DB and a reference to the layer which will be edited later on in the code)  When clicking a button the run function reads:  uri = QgsDataSourceURI() connInfo = uri.connectionInfo()  (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None)  if success:     # Isn't this enough to establish the connection and get a valid reference to the layer?     uri.setConnection("HOST", "PORT", "DB_NAME", user, passwd)     uri.setDataSource("SCHEMA", "TABLE_NAME", "the_geom")     LYR = QgsVectorLayer(uri.uri(), "LYR", "postgres")      # Unless I add the following line, I am not able to use properly the object     # (which asks the user the credentials until he/she inserts the right ones and gets     # a working connection with a valid reference to the layer)     QgsMapLayerRegistry.instance().addMapLayer(LYR)   What am I doing wrong?  Thanks in advance,  m.
87718
I have created a table join between two shapefiles which I've named 'OSMM' and 'Mastermap'. I want to copy and paste all features (polygons) without a match from the target layer ('Mastermap') into the parent shapefile ('OSMM'). I can't find any up-to-update code for QGIS 3.6. Here is my code so far: #1. loads the SHP files uri = 'C:/Users/xx/Downloads/OSMM.shp' vlayer = iface.addVectorLayer(uri,&quot;&quot;,&quot;ogr&quot;) uri = 'C:/Users/xx/Downloads/Mastermap.shp' vlayer = iface.addVectorLayer(uri,&quot;&quot;,&quot;ogr&quot;)  #2. Joins &quot;InvoiceNum&quot; from OSMM to Mastermap layerToJoin = QgsProject().instance().mapLayersByName('OSMM')[0] target = QgsProject().instance().mapLayersByName('Mastermap')[0] myJoin = QgsVectorLayerJoinInfo() myJoin.setJoinFieldName('InvoiceNum') myJoin.setTargetFieldName('InvoiceNum') myJoin.setJoinLayerId(layerToJoin.id()) myJoin.setUsingMemoryCache(True) myJoin.setJoinLayer(layerToJoin) myJoin.setJoinFieldNamesSubset(['InvoiceNum']) target.addJoin(myJoin)  #3. Selects NULL features from Mastermap params = { 'EXPRESSION' : '\&quot;OSMM_InvoiceNum\&quot; is NULL', 'INPUT' : 'C:/Users/xx/Downloads/Mastermap.shp', 'METHOD' : 0 } processing.run(&quot;qgis:selectbyexpression&quot;, params)  So how do I perform the PyQGIS version of Ctrl+C on 'Mastermap' and Ctrl+V into 'OSMM'? Presumably I will then need to use the following code: #5. Save the changes OSMM.commitChanges()