I'm trying to add the attribute $area. I made a intersection and Tot_aera isn't the good one, so I want to add a new.  I made that :   from PyQt4.QtCore import * try:     if ind==-1:         if caps &amp; QgsVectorDataProvider.AddAttributes:             res=provider.addAttributes( [ QgsField(nameattr,QVariant.Double) ] ) except:     print "FALSE"   So I have a new attribute but NULL. So my question : How put "$area" in nameattr?
121914
I'm trying to compute the areas of the new layer I created by intersecting two layers.   How can I write a script that does something equivalent to clicking Export/Add geometry columns?
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.
79719
I have to try to add a field called 'Name' to a bunch of different feature classes using python, and then access the name of the feature class to fill in the field. I have no idea how to even start this! I know I need a loop but that's all I know.
81807
When I open QGIS, add the layer, and calculate the areas of the shapefile via field calculator I get a different area than when I open QGIS and check "Enable on the fly CRS transformation" and calculate the area. This is despite making sure that the project and the layer have the same Coordinate system (same EPSG number). What am I doing wrong?   I have a shapefile with area calculations made with ArcGIS (not be me, the data was handed to me and I have no clue for which CRS the area was calculated with ArcGIS). The shapefile layer CRS is EPSG: 21781 (Switzerland). In QGIS, if I do not change the OTF settings and leave the project CRS as EPSG:4326 (WGS84) I get the same value as the ArcGIS area value. However, if I change the OTF before adding the layer to EPSG: 21781 I get different area values. As I understand this suggests that ArcGIS Area was calculated with the CRS EPSG: 4326.  First workflow:   open QGIS  project CRS: EPSG 4326  add layer  project CRS adapts automatically and is EPSG 21781 now  calculate $area with field calculator    Second workflow:   open QGIS  project CRS: EPSG 4326  Turn on OTF, set project CRS to EPSG 21781  add layer  calculate $area with field calculator    Step 5 of the first and second workflow DO NOT produce the same area.
26033
I'm new to drupal and I need some help.  I created a new module with name user_extra. Which create necessery table when Installing the module.  But I also need to insert some database field in 'users_field_data' table ('user_extra_id' and 'user_office')  In baseFieldDefinitions I wrote all necessery database table fields for user_extra table.   public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {     // Standard field, used as a unique if primary index.     $fields['id'] = BaseFieldDefinition::create('integer')         -&gt;setLabel(t('Unit ID'))         -&gt;setDescription(t('The unit ID.'))         -&gt;setReadOnly(TRUE)         -&gt;setSetting('unsigned', TRUE);      $fields['uuid'] = BaseFieldDefinition::create('uuid')         -&gt;setLabel(t('UUID'))         -&gt;setDescription(t('The unit UUID.'))         -&gt;setReadOnly(TRUE);         .         .         .     $fields['user_info'] = BaseFieldDefinition::create('string')         -&gt;setLabel(t('User Info'))         -&gt;setDescription(t("The User Info"))         -&gt;setSetting('max_length', 255)         -&gt;setDisplayOptions('form', array(           'type' =&gt; 'string_textfield',           'weight' =&gt; 10,         ))         -&gt;setDisplayConfigurable('form', TRUE);      return $fields;      }   When I install the module it inserts all values that I define in baseFieldDefinitions.  But I also need to create 'user_extra_id' and 'user_office' in 'users_field_data' table with setDisplayOptions and setDisplayConfigurable options.  This is the commenting that I made in entity file  /**  * @ContentEntityType(  *   id = "user_extra",  *   label = @Translation("user extra"),  *   handlers = {  *     "storage" = "Drupal\user_extra\UserextraStorage",  *     "storage_schema" = "Drupal\user_extra\UserextraStorageSchema",  *     "access" = "Drupal\user_extra\UserextraAccessControlHandler",  *     "list_builder" = "Drupal\user_extra\UserextraListBuilder",  *     "view_builder" = "Drupal\user_extra\UserextraViewBuilder",  *     "views_data" = "Drupal\user_extra\UserextraViewsData",  *     "form" = {  *       "default" = "Drupal\user_extra\Form\UserextraForm",  *       "add" = "Drupal\user_extra\Form\UserextraAddForm",  *       "edit" = "Drupal\user_extra\Form\UserextraEditForm",  *       "delete" = "Drupal\user_extra\Form\UserextraDeleteForm",  *     }  *   },  *   admin_permission = "administer user_extra",  *   base_table = "user_extra",  *   entity_keys = {  *     "id" = "id",  *     "label" = "name",  *     "uuid" = "uuid",  *   },  *   links = {  *     "canonical" = "/admin/user_extra/{user_extra}",  *     "add-form" = "/admin/user_extra/add",  *     "delete-form" = "/admin/user_extra/{user_extra}/delete",  *     "overview-form" = "/admin/user_extra/${user_extra}/overview",  *     "edit-form" = "/admin/user_extra/{user_extra}",  *     "collection" = "/admin/user_extra",  *     "children" = "/admin/user_extra/{user_extra}/children",  *   },  * )  */
53788
I cut a part out of one feature and added it to another feature in a polygon shapefile.  My problem now is that both features has the same values in the area-, perim-, p2a-, width- and length-columns?  The features are very much different in size, how do I get QGIS to sort of "re-calculate" the areas etc?
14824
Any time I am inserting new point feature in QGIS, the Feature Attribute dialog box is popping up. Is there a way to prevent it? (I am willing to insert many points at once and this pop up box slows down the process).
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?
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?
5326
I'm using QGIS 2.6 and regularly update a shapefile layer to indicate felling progress. However, if I edit the nodes of a polygon, save the layer out then look at the Attributes table the area shown doesn't change.
35297
Is there a way to add an error on a dynamically referenced field? Let's take this simple example:  opp.get('Name').addError('Invalid name');   This is not working, I'm looking for a similar minded way.  Thanks
29356
Using QGIS, if I load a polygon layer and make a new column, how do I fill that column with the:   area of each polygon and another column with length of the perimeter of each polygon?
119496
I know it has been asked and answered before, and I need to put { and } around it, but for some reason this doesn't work:  \draw (0,0) -- ({atan(1)}:{sqrt(2)});   Any idea why?
124279
I have two feature classes, a polygon of sales areas for a city, and point layer of addresses. I want to select the addresses based on the sales area they are in and update their attribute table to show the sales area. I have searched python+point+in+polygon for other posts and I know how to select the polygons but I can't figure out how to populate the address points.   I found the following script that works but takes almost two hours to run.  import arcpy import os  # Allow overwrite  arcpy.env.overwriteOutput = True  # Script user input parameters polygonLayer = arcpy.GetParameter(0) pointLayer = arcpy.GetParameter(1) workspace = arcpy.GetParameter(2) copyField = = arcpy.GetParameterAsText (3)   # Add new field to target feature class  fieldList = arcpy.ListFields(pointLayer) fieldNameList = [] for field in fieldList:    fieldNameList.append(field.name) fieldType = arcpy.ListFields(polygonLayer,copyField)[0].type if not copyField in fieldNameList:     arcpy.AddField_management(pointLayer, copyField, fieldType)  arcpy.MakeFeatureLayer_management(polygonLayer, "PolygonLayer")  pntCursor = arcpy.UpdateCursor(pointLayer) for pnt in pntCursor:     rowID = pnt.OBJECTID     arcpy.MakeFeatureLayer_management(pointLayer, "PointLayer", '"OBJECTID" = ' + str(rowID))      # Polygon selection based on CONTAINS selection method     arcpy.SelectLayerByLocation_management("PolygonLayer", "CONTAINS", "PointLayer")      # Copy field values from polygon to point layer         polyCursor = arcpy.SearchCursor("PolygonLayer")             for poly in polyCursor:         pnt.setValue(copyField, poly.getValue(copyField))         pntCursor.updateRow(pnt)      arcpy.Delete_management("PointLayer")          del pntCursor, polyCursor, pnt, poly   I don't think I need to create a new field so I have simplified my script too:  # Import arcpy module import arcpy import os  # Allow overwrite  arcpy.env.overwriteOutput = True  # Script user input parameters polygonLayer = arcpy.GetParameter(0) pointLayer = arcpy.GetParameter(1) workspace = arcpy.GetParameter(2) fsaPoly = arcpy.GetParameterAsText (3) #FSA in FSA_Boundaries fsaPnt =  arcpy.GetParameterAsText (4) #FSA in Addresses   # Select all Address in FSA     polyCursor = arcpy.SearchCursor("PolygonLayer")      for poly in polyCursor: # Select based on CONTAINS      arcpy.SelectLayerByLocation_management(poly, "CONTAINS", "PointLayer")  # Add FSA to Address         pntCursor = arcpy.UpdateCursor("pointLayer")               for pnt in pointCursor:             pnt.setValue(fsaPnt, fsaPoly)             pntCursor.updateRow(pnt)   del pntCursor, polyCursor, pnt, poly   I know my update cursor is wrong but i'm stuck on how to update one feature class using information selected from the other.   I know I can do this manually but I need to do it for multiple cities so I would like to automate the process.   I am using Arc 10.2.2 to run my python script.
103677
I have a polygon layer loaded from POSTGIS database. This layer has a default value for the first column. I can create a new feature set that attribute to some predefined value with      newFeature = QgsFeature()     newFeature.setFields(activeLayer.pendingFields())     newFeature.setAttribute(0, "someValue")   But I want to set it to the default value that comes from the layer. When I try to add a feature with QGIS 2.10 it automatically sets the default value for that column. How can I achieve that with PyQGIS?
31878
I want to build a shortcode that takes a single attribute.  Everything online is telling me to make it using an array:  // Add Shortcode function bg_comparison_points_shortcode( $atts ) {     // Attributes     $atts = shortcode_atts(         array(             'custom_field' =&gt; '',         ),         $atts,         'comparison_points'     );     return bg_calculate_points($custom_field); } add_shortcode( 'comparison_points', 'bg_comparison_points_shortcode' );   But in my mind something like this would be much simpler  // Add Shortcode function bg_comparison_points_shortcode( $custom_field ) {     return bg_calculate_points($custom_field); } add_shortcode( 'comparison_points', 'bg_comparison_points_shortcode' );   Is there a problem doing this simpler version?
96497
Just trying to run the following code already given in the pyqgis cookbook to create graduated colors symbology (as in example with 2 classes)  I define the source info for the shapefile but when I run execute the code within my test-plugin, it just adds the layer without classifiying. Just adds as usual, all polylines appear same.  Any solution or working code/method?  link to code in cookbook   from qgis.core import  (QgsVectorLayer, QgsMapLayerRegistry, QgsGraduatedSymbolRendererV2, QgsSymbolV2,QgsRendererRangeV2)  myVectorLayer = QgsVectorLayer('C:/my_test_shape_file.shp', 'test_shp_file', 'ogr')  myTargetField = 'target_field' myRangeList = [] myOpacity = 1  # Make our first symbol and range... myMin = 0.0 myMax = 50.0 myLabel = 'Group 1' myColour = QtGui.QColor('#ffee00') mySymbol1 = QgsSymbolV2.defaultSymbol(myVectorLayer.geometryType()) mySymbol1.setColor(myColour) mySymbol1.setAlpha(myOpacity) myRange1 = QgsRendererRangeV2(myMin, myMax, mySymbol1, myLabel) myRangeList.append(myRange1)  #now make another symbol and range... myMin = 50.1 myMax = 100 myLabel = 'Group 2' myColour = QtGui.QColor('#00eeff') mySymbol2 = QgsSymbolV2.defaultSymbol(myVectorLayer.geometryType()) mySymbol2.setColor(myColour) mySymbol2.setAlpha(myOpacity) myRange2 = QgsRendererRangeV2( myMin, myMax, mySymbol2, myLabel) myRangeList.append(myRange2)  myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList) myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval) myRenderer.setClassAttribute(myTargetField) myVectorLayer.setRendererV2(myRenderer) QgsMapLayerRegistry.instance().addMapLayer(myVectorLayer)      @Kelly's code works perfectly.   However I noticed that both the code (one I have typed in my first message and yours in the 2nd message) DO NOT work in QGIS v1.7.3 but WORKS in QGIS v1.8.0. I think this was a bug(?) that already resolved in v1.8.0  And one more question;  Do you have any sample code for (natural breaks, Jenks) classification of the "numeric_attribute_field" based on given number of classes (i.e. no of classes will be a variable in the code, say "n", and I will pass that from the plugin GUI i.e. n = spinBox.value() )