13

Interesting question! I couldn't find any native signal emitted when an attribute table is opened or closed so I would call this solution a fairly inelegant workaround but it seems to work well enough. I found that QApplication has a focusChanged(old, new) signal which is emitted whenever the widget focus changes e.g. opening/ closing dialogs or clicking ...


10

Welcome to GIS.SE! As you thought, there is a way to know if a field exists in a layer not by iterating features but by looking at the layer structure. In the QGIS Layers Panel, select a layer. Then in the Python Console inside QGIS, run the following code: field_name = "my_field" layer = iface.activeLayer() # Gives you the layer you have selected ...


10

If you are using QGIS 3 that book is outdated in hopes of improving your abilities around PyQGIS 3. Following code has 3 necessary corrections to run as expected: layer = QgsVectorLayer('Point?crs=epsg:4326', 'MyPoint' , "memory") pr = layer.dataProvider() pt = QgsFeature() point1 = QgsPointXY(20,20) #1 correction pt.setGeometry(QgsGeometry.fromPointXY(...


10

The easiest for me would be to check the properties of the symbology layer which contains symbol properties affecting the whole layer: dir(symbol) >>>['DynamicRotation', 'Fill', 'Hybrid', 'Line', 'Marker', 'RenderHint', 'RenderHints', 'ScaleArea', 'ScaleDiameter', 'ScaleMethod', 'SymbolType', '__class__', '__delattr__', '__dict__', '__dir__', '...


10

Use this script: selection = [] def selection_changed(selected, deselected, clearAndSelect): global selection # If the user deselects feature(s), remove ID's from list if deselected: selection = [ID for ID in selection if ID not in deselected] print(f"Selection: {selection}") else: # get newly selected IDs ...


10

By type name (typeName()): int_types = ["Integer", "Integer64"] int_fields = [field for field in iface.activeLayer().fields() if field.typeName() in int_types] OR by type number (type()): int_types = [2, 4] # 2: Integer, 4: Integer64 int_fields = [field for field in iface.activeLayer().fields() if field.type() in int_types] Type of some ...


10

You use wrong TYPE code. You have to use 2 for rectangular grid. 3 means diamond. params = {'TYPE':2, ...} # 2: rectangle For more details about the algorithm try import processing processing.algorithmHelp("qgis:creategrid") and get more info: Create grid (native:creategrid) This algorithm creates a vector layer with a grid covering a given ...


10

You must set setUseLayerName() to False to name legend tree layers manually. # # previous lines # for i, layer in enumerate(layersToAdd): tree_layer = root.addLayer(layer) tree_layer.setUseLayerName(False) tree_layer.setName(names[i]) legend.updateLegend() ...


10

You set feature fields to empty QgsFields. fields = QgsFields() # fields is empty feature.setFields(fields) # you set the empty fields Instead, pass layer.fields() to QgsFeature. feature = QgsFeature(layer.fields()) You also get NULL values, because you add the feature to the layer (provider.addFeatures([feature])) before you populate the fields. Use this ...


9

The input parameters can be accessed as a dictionary object, so parameters['SPECIES_POINTS'] will give you the path to the input layer. The call to the algorithm would then be: pointsReprojected = processing.run("native:reprojectlayer", { 'INPUT': parameters['SPECIES_POINTS'], 'TARGET_CRS': CRS, 'OUTPUT' : ...


9

try: from qgis.core import QgsApplication QgsApplication.qgisSettingsDirPath() for show profiles folder https://qgis.org/api/classQgsApplication.html#a89ad50b0d0fd60ccae803f22f6c5cf46


9

You can use this script. First, select a the layer, then run the script. It adds the result as a memory layer. You should save the result as a new file manually or using a code. input_layer = iface.activeLayer() max_area_x = ["max_area_1", "max_area_2", "max_area_3"] for i in range(len(max_area_x)): # OR for i in [0, 1, 2] input_layer = processing.run("...


9

Change layer.setSubsetString("GAMME_DE_S=VSR") to layer.setSubsetString("GAMME_DE_S='VSR'") Then to add the layer, if not layer.isValid(): print("Layer failed to load!") else: QgsProject.instance().addMapLayer(layer) A general tip to avoid issue with syntax in setSubsetString is add the layer manually with the GUI, ...


8

I'm going to answer my own question in two ways. First, I'll use the example from the PyQGIS Developer Cookbook. I initially struggled with this example but eventually got it working, so here is a simplified example below with some additional annotation and comments. I hard coded some values which you may want to adapt. Here is the full code as an example: ...


8

The easiest approach is to run the algorithm through the GUI, and then look in the Processing "history". You'll see the equivalent Python command shown there for the operation you just performed via the gui.


8

The order of when you set the extent, add the map to the layout, and resize the rectangle is important. Steps to add a map to a new layout in QGIS 3. Instantiate the map object with QgsLayoutItemMap(layout) Set a base Rectangle Set the extent Add the map to the layout object, layout.addLayoutItem(map) Now you can Move & Resize the rectangle as ...


8

Great idea you need place startup.py in C:\Users\<username>\AppData\Roaming\QGIS\QGIS3 and add missing import ,and voilá from qgis.utils import iface from PyQt5.QtWidgets import QAction import webbrowser def open_gis_se(): webbrowser.open('https://gis.stackexchange.com') iface.helpMenu().addSeparator() gis_se_action = QAction('Go to gis....


8

Updated answer: Below is a recipe to apply a graduated renderer based on values in an attribute field, specifying the number of classes and color ramp. # Set layer name and desired paremeters layer_name = 'Your_layer_name' ramp_name = 'Spectral' value_field = 'Your_field_name' num_classes = 5 classification_method = QgsClassificationEqualInterval() #You ...


8

NULL is defined in qgis.core from qgis.core import NULL with edit(layer): for feature in layer.selectedFeatures(): feature.setAttribute('distance', NULL) layer.updateFeature(feature)


8

You can use the following structure: # # previous lines # page_label = QgsLayoutItemLabel(layout) # # other label settings here # text = "[% 'Page: ' + to_string(@atlas_featurenumber ) + '/' + to_string(@atlas_totalfeatures)%]" page_label.setText(text) layout.addLayoutItem(page_label) myAtlas.beginRender() for page in range(myAtlas.count()): ...


8

Personally, I prefer to use the changeAttributeValues() method of QgsVectorDataProvider (see API docs here) as I find it more reliable. This method takes an attributes map which is basically a dictionary where the key is a feature id and the value is a second dictionary comprising field indexes as keys and the new attributes as values. I have tested this ...


7

To change QgsFeature geometry in QGIS 3 you have to call setGeometry() explicitly. geom = feat.geometry() geom.translate(100, 100) feat.setGeometry(geom) Explanation: In QGIS 2 geometry() returns a pointer, so it can be modified in place. QgsGeometry* QgsFeature::geometry() //QGIS 2 In QGIS 3 geometry() returns value instead of a pointer. Additionally ...


7

You attempt to set a name to a deleted object. You need to create a new object : [...] for layout in layouts_list: if layout.name() == layoutName: manager.removeLayout(layout) layout = QgsPrintLayout(project) layout.setName(layoutName) [...]


7

Here is the code which is working for me: urlWithParams = 'type=xyz&url=https://a.tile.openstreetmap.org/%7Bz%7D/%7Bx%7D/%7By%7D.png&zmax=19&zmin=0&crs=EPSG3857' rlayer = QgsRasterLayer(urlWithParams, 'OpenStreetMap', 'wms') if rlayer.isValid(): QgsProject.instance().addMapLayer(rlayer) else: print('invalid ...


7

layer = iface.activeLayer() intfields = [f for f in layer.fields() if f.typeName().startswith('Int')] print(intfields) Found typeName here


7

From Docs, you can pass a QgsFeatureRequest to getFeatures() https://qgis.org/pyqgis/3.0/core/Vector/QgsVectorLayer.html#qgis.core.QgsVectorLayer.getFeatures QgsFeatureRequest describe the way you retrieve the QgsFeature You can use setSubsetOfAttributes (https://qgis.org/pyqgis/3.0/core/Feature/QgsFeatureRequest.html#qgis.core.QgsFeatureRequest....


7

You should "very often" use QgsFeatureRequest : https://qgis.org/api/classQgsFeatureRequest.html https://qgis.org/pyqgis/master/core/QgsFeatureRequest.html If you need only a subset of attributes, and also maybe you don't need the geometry, you can do something like: expected_fields = ['KKOD', 'KATEGORI'] layer = iface.activeLayer() indexes = [layer....


7

You should use setRenderer3D method of QgsMapLayer. layer.setRenderer3D(renderer) QgsVectorLayer inherits that method from QgsMapLayer.


7

You can use the QgsVertexMarker and QgsRubberBand classes to show points on the map canvas as temporary markers which are not part of a layer. Here are are a couple of short examples to get you started. Vertex Marker: canvas = iface.mapCanvas() lon = 131.2 lat = -12.5 pnt = QgsPointXY(lon, lat) m = QgsVertexMarker(canvas) m.setCenter(pnt) m.setColor(...


7

iface.addToolBarIcon method adds an icon to the Plugins toolbar. It doesn't add the icon to the toolbar area. You should open Plugins toolbar. (3rd one is Show Time icon in the image)


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