New answers tagged

0

Next function can change raster values greater than 98 for 0. def changeRasterValues(band): fmttypes = {'Byte':'B', 'UInt16':'H', 'Int16':'h', 'UInt32':'I', 'Int32':'i', 'Float32':'f', 'Float64':'d'} data_type = band.DataType BandType = gdal.GetDataTypeName(band.DataType) raster = [] for y in range(band.YSize): scanline = ...


0

Maybe this video will help you. https://www.youtube.com/watch?v=Bp_UhSKH3NQ


1

The API documentation says: "The context parameters theExtent, theWidth and theHeight are important to identify on the same zoom level as a displayed map and to do effective caching (WCS; Web Coverage Service). If context params are not specified the highest resolution is used". Then, I think that it always returns one value. For this reason, if you want to ...


1

You want QgsPaintEffect. It's the base class from which all the live layer effects inherit: https://qgis.org/api/classQgsPaintEffect.html QgsSymbolLayerV2.setPaintEffect() is probably what you need: https://qgis.org/api/classQgsSymbolLayerV2.html#a5d4f3921ee369094736f17ec44361620


0

Sleep blocks the execution of your script for a while, synchronously. One solution for your question is to use a QTimer, which controls when to execute functions and it's asynchronous, i.e., it allows other functions to continue to run (think of a map.refresh()) while waiting some milliseconds to run the next instruction. Have a look at How to iterate over ...


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


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


0

You don't mention if you're doing it, but as you're writing a standalone application, you need to create a Map Canvas by yourself, in this way: self.map_canvas = QgsMapCanvas() Then you can set the map tool using self.map_canvas: tool = PointTool( self.map_canvas ) self.map_canvas.setMapTool( tool ) Why not to write the parenthesis in ...


1

To fix the error: NameError: global name 'QgsMapLayerRegistry' is not defined Just add the following at the top of your script: from qgis.core import QgsMapLayerRegistry Tip: What I do normally when I receive similar errors is to type the class into the Python Console. It will then provide you with a list of classes and libraries in which they ...


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


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.


1

You can use None as output parameter. Doing so, QGIS Processing creates a temporary vector file for you: processing.runandload("qgis:createpointsalonglines", "Clipped" ,100,0,0,None) Or: res = processing.runalg("qgis:createpointsalonglines", "Clipped" ,100,0,0,None) iface.addVectorLayer(res['output'],'my points','ogr') In my case (on a GNU/Linux), the ...


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.


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


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


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


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


0

Arcgis solution, but applicable to any decent GIS. Project your layers. Calculate xy columns Join table to another by address. Calculate distance between 2 pairs of coordinates


1

Got it! Overriding functions of the QgsHistogramDiagram only works, if there also exists an override of the clone() function (similar to other inherited qgis-objects), like: def clone(self): return OwnHistogram()


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


0

Solution 2 doesn't work because 'my_layer.getFeatures(request)' is a QgsFeatureIterator object. You have to create, for example, a memory layer with the features "into" this object. In my case, I used the next shapefile, with 8 features, for selecting the features with indexes 1, 5 and 7. The complete code is: layer = iface.activeLayer() request = ...


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


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


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)


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


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 dont see any problem with that.


1

Summarizing the comments so this question can be marked as answered: VRT does not support any kind of indexing. There is an open GDAL ticket about this http://trac.osgeo.org/gdal/ticket/5762. However, there may be a workaround. It should be possible to create a set of smaller .VRT files which contain a reasonable amount of images and then build another vrt ...


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


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


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


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


0

You're close! You might be receiving errors because when you run code from the script, you need to import the relevant modules for the code to run. QGIS loads most of these at startup but the scripts are externally run. Modifying your code slightly, you could use: ##Example=name from qgis.core import QgsVectorLayer, QgsMapLayerRegistry vectorLyr = ...


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


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


1

It seems that it depends on the font you're using. Try alternating among the following options: Bold: layer.setCustomProperty("labeling/namedStyle", "Bold") Italic: layer.setCustomProperty("labeling/namedStyle", "Italic") Bold and Italic: layer.setCustomProperty("labeling/namedStyle", "Bold Italic") If neither Bold or Italic are selected in your ...


0

You might use this code if you want but you need to improve it. from PyQt4.QtCore import * from PyQt4.QtXml import * from PyQt4.QtGui import * layers =iface.legendInterface().layers() canvas=iface.mapCanvas() for layer in layers: myFile = "your qpt path" myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() ...


1

check this: from PyQt4.QtCore import * from PyQt4.QtXml import * myFile = "PATH_TO_COMPOSER_TEMPLATE" myTemplateFile = file(myFile, 'rt') myTemplateContent = myTemplateFile.read() myTemplateFile.close() myDocument = QDomDocument() myDocument.setContent(myTemplateContent, False) newcomp = iface.createNewComposer() ...


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.


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

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


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


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


0

Maybe a little bit late but I had the same problem and I figured this out (assuming you want to close the first composer): activeComposer = iface.activeComposers() composer = activeComposer[0] composerWindow = composer.composerWindow() composerWindow.close()


0

Use QgsComposition.setPaperSize( width, height ). See https://qgis.org/api/classQgsComposition.html#a512d7c89fa0e76abb13b5395fae57069


0

Perhaps there is a solution to this on qtcentre.org: http://www.qtcentre.org/threads/32665-How-do-I-set-a-custom-page-paper-size-in-QPrinter (which can be easily ported to python) I think this is set up in the code line printer.setPaperSize(QSizeF(210,297), QPrinter.Millimeter)



Top 50 recent answers are included