I would like to construct a map tool application that allows only to add some point features.   How do I complete the following code to activate snap mode while editing a layer with PyQGIS 3?  from qgis.core import * from qgis.gui import * from PyQt5.QtGui import * from PyQt5.QtCore import *  class AddPointTool(QgsMapTool):    def __init__(self, mapCanvas, layer):        QgsMapTool.__init__(self, mapCanvas)        self.layer=layer        self.setCursor(Qt.CrossCursor)     def canvasReleaseEvent(self, event):        point=self.toLayerCoordinates(self.layer, event.pos())        fields=self.layer.dataProvider().fields()        feature=QgsFeature()        feature.setFields(fields)        feature.setGeometry(QgsGeometry.fromPointXY(point))         self.layer.addFeature(feature)        self.layer.updateExtents()        self.layer.triggerRepaint()  canvas=iface.mapCanvas() layer=iface.activeLayer()  layer.startEditing() layer.triggerRepaint() tool=AddPointTool(canvas,layer) canvas.setMapTool(tool)
123605
The following expression enables snapping for PyQGIS 2.0 :  QgsProject.instance().setSnapSettingsForLayer(layer.id(), True, 2, 1, 10, True)   What is the equivalent expression in PyQGIS 3.0?
71061
I'm new at scripting.  I know that it's a basic question but I tried everything I could and nothing works.  So here's my problem:  I want to create a shortcut that automatically sets up a mirror modifier to an empty and then my custom pie menu opens with extra modifier options.  The only problem is that the menu will show me the option only of the selected object, and in my series of code I'm stuck at selecting the empty. I just want to select the object I defined as "OB" and it's done.  Here is the code:   import bpy  OB = bpy.context.selected_objects[0] bpy.ops.object.modifier_add(type='MIRROR') bpy.ops.object.mode_set(mode='OBJECT') bpy.ops.object.empty_add(type='PLAIN_AXES', view_align=False, location=(bpy.context.scene.cursor_location)) bpy.context.object.name = "Mirror Axes" OB.modifiers["Mirror"].mirror_object = bpy.data.objects["Mirror Axes"]  # HERE I NEED THE CODE THAT SELECTS "OB"  open_menu("D Mirror Menu")   I tried:    bpy.context.scene.objects.active = OB  OB.select = True  bpy.context.selected_objects[0] = OB   bpy.context.object = OB    And many other methods, but nothing works, the empty is still selected !! and I dont know why.  thanks
105912
I've got a simple Leaflet map with a basemap and one map-layer coming from my own hosted GeoServer.  I made the layers show up nicely in a map.  Now I want to add popups on the point layer showing information stored in MapService.  I couldn't find too much information about that topic.   There's one link to a working example but the link seems to be broken. I found another example which I addopted. You can see it on . I'd like to display the content of the name field in the attribute table but nothing happens when the user clicks the map.  Any idea?
87680
I want to apply unique symbol to each feature. I have used following code for doing that from qgis.core import * from PyQt4.QtGui import * # supply path to where is your qgis installed QgsApplication.setPrefixPath(&quot;/path/to/qgis/installation&quot;, True) # load providers QgsApplication.initQgis()  # Get the active layer (must be a vector layer) layer = qgis.utils.iface.activeLayer(); iter = layer.getFeatures(); for feature in iter:     geom = feature.geometry()     print &quot;Feature ID %d: &quot; % feature.id()     qgis.utils.iface.mapCanvas().setSelectionColor( QColor(&quot;yellow&quot;) );     layer.setSelectedFeatures([feature.id()])     qgis.utils.iface.mapCanvas().zoomToSelected( layer )     qgis.utils.iface.mapCanvas().refresh()     selected_features = layer.selectedFeatures()     for i in selected_features:        attr =i.attributes()     chaltano= str(attr[layer.fieldNameIndex('test')])     renderer = QgsCategorizedSymbolRendererV2(&quot;test&quot;)     layer.setRendererV2(renderer)     symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())     symbol.setColor(QColor(&quot;red&quot;))     cat = QgsRendererCategoryV2(feature.id(), symbol,str(feature.id()))     renderer.addCategory(cat)  Symbol is applying to only last feature. Here, &quot;test&quot; is attribute.
9216
I want to prompt for user input after all parameters have been specified for the script tool. I've seen many forum posts and stackexchange questions about this, and they all conclude that it's unnecessary, but I think my case is an exception. I want to give the user an opportunity to confirm data, such as how many sets of GPS coordinates there are. They will be yes/no questions ("is this data obviously incorrect?"), and the script tool parameter input form doesn't seem like it'd work well for this.  I know Tkinter's event handler causes problems with ArcGIS, and other framworks have similar problems. One workaround I found is to have your script call another script that runs as a separate process, and display the GUI from the second process, but that seems a little too hackish.    Apparently wxPython does work, but it's not included with python. I need to be able to distribute these scripts without any extra requirements other than ArcGIS, so that wouldn't work for me.    To clarify, the most important use would be to prompt the user when my software validation checks can't validate the data. For example, I have a list of IDs that I want to validate, but the format isn't consistent. I want to be able to prompt the user with a yes/no dialog if I can't validate in software (eg. the ID doesn't match one of the common patterns). It's possible that new ID formats will be created without my knowledge.    Another example: I have a file that contains, among other things, a table of start &amp; stop times. I want to validate each row of the table individually, and cramming all of that data, plus the other checks, into the warning window would get ugly fast.
44228
I am trying to run a standalone application. However, it does not run the program because of mentioned error in title. Here is my code:  from qgis.core import * from qgis.gui import * from qgis.utils import * from PyQt5.QtCore import * from PyQt5.QtGui import *  app = QgsApplication([], True) path = "C:/OSGeo4W64/apps/qgis-dev" app.setPrefixPath(path, True) app.initQgis()  canvas = QgsMapCanvas() title = "PyQGIS Standalone Application Example" canvas.setWindowTitle(title) canvas.setCanvasColor(Qt.white)  layer_info = 'LineString?crs=epsg:4326' layer = QgsVectorLayer(layer_info, 'MyLine', "memory") pr = layer.dataProvider() linstr = QgsFeature() wkt = "LINESTRING (1 1, 10 15, 40 35)" geom = QgsGeometry.fromWkt(wkt) linstr.setGeometry(geom) pr.addFeatures([linstr]) layer.updateExtents() QgsProject.instance().addMapLayer(layer)  canvas.setExtent(layer.extent()) canvas.setLayers([layer]) canvas.zoomToFullExtent() exitcode = app.exec_() QgsApplication.exitQgis() sys.exit(exitcode)   When I run it, I get this error:  Traceback (most recent call last):   File "C:/Users/DELL/Desktop/MyMap/myMap.py", line 1, in &lt;module&gt;     from qgis.core import *   File "C:\OSGeo4W64\apps\qgis-dev\python\qgis\__init__.py", line 72, in &lt;module&gt;     from qgis.core import QgsFeature, QgsGeometry   File "C:\OSGeo4W64\apps\qgis-dev\python\qgis\core\__init__.py", line 34, in &lt;module&gt;     from qgis._core import *   ImportError: DLL load failed: The specified module could not be found.  Python version is: 3.6 PyQt   version is: PyQt5.9 Windows 10 - 64bit  I also add many path:  %SystemRoot%\system32 %SystemRoot% %SystemRoot%\System32\Wbem %SYSTEMROOT%\System32\WindowsPowerShell\v1.0\ C:\OSGeo4W64 C:\OSGeo4W64\apps C:\OSGeo4W64\apps\gdal-dev C:\OSGeo4W64\apps\gdal-dev\bin C:\OSGeo4W64\apps\gdal-dev\pymod3\Lib\site-packages C:\OSGeo4W64\apps\grass\grass-7.2.2\bin C:\OSGeo4W64\apps\Python36 C:\OSGeo4W64\apps\Python36\Scripts C:\OSGeo4W64\apps\Python36\DLLs C:\OSGeo4W64\apps\Python36\lib\site-packages C:\OSGeo4W64\apps\qgis-dev C:\OSGeo4W64\apps\qgis-dev\bin C:\OSGeo4W64\apps\qgis-dev\lib C:\OSGeo4W64\apps\qgis-dev\python C:\OSGeo4W64\apps\qgis-dev\python\qgis C:\OSGeo4W64\apps\Qt5 C:\OSGeo4W64\apps\Qt5\lib C:\OSGeo4W64\bin C:\OSGeo4W64\apps\qgis-dev\python C:\OSGeo4W64\apps\Python36\lib C:\OSGeo4W64\include C:\Users\Mustafa Uçar\AppData\Roaming\QGIS\QGIS3\profiles\default C:\Users\Mustafa Uçar\AppData\Roaming\QGIS\QGIS3\profiles\default\QGIS   How can I fix this error?
117925
I'm trying to create some custom labels for point features in a QGIS point vector layer, and I want to write a python plugin to do it.  We need our labels to be presented with color tinted rectangles behind them (or else!). The labels are long strings, and are created using labeling engine expressions and conditionals.   I thought the easiest way would be to let the user set up labels for the active layer the way they want, and then let my plugin can grab the label text from the features in the layer and use the text strings to create boxes. My problem is I can't find a way to access those text strings in the QGIS API. How are label strings generated by the labeling engine stored in QGIS and how can I get to them?
31683
A while ago I made a plugin for QGIS for myself.  This worked until version 2.18. Now I have version 3.0 and would like to use this plugin here too. But I get some error messages. I have been able to solve most of them fairly easily. Only I can not do this. Perhaps there is someone among you who can help me in this.   This is the code that I used before.   def initGui(self):     """Create menu entries and toolbar icons inside the QGIS GUI."""      icon_path = ":/plugins/BFVWtools/"      """Create the menu entrie Configuratie and toolbar icon inside the QGIS GUI."""     self.add_action(icon_path + "/icon.png", text=self.tr(u'Configuratie'),      callback=self.run, parent=self.iface.mainWindow())     self.action = QAction( QIcon( os.path.dirname(os.path.realpath(__file__)) + "/icon.png" ), "Configuratie",      self.iface.mainWindow() )     QObject.connect(self.action, SIGNAL("triggered()"), self.run)   The error message I get is the following  AttributeError: type object 'QObject' has no attribute 'connect'  Traceback (most recent call last):   File "C:/OSGEO4~1/apps/qgis/./python\qgis\utils.py", line 345, in startPlugin plugins[packageName].initGui()   File "C:/Users/Automatisering/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\BFVWtools\bfvw_tools.py", line 212, in initGui QObject.connect(self.action, SIGNAL("triggered()"), self.run) AttributeError: type object 'QObject' has no attribute 'connect'   Apparently there is no attribute 'Connect' in QObject    After your explanation, I have converted everything to PyQt5 and changed the connect to slot. The strange thing is that I now get all the entrys from the menu one after the other.
115422
I saw the latest update of QField 1.8 wherein users are allowed to draw/digitize in freehand lines/polygons geometries. I was wondering how can it be enabled in QField? We badly need it in our fieldwork/geotagging activities of natural resources.  I have finally found out how to enable it. It could be seen in the QField Settings. The &quot;Consider mouse as a touchscreen device&quot; should be disabled for the Freehand Digitizing function to work.
77366
I've added a polygon layer and a point layer to my leaflet map.   I would like the points to appear after a certain zoom level or when a "click" event occurs e.g. (polygons.on("click", function....)  I have looked at different questions here and also this   But I am still unable to understand what to do in my code.   Here is my code:  &lt;script type="text/javascript"&gt;    var mapboxTiles = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {     attribution: '&lt;a href="http://www.mapbox.com/about/maps/" target="_blank"&gt;Terms &amp;amp; Feedback&lt;/a&gt;'   });   var map = L.map('map')     .addLayer(mapboxTiles)     .setView([42.444508, -76.499491], 4);    var polygons =  new L.geoJson(null, {       pointToLayer: function (feature, latlng) {           return L.marker(latlng, {});       }   });   var points =  new L.geoJson(null, {       pointToLayer: function (feature, latlng) {           return L.marker(latlng, {});       }   });    points.bindPopup("popup.").openPopup();   polygons.on("click", function (event) {       map.fitBounds(event.layer.getBounds());   });    polygons.addTo(map);   points.addTo(map);    $.getJSON('polygons.php', function (data) {       polygons.addData(data)   });   $.getJSON('points.php', function (data) {     points.addData(data)   });  &lt;/script&gt;
52758
I want my script to perform actions on a particular layer.  Online advice I've found so far suggests using the iface method "setActiveLayer()".  Makes sense based on the name alone.    Scenario:  In the Layers window I have a layer named "Province" highlighted (active).  Then I run the following code:  &gt;&gt;&gt; vl = QgsMapLayerRegistry.instance().mapLayer( 'na_roads_Prov' ) &gt;&gt;&gt; iface.setActiveLayer(vl)   Console Output = False  As far as I understand executing this code in the console should move the highlighted "active layer" from "Province" to 'na_roads_Prov'.  Yes?  Instead the "Province" layer remains highlighted as active, and the console output says "False".  Any ideas?  Am I not referring to the layer correctly?
22769
I have a PostGIS point layer with mixed features (with and without geometry). When a non geometry feature is selected from attribute table I don´t know how to set its geometry with QGIS editing tools. The add spatial object is only for new features.
27196
In QGIS 3.0, "Processing Modeler" window has no "Export as Python script" button unlike QGIS 2.x.    If you look at the codes (in DlgModeler.ui and ModelerDialog.py files), you see the code lines related to that button.  in ModelerDialog.py (commented):  #self.mActionExportPython.triggered.connect(self.exportAsPython) . . #self.mActionExportPython.setIcon( #            QgsApplication.getThemeIcon('/mActionSaveAsPython.svg'))   in DlgModeler.ui:  &lt;action name="mActionExportPython"&gt;   &lt;property name="text"&gt;     &lt;string&gt;Export as Python script...&lt;/string&gt;   &lt;/property&gt;   &lt;property name="toolTip"&gt;    &lt;string&gt;Export as Python script&lt;/string&gt;   &lt;/property&gt; &lt;/action&gt;   After some editings I explained , "Export as Python script" button came into view.    Is there a specific reason or is it a mistake?
96820
I have loaded two layers in canvas and would like to move the layers using the following code in TOC, but it is not moving the layers to the position based on the index given.   from PyQt4.QtCore import * from PyQt4.QtGui import *  from qgis.core import * from qgis.gui import * import qgis.utils  canvas = qgis.utils.iface.mapCanvas() layers = canvas.layers()  for i in layers:   if i.name() == "Layer2":     alayer = i   elif i.name() == "Layer1":     blayer = i  qgis.utils.iface.legendInterface().moveLayer(alayer, 0) qgis.utils.iface.legendInterface().moveLayer(blayer, 1) canvas.refresh()   How can I do that?
69554
I am trying to get coordinates from a mouse click in QGIS 3 and python 3 using the plugin builder.  I have tried using the response , and i can manage to get the coordinates printed to the python console in QGIS but at the same time i get the message that "'TypeError: 'QgsMapToolEmitPoint' object is not iterable" or "'QgsMapToolEmitPoint' object does not support indexing"   I can't remember i ever seen a python program causing an error but still manage to compute and output the wanted result. The "not iterable" error traces back to the line with the for loop "for point in ... " the "does not support indexing" error is caused if i do e.g. x = pointTool[0]  Here is a version of the code:  from qgis.gui import QgsMapToolEmitPoint   def display_point(pointTool):     #print(pointTool)     cood = []     for point in pointTool:         cood.append(point)     print(cood)  # a reference to our map canvas canvas = iface.mapCanvas()  # this QGIS tool emits as QgsPoint after each click on the map canvas pointTool = QgsMapToolEmitPoint(canvas)  pointTool.canvasClicked.connect(display_point)  canvas.setMapTool(pointTool)  display_point(pointTool)
6194
In my case I failed to use  plugin (2.0.30) with QGIS 2.14.11 and 2.18.3 on windows64.  Tested on several datasets: points, polygons, and csv.- But I am not sure what I have missed.    I want to click on this Calculate button.
82092
I am using QGIS 2.16 / Windows 10.  I have a point shapefile which I have been using for a little while that has always been editable.  Today I was editing the layer, saved my edits and left my computer for a few hours. When I came back I was not able to toggle the editing button on the toolbar and when I right click on the layer it longer has toggle editing as an option.  I have googled the problem every way I can think of and have not been able to find an answer to why the layer is suddenly un-editable or how to fix this.