15

After getting around cookbook, the best place to learn is referring the QGis API Documentation. In this case we are looking for zoom functions, which are related to map canvas. So check if QgsMapCanvas class contains something. Zoom functions available in QGis are provided in QgsMapCanvas Class. >>> canvas = qgis.utils.iface.mapCanvas() >>&...


14

You could use the following code which is heavily based on the answer from this post: How to delete selected features in QGIS using Python layer = iface.activeLayer() with edit(layer): for feat in layer.getFeatures(): layer.deleteFeature(feat.id()) Edit: Thanks to @GermánCarrillo, a more efficient method could be to delete all features at ...


14

You could just replace: layers = iface.legendInterface().layers() with layers = [layer for layer in QgsProject.instance().mapLayers().values()]


12

The answer is almost completely contained in a post I recently wrote. The extent is returned as a QgsRectangle() object with the following code: layer = iface.activeLayer() # load the layer as you want ext = layer.extent() For getting the coordinates of the vertices for the current layer, you may run this code: xmin = ext.xMinimum() xmax = ext.xMaximum() ...


10

You can start QGIS Python console when opening a project by writing a couple of lines in QGIS->Project->Project Properties: def openProject(): import qgis qgis.utils.iface.actionShowPythonDialog().trigger() Make sure you enable macros on your project, this way: Settings->Options->General->Enable macros: Always As you want the ...


9

The equivalent of layers = self.iface.legendInterface().layers() in QGIS 3.0 is layers = [tree_layer.layer() for tree_layer in QgsProject.instance().layerTreeRoot().findLayers()] This recursively finds all layers and returns them in the same order as listed in Layers Panel.


7

QGIS offers you several classes for logging messages into the Log Messages Panel (i.e., no need to print debug messages from your plugin into the QGIS Python console). You could even easily create a tab in such panel exclusively for your plugin using QgsMessageLog class: QgsMessageLog.logMessage( "Info message from plugin", "My Plugin", 0 ) QgsMessageLog....


7

In addition to @bcollins answer, if you want to change your variables you have defined inside the QGIS python console you can try this approach: Define a variable which holds all variables before you start programming: my_dir = dir() Do your magic with gis, for example: my_variable = 42 my_other_variable = "foo" Then do something like this: for ...


5

Usually when I run processes, I define the extent instead of leaving it blank (which often results in errors like you have shown). So you could use something like the following: # Define input and output paths path = "D:/Developpement/Debits_cartes_alea/Donnees_test/flow_direction.tif" output = "D:/Developpement/Debits_cartes_alea/Donnees_test/1sortie.tif" ...


5

In QGIS3 you can use truncate() bool QgsVectorDataProvider::truncate() Removes all features from the layer.


5

You already know the general procedure and have experience with the script How to batch "Layer save as"-process in QGIS?. Consider the line QgsVectorFileWriter.writeAsVectorFormat(layer, pathToFile + newName, "utf-8", None, "ESRI Shapefile") You have to change 2 things. 1) To get the original file name add following lines to the top of the loop ...


5

There are a couple of builtin functions you should consider for this. dir() will gives you the list of in scope variables globals() will give you a dictionary of global variables locals() will give you a dictionary of local variables but you may run into trouble because you could inadvertently delete some variables that QGIS sets. So something like this ...


5

A method which I used a while ago was to begin each variable name with an underscore ("_"). As there are no other variables beginning with a single underscore (only double), you can search for all these variables and delete them accordingly: # Define user variables _foo1 = "Hello world" _foo2 = "bar" _foo3 = {"1":"a", "2":"b"} _foo4 = "1+1" # Create list ...


5

you were on the right track you just need to go a step further. See the QGIS documentation for QgsRectangle Basically, you do: get the current Layer layer = iface.activeLayer() get the extent which is a QgsRectangle object ex = layer.extent() and there extract the Values with: xmax = ex.xMaximum() ymax = ex.yMaximum() xmin = ex.xMinimum() ymin = ex....


5

You can achieve what you want in two steps: You need to extract the values of DEM raster data into point shapefile using QGIS Point sampling tool. You need to make sure that the raster data and the point shapefile have the same projection. If the raster data and point shapefile have different projections, the output point shapefile will have empty fields ...


5

These are mentioned in the QGIS documentation: layer = iface.addVectorLayer("/path/to/shapefile/file.shp", "layer name you like", "ogr") So the parameters are: Path to shapefile; The name you want to give to the shapefile when it is loaded; The name of the vector data source/provider.


5

You generally shouldn't use print() for debugging this as the Python Console is not built to really help you here. The best advice is to use QgsMessageLog.logMessage as that will scroll with the output and log out into the log window (bottom right button in the status bar)


4

You sure can. import qgis.utils inqgis = qgis.utils.iface is not None In QGIS this will return True outside it will return False


4

All the zoom options under the 'View' menu can be executed in the python console by the following code. eMenu = self.iface.viewMenu() eMenu.actions() [index].trigger() Replace the "index" with the index number of the zoom action you want to perform. For eg., To perform 'zoom to selected features', use eMenu.actions() [12].trigger()


4

I was able to provide a full solution in the following question: How to compute an interpolation raster from the python console in QGIS? I will repost the answer here as well, because of the large interest it seems to attract: Answer: The documentation on pyqgis is not very self-explanatory, but i figured out how to properly call the associated ...


4

Just to add to @Jakob's brilliant answer, you can use name() to print the name of the layer: vl = QgsMapLayerRegistry.instance().mapLayersByName('Province')[0] print vl.name() If you have multiple layers loaded, you can use the for loop which identifies the first layer found, prints the name, then repeats for any subsequent layers: layers = ...


4

You need to access the attributes of the features of the table. lyr = iface.activeLayer() features = lyr.getFeatures() for ft in features: attrs = ft.attributes() print attrs To access first column use print attrs[0] Column names can be add with: lyr = iface.activeLayer() features = lyr.getFeatures() field_names = [field.name() for field in ...


4

Despite the author's intention, I think the plugin won't be easily usable out of QGIS (or even from the QGIS Python Console) as is. Inside the operate() function, the code is relying on plugin dialogs and on dialog methods like: self.dlg.OuptDir.text() In particular, the error you're getting is due to these lines in operate(), which give layertocut a ...


4

In the console, the plugins folder is in the PYTHONPATH (no need of import imp) Simply use (Is there a way to access QGIS plugins in Python?) import gridSplitter gridSplitter.__file__ '/Users/my/.qgis2/python/plugins/gridSplitter/__init__.pyc' The content of the module with see (dir for humans) see(gridSplitter) help() .classFactory() ...


4

You can use a project macro to execute python code whenever you open the project. Navigate to File > Project properties > Macros and insert the code in the openProject() function. def openProject(): layer = QgsMapLayerRegistry.instance().mapLayer('the_layer_id') def update(): field = layer.fieldNameIndex('mod') e = QgsExpression( " ...


4

if you're using qgis 2.18.1, use save as.., and the select fields to export.. option. this is a fairly recent addition, I think. I find it very useful with Openstreetmap data, which often has lots of empty columns. it's also a lot faster than deleting columns from the attribute viewer, which was painfully slow with hundreds of columns :)


4

ST_Line_Locate_point only works with Linestrings, not MultiLinestrings. This makes sense, as the return value is the percentage distance along the line that the point occurs, which wouldn't make sense with a MultiLinestring, as you wouldn't know which of the constituent Linestrings was being referred to. You can fix this by using ST_Dump. WITH lines (geom) ...


4

I think you can't successfully apply a QgsSimpleLineSymbolLayerV2() symbol to a polygon because it belongs to linestring geometries. The allowed symbols for polygons are: Simple fill (QgsSimpleFillSymbolLayerV2); Gradient fill (QgsFillSymbolLayerV2); Centroid fill (QgsCentroidFillSymbolLayerV2); Line pattern fill (QgsLinePatternFillSymbolLayer); Point ...


4

You almost have it... just loop over selected_features and indent the code properly: lyr = iface.activeLayer() selected_features = lyr.selectedFeatures() featList = [] for feat in selected_features: featList.append(feat.attributes()) featList.sort() for f in featList: print f


4

When you type vh as an expression in the Field Calculator, it assumes you are calling a field. If you type 'vh' (note the single quotes), it treats this as a string value. In your code, you are doing the former (i.e. calling a field name). What you will need to do is call it as a string instead but be careful when using single quotes to specify a string ...


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