New answers tagged

0

NNJoin There is a more advanced plug with in QGIS plugin repo called NNJoin which joins two vector layers (the input and the join layer) based on nearest neighbor relationships. please refer the page NNJoinPlugin


3

Use this expression for the label: '1 : ' + to_string( round( map_get( item_variables('MyMap'), 'map_scale' ), 0 ) )


3

Create a list of copies of the existing columns in your table. You can then create additional QgsLayoutTableColumn objects, set their attribute and heading values and append them to the list of columns. Finally, use the setColumns() method on your table passing the updated column list and refresh the layout. The code below should work for you. # your ...


7

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() ...


0

The line shpSavedLayer.setCrs(projectCrs) overrides your layers' CRSs regardless of their coordinates' actual CRS. Don't do that and your map should look as expected. You only need to use that method if you want to fix a wrongly detected or missing CRS. You must not use it if your data is valid and correct.


6

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()): ...


3

You can use the code snippet below: pdf_headers = ['Champ','Superficie (ha)','Superficie épandable (ha)'] #retrieve layout table columns cols = pdf_table.columns() #construct a new list containing cloned QgsLayoutTableColumn objects new_cols = [col.clone() for col in cols] #iterate the cloned columns and use setHeading() method to set each #column's ...


4

You need the following short snippet of code to construct a QgsLayoutTableStyle() object, set its enabled and cellBackgroundColor attributes, and then pass it as the 2nd argument to the setCellStyle() method. table_style = QgsLayoutTableStyle() table_style.enabled = True table_style.cellBackgroundColor = QColor(166, 206, 227, 255) pdf_table.setCellStyle(...


2

It's a missing quotes error. A good advice to debug queries build like this or all strings build with variables, it's just to print the result to see if it's good. So, what if we debug the good one ? print( '(SELECT * FROM schema.layer1 WHERE layer1.id=' + str(dlg.comboBox.currentText()) + ')' ) # Note that a more Pythonic way to write this is : # for ...


3

You need to pass the algorithm parameters as a dictionary. Try something like: raster = [l for l in QgsProject().instance().mapLayers().values() if isinstance(l, QgsRasterLayer) and 'h_Max' in l.name()][0] processing.runAndLoadResults("gdal:contour", {'INPUT':raster, 'BAND':1, 'INTERVAL':10,# adjust interval as required '...


2

Normally, when using a vector tool, processing.run with TEMPORARY_OUTPUT returns ["OUTPUT": QgsVectorLayer]. I have already learned that if is_child_algorithm=True is added, it returns a temporary layer id. The reference of a temporary layer can be obtained by means of context.temporaryLayerStore(). You can add the following lines to your ...


1

You may try below code (tested with my own database table using data with EPSG 4326) Some of the code in the sample can help you for other purposes as it was an existing script I've updated to manage the PostGIS layer part. You may clean some of the code depending of your requirements import os import sys from qgis.core import (QgsApplication, ...


2

Ok. I figured it out. I am not sure if this is the best practice but it works. First of all I use a pyqtSignal: class BatchLoadRasters(QgsTask): """This shows how to subclass QgsTask""" progress= QtCore.pyqtSignal(bool, object) # For reporting progress Then I move the layer to the main thread and emmit this signal when ...


1

We don't know that the other parts of your code look like. So it is hard to provide a perfect answer. But the followings will give you an idea. It worked for me in the project with GUI. from qgis.gui import QgsLayerTreeMapCanvasBridge ... canvas = QgsMapCanvas() root = QgsProject.instance().layerTreeRoot() bridge = QgsLayerTreeMapCanvasBridge(root, canvas) ...


9

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 ...


0

So, the empty row issue was resolved for the following line: with open(csvFile, 'r') as csvSrcFile, open(csvLayerUriList[csvLayerUriIndex1], 'w') as csvTrgtFile: The Python open() function requires the newline = ''argument in Windows as explained here. So, the corrected code looks like this: with open(csvFile, 'r', newline='') as csvSrcFile, open(...


0

for this block of code: #joins the shape layer to the proper CSV field shpField = 'puma' csvField = 'puma' joinCsvName = shpSavedLayer.name().split("-")[0] for csvSavedLayer in csvSavedLayerList: csvSavedLayerName = csvSavedLayer.name() if csvSavedLayerName == joinCsvName: joinCsvLayer = csvSavedLayer joinCsvField = [] joinCsvField....


5

I found a solution worked for me. Add this script to the "Function Editor": from qgis.core import * from qgis.gui import * @qgsfunction(args='auto', group='Custom') def isSelected(feat, field, feature, parent): layer = QgsProject.instance().mapLayersByName(field)[0] for f in layer.getSelectedFeatures(): if f['fid'] == feat['fid']:...


0

The accepted answer works, but I was looking for a method that could apply colour ramps to both raster and vector data. Notes on previous answers: The renderer.updateClasses method is deprecated since v3.10 (the QgsClassificationMethod class should be used instead). QGIS is capable of interpolating colours for classes without using external libraries (but ...


1

With your help I ended up using a generator like this (for when I forget it): layer = iface.activeLayer() fields_to_return = ['kommunkod','lanskod', 'lansnamn'] indexes = [layer.fields().indexFromName(field) for field in fields_to_return] request = QgsFeatureRequest() request.setFlags(QgsFeatureRequest.NoGeometry) request.setSubsetOfAttributes(indexes) ...


6

iface is predefined variable in QGIS. It is defined while QGIS starts and refers to QGIS interface. That means you cannot use iface in your standalone application. You can use QgsProject.instance() to get the attributes of a project in your application. project = QgsProject.instance() To get the active layer use the script below: def activeLayer(): ...


Top 50 recent answers are included