Hot answers tagged

7

I found this other thread which was helpful How do I set layer transparency in QGIS 2.0 with Python? It seems like there should be a shorter and more efficient way, but I tested this and it works: print 'Start' active_layer = qgis.utils.iface.mapCanvas().currentLayer() raster_transparency = active_layer.renderer().rasterTransparency() ltr = ...


5

QGIS API provides you with a couple of ways for optimizing features requests. In your case, if you don't need geometry and the rest of attributes in the result, you can: Use flag NoGeometry (see docs). Set subset of attributes you really need using setSubsetOfAttributes() (see docs). That should speed your request up.


5

Here a solution without python needs. Add a new virtual layer with a query like : WITH r AS ( SELECT Basins800.rowid AS idGray, area(Basins800.geometry) AS areaGray, area(Intersection(Basins800.geometry, Severity.geometry)) AS aeraInter, Basins800.geometry AS geomGray FROM Basins800, Severity ) SELECT *, areaInterSum/areaGray AS ...


4

It sounds like a profiling tool might be of interest. However in the scenario you gave, it's possible that the GUI signal doesn't trigger python code. But this might help with python plugins (which includes processing and plugin manager, which are also written in python) Luckily python 2.7 comes with a profiler (actually, two - profile and cProfile) In ...


4

It looks like your issue might be caused by as simple syntax error. The correct syntax is if __name__ == '__main__': (with double underscores around main) That if statement is essentially used to check whether the file is being executed as a standalone script or if it has been imported by some other python script. Anything inside the if statement will only ...


3

Another suggestion which may also help - make sure you have a suitable index created on your field on the Postgres database, and then switch on the option under Settings -> Data Sources -> "Execute expressions on server-side if possible". That should make a huge difference, as all the filtering will be done on the server rather then sending ALL the features ...


3

I finally solved the problem! It was really a type-problem, as input values are defined as QVariant inside @qgsfunction. So, to get my code work I had to convert them into integers first. Apparently, QGIS takes care of type conversions itself... Function looks like this now: @qgsfunction(args="auto", group='Python') def bitwise_and(value1, value2, feature,...


3

You probably moved on ages ago, but for anyone else with this problem, I found a hack'ish way to disable the Save button in all open composer windows: for c in iface.activeComposers(): if c.isVisible(): w = c.composerWindow() # the QMainWindow of the print composer t = w.childAt(20,30) # its composer QToolBar t.setMovable(False) #...


3

I figured it out! It was something very small. Basically, the layers you would like to see displayed on the canvas is provided through canvas.setLayerSet(list_of_layers). # total list of layers actually displayed on map canvas canvas_layers = [] # load vector layers for files in os.listdir(source_dir): # load only the shapefiles if files.endswith("...


3

As mentioned in the comment, you could create a model from the Processing Toolbox but if you want to create a script, you could use the following which creates the start_lat field and updates it for each layer (comments are included which hopefully will help): # Import required module to create field from PyQt4.QtCore import QVariant # For each layer in ...


3

There are a couple of different approaches to that: Start a new project iface.newProject() Add a layer Whenever a new layer gets added to the mapcanvas, the welcome page will disappear Change the configuration In contrast to the other two approaches, this changes the configuration of the QGIS installation permanently. # 0: Welcome page # 1: Most ...


2

After seeing the link to Severity and Basins800 shapefiles, I could understand the necessary geoprocess. I modified the code in: Programmatically finding polygons which are >90% overlapped by another vector polygon layer using QGIS? for getting this one: mapcanvas = iface.mapCanvas() layers = mapcanvas.layers() #for Severity feats_lyr1 = [ feat for ...


2

If you're using backslashes, you need to use double backslash to escape the path. In my case: img.save("render.png","png") True img.save("C:\Users\ME\Folder\\render.jpg","JPG") True Or you could use single forward slashes: img.save("C:/Users/ME/Folder/render.jpg","JPG") True


2

Try using the following line instead: joinObject.setJoinFieldNamesSubset(['TYPE']) And as it is a list, you can specify which fields you only want to have joined: joinObject.setJoinFieldNamesSubset(['Field_1', 'Field_2', 'Field_3'])


2

I seem to have found the problem. In QGIS all layers were initially activated for the Snapping. First I disable any snapping operations. Subsequently, the Snapping is enabled for a few layers. for item in QgsMapLayerRegistry.instance().mapLayers().values(): QgsProject.instance().setSnapSettingsForLayer(item.id(), False, 2, 0, 2, True) fieldLayer = ...


2

The error you get says the field index is -1, so your new field wasn't found in your attribute table. That may be happening because: You need to use QVariant.Double instead of QVariant.Float. You've not committed the new field to the layer provider before asking for your new column index. You're asking for the index of myNewColumn but your provider ...


2

I have this function to remove a group and all his layers. I think is nearly what you want. def removeGroup(name): root = QgsProject.instance().layerTreeRoot() group = root.findGroup(name) if not group is None: for child in group.children(): dump = child.dump() id = dump.split("=")[-1].strip() ...


2

Default values are accessible via the data provider, so this may work for simple cases: provider = activeLayer.dataProvider() newFeature.setAttribute(0, provider.defaultValue(0))


2

Is Python a requirement? If I understand what you want, you can do this in the QGIS UI, in the raster layer properties:


2

It is best to not include spaces when defining your parameters: ##Networking=group ##lIn=vector #lOut=output vector from qgis.core import * v = processing.getObject(lIn) #[...the rest...] If you run the above code now (notice I commented out the output vector since nothing is being passed to it), it should run without errors.


2

Not sure if there is a plugin for this but you could run the following code in your Python Console which: Creates a new memory layer (you can define the type and crs). Iterates through each layer in the ToC and adds the attribute fields. Fetches all selected features in each layer and writes it to the memory layer. Saves the memory layer as a shapefile (...


2

I now found a solution to my problem, although it's not the most elegant one. I got access to the elements by calling the actions() method of the view menu: vm = iface.viewMenu() panels = [i for i in vm.actions() if i.title() == 'Panels'][0] toolbars = [i for i in vm.actions() if i.title() == 'Toolbars'][0] Unfortunately the plugin will be used in ...


2

Your issue is in the URL. I retrieved the "right" one from https://data.gov.uk/dataset/flood-map-for-planning-rivers-and-sea-flood-zone-2 INTERFACE%3DENVIRONMENT--86ec354f-d465-11e4-b09e-f0def148f590 seems to act as a token for authentication to WMS service. Try below code (tested on my machine) urlWithParams = 'contextuaWMSLegend=0&crs=EPSG:27700&...


2

after adding some print statements after each line I managed to work out that it's symbol.changeSymbolLayer(0, symbol_layer): bool QgsSymbolV2::changeSymbolLayer( int index, QgsSymbolLayerV2* layer ) { QgsSymbolLayerV2* oldLayer = mLayers.value( index ); if ( oldLayer == layer ) return false; if ( !layer || !layer->...


2

Not sure why you are getting that error, here is another option to add the column using psycopg2: import psycopg2 conn = psycopg2.connect("dbname = 'dbName' port = '5432' user = 'postgres' host = 'serverName' password = '********'") cur = conn.cursor() sqlQuery = "ALTER TABLE tableName ADD COLUMN newColumnName numeric;" cur.execute(sqlQuery) conn.commit() ...


1

Yes, it is possible by using a QgsFeatureRequest with 'setFilterRect' method. The argument of this method is a QgsRectangle object obtained for visible part of Map Canvas with its 'extent' method (QgsMapCanvas class). I tried out my approach with this code: layer = iface.activeLayer() mapcanvas = iface.mapCanvas() rect = mapcanvas.extent() request = ...


1

You need to import it in this way in the header of the corresponding Python file: from qgis.core import QgsRasterBandStats If you have other classes being imported from qgis.core, you can list them: from qgis.core import class1, class2, ..., QgsRasterBandStats


1

To Create the Vector Grid using the extents of the Vector Layer, we use: processing.runalg('qgis:vectorgrid', extent, step_x, step_y, type, output) from https://docs.qgis.org/2.8/en/docs/user_manual/processing_algs/qgis/vector_creation_tools.html#create-grid Here is the code on how to achieve the desired result, please note this will work on all vector ...


1

As I noted in my comment, try: uri.setConnection("host_name","5432","database_name", None, None, authConfigId = "4zoa91a") This plugin has an example using this method: https://github.com/bstroebl/DataDrivenInputMask/blob/master/ddmanager.py


1

Guess it was easier than I thought, I just had to create a list of QgsMapLayers from a group I want excluded in the QgsMapLayerComboBox: root = QgsProject.instance().layerTreeRoot() other_group = root.findGroup('Other group') layers = [] for group in other_group.children(): for layer in group.children(): layerList = QgsMapLayerRegistry.instance()...



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