Tag Info

Hot answers tagged

4

You can use the method setEditorWidgetV2() from QgsVectorLayer. To set the edit widget of a field to DateTime, do this: vLayer.setEditorWidgetV2( fieldIndex, 'DateTime' ) Parameters can be set via a dictionary of key-values, like this: vLayer.setEditorWidgetV2Config( fieldIndex, {'display_format': 'yyyy-MM-dd', 'allow_null': False, 'field_format': ...


4

Don't use a message box for this. It is not what they are for and will make people cry. Use the message bar. iface.messageBar().pushWarning("title", "message") or iface.messageBar().pushMessage("title", "message") http://qgis.org/api/classQgsMessageBar.html


4

You can also reference a layer by it's name: layer = QgsMapLayerRegistry.instance().mapLayersByName("MY_LAYER_NAME")[0] selected = layer.selectedFeatures() if your not sure of the name, you can look for it: layer=None for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.name() == "MY_LAYER_NAME": layer = lyr break


4

You could access the specific feature, without a loop, using the setFilterFid() method. In your case, if you wanted to call the feature in row 222, you would do: aLayer = iface.activeLayer() request = QgsFeatureRequest().setFilterFid(222) feat = aLayer.getFeatures(request).next() print feat.attributes() To just get a specific attribute, you would use ...


3

Look at Get a list of layer names using PyQGIS` You can use a simple Python dictionary names = [layer.name() for layer in QgsMapLayerRegistry.instance().mapLayers().values()] layers = dict((name,i) for i, name in enumerate(names)) print layers {u'layer1': 1, u'layer2': 0, u'layer3': 2, u'layer': 3, ...} or: canvas= qgis.utils.iface.mapCanvas() layers = ...


3

I think you need to add qgis.core module as the QGis.WkbType belongs to it: from qgis.core import * I tested this on a script and it worked for me: ##Test=name from qgis.core import * from qgis.utils import * layer = iface.mapCanvas().currentLayer().wkbType() == QGis.WKBPoint print layer The script prints a True/False statement in the Python Console. ...


3

If I got you right, you can use the SIGNAL selectionChanged from your vector layer and connect it to your other function (which must accept an argument to receive selected features' ids). For example, load a vector layer to QGIS, activate it in the ToC and run the following code in the QGIS Python console. You should see the function is running after a new ...


2

You would just need to make sure your layer has a name you can distinguish from others. Instead of layer = self.iface.activeLayer(), do: layer=None for lyr in QgsMapLayerRegistry.instance().mapLayers().values(): if lyr.name() == "YOUR_LAYER_NAME": layer = lyr break If you don't trust the layer name (after all, it can be changed by the ...


2

You are calling the wrong class. What you need to call is mapCanvas, and not canvas. Change your code to this: allLayers = iface.mapCanvas().layers() for i in allLayers: print i.name() This will print all of your current layers' names. Also note that you need to indent the print line. I assume in your post this was just a copy/paste problem, but if ...


2

I can't say exactly why the runandload method doesn't work with raster memory layers (not experienced enough) but since you only want to use the result as an intermediate calculation, an alternative can be: int_raster = processing.runalg("gdalogr:cliprasterbymasklayer", path_to_raster, path_to_shape, "", False, False, "", None) You can use int_raster ...


2

You are probably setting a connection between a SIGNAL (button clicked) and a SLOT (your method showTable) every time your plugin is open (run() method?) and you are not disconnecting such SIGNAL/SLOT when your plugin is closed. This leads to a new call to showTable() every time you open your plugin, because there's a new connection calling it. A couple of ...


2

I didn't find the option from the API, but you could mimic such behavior this way: I assume there are selected features already, so get their Ids: lyr = iface.activeLayer() selIds = lyr.selectedFeaturesIds() You said you have an expression, let's say: expr = QgsExpression( "\"NMG\" = 'CALI'" ) Now, get feature Ids that match your expression: it = ...


2

This would be enough: iface.mapCanvas().layers()


2

Nathan W is correct. But, if you still want to display a QMessageBox with autoclose behaviour. You can do it bu subclassing the QMessageBox like this: class CustomMessageBox(QMessageBox): def __init__(self, *__args): QMessageBox.__init__(self) self.timeout = 0 self.autoclose = False self.currentTime = 0 def showEvent(self, QShowEvent): ...


2

Two steps: - add a line that indicates UTF-8 encoding to the top of your script - add the letter u (to indicate unicode) before the string that contains the umlaut For example, the following snippet: # -*- coding: utf-8 -*- from qgis.gui import QgsMessageBar iface.messageBar().pushMessage('Hallo', u'PyQGIS k├Ânnte einfacher sein!', QgsMessageBar.WARNING, ...


2

You can achieve it by running the following code snippet in the QGIS Python console: from PyQt4.QtCore import QVariant for layer in QgsMapLayerRegistry.instance().mapLayers().values(): prefix = layer.name().split("_")[0] res = layer.dataProvider().addAttributes([QgsField("density", QVariant.String)]) layer.updateFields() fieldIndex = ...


2

You can set the base directory of the "Add Vector Layer" dialog, reflecting the latest active layer's path, this way: import os from PyQt4.QtCore import QSettings def setOpenDir( layer ): # Check if layer exists, has a proper path, and is of type vector if layer and os.path.exists( layer.source() ) and layer.type() == 0: layerPath = ...


2

Connect to the project read signal to know when a project is loaded def project_loaded(dom): print QgsProject.instance().readPath("./") QgsProject.intance().readProject.connect(project_loaded)


2

Keep things simple, you don't need a special function selectedfeatures here, you can do everything at once (try your script in the Python console before). 1) you don't need the Valtestand state_and_cities variables: layer = iface.activeLayer() idx = layer.fieldNameIndex('name') idx1 = feature.fieldNameIndex('state') for feature in layer.selectedFeatures(): ...


2

If you only want the point coordinates, you don't need Shapely, simply use the appropriate key of the dictionary: for point in filter_list: print point['geometry']['coordinates'] (270977.604378, 153144.810665),... If you want a Shapely geometry, use the shape function of Shapely: from shapely.geometry import Point, shape for point in filter_list: ...


1

OK. I can point you to code snippets and resources to help you get to your goal. PyQGIS Cookbook is a great place to look if you are just getting started with scripting. First you need to iterate through the groups and layers. This is a good reference for it. You can do something like # Iterate through the Legend to find all groups and layers root = ...


1

I'm not sure if it helps for you but in principle you set paths either by writing the commands into the DOS-box (started with cmd) or by setting them via a batch file. To use eclipse with QGIS the following lines have been recommended. All you have to do is to write them into a plain text file and give its filename a .bat ending. Just make sure to replace ...


1

One way to achive this is store the user activity in a variable like self.user_action then in your accept() method (which is called when you click Run button), use it to determine what to do def accept(): if self.user_action == 'DROPDOWN_SELECTION': self.run_function1() elif self.user_action == 'MAP_SELECTION': self.run_function2()


1

Finally I found the answer : using the QgsLegendModelV2()class, and its functions inherited from QgsLayerTreeModel : "index(i,j)" to select each legend item and "rowcount" to obtain the rows number. All in a "for x in xrange" loop. That gives: for i in self.composition.items(): if isinstance(i,QgsComposerLegend): legend = i for i in ...


1

I realized I needed to set the coordinate system of shp to WGS84, then write out to a new file and specify the local coordinate system - then add that layer to the map and buffer it. Worked! Here is my updated code: from qgis.core import * from qgis.analysis import * from PyQt4.QtCore import * from PyQt4.QtGui import QInputDialog from qgis.utils import ...


1

I believe you want this line: nearCity = feature.attributes()[idx] to be: nearCity = f.attributes()[idx] Using the feature variable will always point to the last value in selection. (This is untested advice, so I might not be understanding something fundamental here.)


1

I'd suggest setAttributes() which takes the list of attribute values, for example feat.setAttributes([id,x,y]) You can find more examples in the Vector section of the PyQGIS Developer Cookbook. It's true that the C++ Api doc can be difficult to interpret that's why the PyQGIS Cookbook is important and any outdated code snippets should be reported on the ...


1

in your case qgis.utils.iface.activeLayer() return the last selected one. To obtain selected layers use the ability of the TreeView that contain the layer list. More directly: iface.layerTreeView().selectedLayers() more detail exploring the class QgsLayerTreeView: http://qgis.org/api/classQgsLayerTreeView.html obviously this work after legend refactoring ...


1

Do you need the memory layer at all? Have a look at the "directly from features" example in the PyQGIS cookbook to see how to create a persistent Shapefile from features, so that you avoid creating a memory layer.


1

You can combine both layers' extents and increase a bit the resulting bounding box to make sure all geometries and labels are visible. In the following code, I i) take first and second layers from the ToC, ii) combine their extents, and iii) scale the resulting bounding box by 10%: extent = QgsRectangle() extent.setMinimal() layers = [ ...



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