I am trying to add a group to the layer panel, then place a vector layer (vectorLayer) into this group from a python script. The code I am using is:  groupName="test group" root = QgsProject.instance().layerTreeRoot() group = root.addGroup(groupName)  group.insertChildNode(-1, QgsLayerTreeLayer(vectorLayer)) QgsMapLayerRegistry.instance().addMapLayer(vectorLayer,True)   My issue is that this code always adds two copies of the vector layer. One of which will be in the group, the other is outside the group.     However, when I change the code to the following with the intent of not adding a second layer, the layer inside the group becomes '(?)'.  groupName="test group" root = QgsProject.instance().layerTreeRoot() group = root.addGroup(groupName)  group.insertChildNode(-1, QgsLayerTreeLayer(vectorLayer)) # QgsMapLayerRegistry.instance().addMapLayer(vectorLayer,True)     Does this mean the layer inside the group is just a pointer to the layer outside the group?   How do I add a layer to a group without the duplicate layer?
53173
I am trying to add new layers into a specific group which I can get to work if I know the index, but how can I get Python to find the index of a group so it can load the new layer into the group wherever it is in the TOC?  qgis.utils.iface.legendInterface().moveLayer( layer, index )
2399
So if I have this custom panel in the 3D view, is there a way I can take a property from for example the properties window and paste it onto my panel below the "text" prop, without creating a new property?  The reason I do not want to create a new property is because I want them to share all data, such as values, keyframes, drivers etc.        bl_info = {     "name": "",     "description": "",     "author": "",     "version": (0, 0, 1),     "blender": (2, 70, 0),     "location": "",     "warning": "",      "wiki_url": "",     "tracker_url": "",     "category": "" }  import bpy  from bpy.props import (StringProperty,                        BoolProperty,                        IntProperty,                        FloatProperty,                        FloatVectorProperty,                        EnumProperty,                        PointerProperty,                        ) from bpy.types import (Panel,                        Operator,                        AddonPreferences,                        PropertyGroup,                        )   class inouse_Settings(PropertyGroup):      my_bool = BoolProperty(         name="Enable or Disable",         description="A bool property",         default = False)     class UV_OT_my_panel(Panel):     bl_space_type = 'VIEW_3D'     bl_idname = "UV_OT_my_panel"     bl_label = "Custom"     bl_category = "Custom"     bl_region_type = 'TOOLS'      def draw(self, context):          scn = context.scene         mytool = scn.inhouse         layout = self.layout          col = layout.column(align=True)         row = col.row(align = True)         row.prop(mytool, "my_bool", text="Text")       def register():     bpy.utils.register_module(__name__)     bpy.types.Scene.inhouse = PointerProperty(type=inouse_Settings)  def unregister():     bpy.utils.unregister_module(__name__)     del bpy.types.Scene.inhouse  if __name__ == "__main__":     register()
60986
I wrote a script to create a big number of heat maps for a given scenario. I would like to save the result of every heat map as an PNG image. I have figured it out doing it with simple Map Rendering but the quality of the result is too low. Furthermore I would like to export to OpenLayers using the same code, which does not seem to be possible with simple rendering.   Now I am trying to do it with QgsComposition instead. Manually in the Map Composer you can just set the paper color to transparent and disable the background of the map canvas.   This is the code that I have so far. I just cannot figure out why it is not working. The result png-file always has a white opaque background.   My OS is Windows 7 and I'm using QGIS 2.6 Brighton.  I hope someone can help me out here.  # PARAMETERS mainPath = 'path/to/folder/' filename = 'filename' imageType = "png" imageWidth_mm = 400 imageHeight_mm = 160 dpi = 300  mapRenderer = iface.mapCanvas().mapRenderer()  c = QgsComposition(mapRenderer) c.setPlotStyle(QgsComposition.Print)  c.setPaperSize(400, 160)  x, y = 0, 0 w, h = c.paperWidth(), c.paperHeight() composerMap = QgsComposerMap(c, x ,y, w, h) c.addItem(composerMap)  # get all items and disable the backgrounds itemList = c.items() c.removeItem(itemList[2]) c.removeItem(itemList[2]) itemList[2].setBackgroundEnabled(False) itemList[3].setBackgroundEnabled(False) # add them to the composition c.addItem(itemList[2]) c.addItem(itemList[3])  c.refreshItems() c.refreshDataDefinedProperty(QgsComposerObject.AllProperties)  c.setPrintResolution(dpi) dpmm = dpi / 25.4 width = int(dpmm * c.paperWidth()) height = int(dpmm * c.paperHeight())  # create output image and initialize it # image = QImage(QSize(width, height), QImage.Format_ARGB32) image = QImage(QSize(width, height), QImage.Format_ARGB32_Premultiplied) image.setDotsPerMeterX(dpmm * 1000) image.setDotsPerMeterY(dpmm * 1000) #image.fill(0)  imagePainter = QPainter(image)  # This part does not seem to have any effect #brush = QBrush(Qt.BrushStyle(0)) # transparent brush # #imagePainter.setBackgroundMode(0) #c.setBackgroundBrush(brush)  c.renderPage( imagePainter, 0 ) imagePainter.end()   imageFilename =  mainPath + filename + '.' + imageType image.save(imageFilename, imageType) print 'image saved' print 'done'
95203
It is my second day on PyQGIS. Not sure why layer doesn't return anything. Can anyone help me on this?    Code:  #!/usr/bin/python from qgis.core import * from qgis.utils import * from PyQt4.QtCore import *  def main():   qgis_prefix="/usr"       QgsApplication.setPrefixPath(qgis_prefix, True)    QgsApplication.initQgis()   app = QgsApplication([], False)    uri = "elevp.csv?delimiter=%s&amp;xField=%s&amp;yField=%s&amp;elevField=%s" % (";","x","y","elev")   vlayer = QgsVectorLayer(uri, "test", "delimitedtext")   QgsMapLayerRegistry.instance().addMapLayer(vlayer)   #print(QgsMapLayerRegistry.instance().mapLayers())     #iface.mapCanvas().setSelectionColor( QColor("red") )   layer = iface.activeLayer()   print(layer)   # Run main wrapper codes main()
23336
When I change symbology for a given QgsVectorLayer (QGIS 2.14.16 LTR) by  r=iface.activeLayer().rendererV2() r.symbol().symbolLayers()[0].setColor(0,0,255,255)   as shown here:    and refreshing the map content by  iface.mapCanvas().refreshAllLayers()   I get the expected result, but the Layer Tree does not update as shown here:    What am I missing, and how can I update the Layer tree from PyQGIS programmatically?
91871
Leaflet maintains that the Map panes elements contain all layers added to the map. The difference between many of the Map panes is strictly the z-index order of layering.  I would like to use a combination of lvector.CartoDB layers, which are essentially overlayPane layers, with TileLayer, such as GeoIQ Acetate-bg and labels.  This is the ordering of the elements as they are added the map:  tileLayer1 = new L.TileLayer(); map.add(tileLayer1);  // add first layer to map  cartoDBLayer1 = new lvector.CartoDB(); cartoDBLayer.setMap(map); // add second layer to map  tileLayer2 = new L.TileLayer(); map.add(tileLayer2);  // add third layer to map   What returns is a map with layers in this order:  tileLayer1,tileLayer2,cartoDBLayer1   tileLayer1 and tileLayer2 are situated in the HTMLElement: TilePane and cartoDBLayer1 is in HTMLElement: overlayPane.  Is there any way to force cartoDBLayer1 to render in the TilePane, such that it falls in order of the z-index that it is added to the map in...   i.e.   z-index[0]:tileLayer1 z-index[1]:cartoDBLayer1 z-index[2]:tileLayer2
7068
I'm using python in QGIS. I have a layer of polygons (its a result of some earlier dissolving and has no overlapping polygons but some holes and islands in holes etc). I want to build a new layer which contains one polygon representing a bbox of the first layer with each polygon cut from it.  Essentially I want to "invert" the layer I have so that where the was polygon, now there is not, and where there was not polygon now there is. All inside a bounding box of the original layer.  I can build a bbox easily and I tried to "subtract" the polygon layer from my new bbox polygon layer but the process slows to a stop and then crashes my PC. Here's the algorythm  processing.runalg("qgis.difference","path/to/polygon.shp","path/to/bbox.shp","path/to/result.shp")   I dont care about attributes (obviously). I just need to cut one set of polygons from one larger polygon.  It seems so simple, I wish I could find a simple command or script to acheive this. As stated at the top I'm looking for a solution in python in QGIS.
38252
For purpose of a project, I created a project in QGIS - aerophoto base and 3 layers. It works perfect on my computer, but if I save it on CD, the project doesent work on any other computer... I saved all data for layers &amp; project works from CD, but only on computer, where it was created.  How can I save it, so it will be working on other comps, since I have to distribute this project to other partners?  I am using windows and QGIS 1.8.0. Lisboa  EDIT &amp; MORE INFO: my project is aerophoto based with one raster and 2 vector layers. It works on my comp (where QGIS 1.8.0 Lisboa is installed).  Now I need to put it on USB (and few on CD), so I can take to my menthor and cooperants to see it...  I copied all data (those are in same folder), I downloaded the QGIS Lisboa (.exe file) so everyone can install it. Now all is on usb. It works on my computer, where this was created. But when I try to see it on laptop (after installing QGIS), it serves me with error (runtime error) - same on my friend computer.  Proposal to make a USB option of qgis is nice, I am in a process of trying, but i suspect there is something else, because error is reported.  if possible, step by step solution, because I am comp analphabet actually :(
2071
I'm writing a script which must work outside of QGIS GUI. I call some API functions from qgis.core but I'd like to use the processing plugin.  I'm able to import processing with sys.path.append() but I can't run any process. Moreover, all "native" algs are missing in QgsApplication.processingRegistry().algorithms()  So is it possible to run processing that way ? What am I missing ?  import os, sys from qgis.core import * QgsApplication.setPrefixPath('/usr', True) qgs = QgsApplication([], False) qgs.initQgis()  sys.path.append('/usr/share/qgis/python/plugins') from processing.core.Processing import Processing Processing.initialize() import processing  layer1 = QgsVectorLayer('data/ROUTE_PRIMAIRE.SHP') layer2 = QgsVectorLayer('data/ROUTE_SECONDAIRE.SHP')  processing.run('qgis:union', layer1, layer2, 'test.shp') # returns nothing   I'm on QGIS 3.0.1 - Debian 9
17429
Is there a way, using Python, to duplicate a layer in QGIS as many times as the single occurrences of a variable contained in a field and with a filter applied on the duplicated layer based on the variable itself?   An example: I have layer0 with a field0 that contains var1, var2, var3, etc. I would like the layer0 duplicated to layer1, layer2, layer3 etc. so that layer1 has a filter where field0 = var1, layer2 has a filter where field0 = var2, etc.  The idea is similar to the LayersByField plugin but instead of creating a new layer for each occurrence of a variable I wish to just duplicate the "master" layer (so to avoid unnecessary files on disk)
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.
57758
Being new with python so far, I got inspired by this answer:   to dive into it a bit.  When creating features in a new target layer from an existing source layer, all "solutions" I found so far to create that new layer, were to either   prepare the new target layer manually in QGIS beforehand, adding all fields (with field types, lengths etc). Hard-code the field settings into the python script when creating that new target layer.    It seems a bit odd to me that there should be no programmatic way to clone the attribute scheme of a layer, and create a new (memory) layer with this scheme, so you wont have to change your script for each new layer, or fumble things together manually.  I'm focused on the creation of memory-layers, cause I want to have the opportunity to decide by myself if the outcome is satisfactory and save it manually when it fits my needs.
69720
The label toolbar uses fields in the attribute table of vector layers to fine tune labeling (Data defined labeling). That's the main reason i'm looking for that, but it may have more applications.  I'd like to automatically add some format columns instead of adding them manually every time.   Do you know a plugin or a way to do this manipulation automatically on multiples layers ?  I tried to get the QGIS tool "Add a field to attribute table" into a quick model which works properly, but it creates a new memory layer. And I'd like just new fields.  ##Add_ETIKT_Field=name ##myvlayer=vector ##myvlayer=output vector outputs_QGISADDFIELDTOATTRIBUTESTABLE_2=processing.runalg('qgis:addfieldtoattributestable', myvlayer,'ETIKT_Y',1,15.0,4.0,None) outputs_QGISADDFIELDTOATTRIBUTESTABLE_1=processing.runalg('qgis:addfieldtoattributestable', outputs_QGISADDFIELDTOATTRIBUTESTABLE_2['OUTPUT_LAYER'],'ETIKT_X',1,15.0,5.0,myvlayer)   What I'm looking to automate is :   Open the attribute table Edit button Field Calculator button Add Column + Type + length + Precision   It seems there's some ideas in , but I'd love to avoid coding anything, or at least at minimum go through the modeler.     Adding and Removing Fields       To add fields (attributes), you need to   specify a list of field definitions. For deletion of fields just   provide a list of field indexes.   if caps &amp; QgsVectorDataProvider.AddAttributes:     res = layer.dataProvider().addAttributes([QgsField("mytext", QVariant.String), QgsField("myint", QVariant.Int)])  if caps &amp; QgsVectorDataProvider.DeleteAttributes:     res = layer.dataProvider().deleteAttributes([0])
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).
112573
I've just downloaded and installed the new version of QGIS 2.10.1 with GRASS 6.4.4.  When opening a new GRASS mapset and importing layers, I missed the button "Add a new vector layer". I've updated the GRASS plugin, but again the button wasn't there (all other GRASS symbols except "add raster layer" were visuable).  It's maybe a stupid question of a GIS beginner, but what can I Do? Is there an option to add (not import) a vector layer via the GRASS toolbox?
44054
I am creating a polygon feature layer with soil classes in QGIS.   I need to share this layer with some colleagues and I need the layer to maintain the color ramp I have created.   Is there any specific format where the color ramp is saved together with the layer?   Since I don´t know how to do that, I was thinking on saving the color ramp that I created as a style.   How can I export this style?
97296
When using the QGIS Gui, there are plenty of predefined colorramps to choose from when styling a layer with e.g. categorized symbology.    When using the Python console for PyQGIS scripting,  describes how to create your own colorramp that you can then apply to a renderer object, for example:  # create a new colorramp colorRamp = QgsVectorGradientColorRampV2.create({'color1' : '0,255,0,255',                                                      'color2' : '255,0,0,255',                                                      'stops' : '0.5;255,255,0,255'})  # set up an empty categorized renderer and assign the colorramp renderer = QgsCategorizedSymbolRendererV2(field, []) renderer.setSourceColorRamp(colorRamp)   Is there a way to access the predefined colorramps that are accessible from the GUI and assign them to a renderer instead of creating my own?