Hot answers tagged

7

You can define a function which adds the project filename as an attribute and connect this function with the event that adds features. You can use the following code, change the name of the field to whatever you choose (I used Name) and paste it into the Python Console. Now whenever you add a new feature, the field will be populated with the current project ...


6

Better than a script, there's a plugin to achieve it, and it's called "Remove empty layers from the map." http://plugins.qgis.org/plugins/RemoveEmptyLayers/ Disclaimer: I'm the plugin's author.


5

Right, you need to use QSettings to store values across QGIS sessions. QSettings is multi-platform, so you don't need to worry about where it stores the data on Linux, on Windows, or on Mac, it handles it for you. You need to call QSettings in this way: from PyQt4.QtCore import QSettings settings = QSettings() You can use QSettings() every time you ...


5

Let me share how it works for me: self.setWindowTitle(title) #data = 'Recordset back from postgis' nb_row = len(data) nb_col = 2 qTable.setRowCount(nb_row) qTable.setColumnCount(nb_col) for row in range (nb_row): for col in range(nb_col): item = QTableWidgetItem(str(data[row][col])) qTable.setItem(row,col,item) ...


4

The error occurs because the plugin (in its version 0.51) does not filter out Raster layers from the QGIS ToC and lists them in its own GUI. The plugin should only deal with Vector layers, since it acts on vector geometries. I sent a pull request to the plugin's author with code to fix this problem, which was accepted and merged by him. The author has just ...


3

Another option would be to use os.wallk using .endwith() method, see example below: import os dir = 'C:/Temp' for root, dirs, files in os.walk(dir): for f in files: if f.endswith('.dat'): layer = QgsRasterLayer(os.path.join(root,f), f) QgsMapLayerRegistry.instance().addMapLayer(layer)


3

If your attributes have aliases, you can get a Python dictionary of aliases calling: lay = iface.activeLayer() lay.attributeAliases() This gives you something like: {u'type': u'Municipality Type', u'name': u'Municipality Name'} If you have a specific field index and you want to get its alias, you can use: lay.attributeAlias( fieldIndex ) Which ...


3

It's a known issue, which will be fixed when QGIS moves to QGIS 3.0 development (since the fix could potentially break existing plugins). To work around it, you need to force a copy of the geometry: geom = QgsGeometry( lay.getFeatures().next().geometry() ) Technical explanation below: Calling just geom = lay.getFeatures().next().geometry() results ...


3

Nice question! Say that you have a vector layer referenced: lyr = iface.activeLayer() At this point, I assume you start an edit session and digitize some features. Now you can use the QgsVectorLayerEditBuffer class, in this way: if lyr.editBuffer(): print len( lyr.editBuffer().addedFeatures() ), "features to add!" addedFeatures gives you a ...


2

Thanks to BradHards and ThomasG77 who sent link for interpolation code. This is what I meant: import qgis.analysis layer = QgsVectorLayer(pathToFile, 'nameOfLayer','ogr') ld1 = qgis.analysis.QgsInterpolator.LayerData() ld1.vectorLayer = layer ld1.zCoordInterpolation=False ld1.InterpolationAttribute = 7 #column index, start with 0 ld1.mInputType = 1 ...


2

It's likely caused by the fact that the canvas renders a cached image instead of requesting a new one. This will cause the cache to be cleared. timer.timeout.connect(layer.triggerRepaint) To get a reference to your layer either create it from python or use the QgsMapLayerRegistry.


2

I reproduced this in QGIS 2.14.2 on Ubuntu, both in Console and in a saved .py script. The issue you linked to has the answer - change your call from .geometry() to .geometryAndOwnership(). I tried that and it fixes the problem. According to the API docs this method is deprecated and you should use constGeometry() instead - but I find this also segfaults. ...


2

This should work: crs = originalLayer.crs().authid() # without () after originalLayer layer2 = QgsVectorLayer("Point?crs={0}".format(crs), "auxlayer", "memory")


2

Thanks to the qgis-dev mailing list and to Denis Rouzaud, this is the answer.. class MyDialogClass(UiClass): def __init__(self): self.setupUi() self.myLayerComboBox.layerChanged.connect(self.myConnectMethod) @pyqtSlot(QgsVectorLayer) def myConnectMethod(self, layer) self.myDataDefinedButton.init(layer, .....) so the link between the 2 ...


2

Yes, there is a way. Imagine you launch QGIS this way from the command prompt: $ qgis /geodata/my_raster.tif Open the QGIS Python Console and type this command: QgsApplication.arguments()[1:] You should get a list of arguments passed to QGIS from the command line: [u'/geodata/my_raster.tif'] To get the raster file name you could do something like ...


2

By using a temporary file, as reassignment of the standard output (Python Console), next code works. ... import sys, os import tempfile as tmpf ... else: #save a reference to the Python Console of QGIS before reassignment oldstdout = sys.stdout #creating a temporary file file = ...


2

You can use glob.glob to get a list of all dat files in the directory and use a loop to add them to QgsMapLayerRegistry


2

To automatically open the QGIS Python Console when QGIS starts, you can read How to show Python console at QGIS program start. However, I guess your ultimate intention is to run the script (even if it doesn't run from the QGIS Python Console), so you can create (if it doesn't exist already) a startup.py file in the QGIS Python directory: On GNU/Linux: ...


2

In QGIS you can try the Distance Matrix of Saga (under Processing > Tools > Saga > Shapes - Points). This calculates a distance matrix for all points in one layer only, but does include an ID. Just combine the two layers into one (e.g. with Vector > Data Management Tools > Merge Shapefile to One). Make sure that you have some attribute that makes it possible ...


2

You can actually do both (add a field and write values in it) using a single QGIS Processing algorithm: processing.runalg('qgis:fieldcalculator', metro_roads, 'STRNAME', 2, 20, 0, True, "concat('This is row # ', $rownum)", path+"Metro_roads_new.shp") This is what each parameter means: processing.runalg('qgis:fieldcalculator', input_layer, field_name, ...


2

I think when you're adding a layer and you want to add it to the composer to save it as an image, you need to make sure the layer is visible. Try adding this line after your for loop: iface.legendInterface().setLayerVisible(layer, True) So now it should look like: for layer in layers: iface.legendInterface().setLayerVisible(layer, True) myFile = ...


2

Without knowing exactly where you're up to it's a bit difficult, but here's the nuts and bolts: layermap = QgsMapLayerRegistry.instance().mapLayers() RemoveLayers = [] for name, layer in layermap.iteritems(): if layer.isValid(): if layer.type() == QgsMapLayer.VectorLayer: if layer.featureCount() == 0: ...


2

After some search I finally found a working solution: As I saw that layer.maximumValue(idx) always kept the same value until I commited changes, I added the number of new elements and that are pending to be commited to this variable. This way I always get serial (autonumeric) number. Idea taken from here: def openProject(): from qgis.core import ...


2

Here's what I did to implement a second Toolbar button and its corresponding dialog: Edit the plugin.py file to add a run2() method, a self.dlg2 variable, a new action in initGui(), and this import: from plugin_dialog2 import pluginDialog2 Copy and paste the UI file and rename it as form2.ui (optionally, open it in Qt-Designer and change the windowTitle ...


1

You could use: iface.mapCanvas().saveAsImage( "myGeoreferencedView.png" ) It exports both PNG and PNGw files. The latter is known as World file and contains coordinate information.


1

rasterMenu = qgis.utils.iface.rasterMenu() for rasterMenuItem in rasterMenu.actions(): if 'Heatmap' in rasterMenuItem.text(): heatmapMenu = rasterMenuItem for heatmapMenuItem in heatmapMenu.menu().actions(): print heatmapMenuItem if 'Heatmap' in heatmapMenuItem.text(): heatmapMenuItem.trigger()


1

Building on what Peter has suggested, you could try using the following code (note that you did not define file_date in your code so I used the basename of the raster instead but you can modify it): from PyQt4 import QtGui from PyQt4.QtCore import * from PyQt4.QtXml import * from PyQt4.QtCore import QSize, QFileInfo from PyQt4 import QtCore from qgis ...


1

I dont see any problem with that.


1

Found a way, basically you just need to specify the column when populating the QTableWidget (mentioned in comment): qTable = self.dockwidget.tableWidget data = [] group1 = root.findGroup('Group1') group2 = root.findGroup('Group2') for child in group1.children(): data.append(child.name()) for child in group2.children(): data.append(child.name()) ...


1

I think if you want to iterate over your layer using the Clip function, you need to select each polygon first before applying the algorithm. Try running the following: layer_adm_level = QgsVectorLayer(base_path + adm_level + ".shp",'adm_level','ogr') if not layer_adm_level.isValid(): print "Layer failed to load!" for adm_level_feature in ...



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