# Tag Info

## New answers tagged pyqgis

3

I think the reason it fails is because processing version 2.12.2 requires QGIS 2.12.0 atleast (and you mentioned you use QGIS 2.10 which works fine with processing 2.10.3. See the plugin repository for more details but the following is a screenshot of the repository): Not sure about detecting the processing version after using import processing but you ...

7

Do you have to publish it? Legally, The GPL License of PyQGIS forces you to share the code only with your "client", therefore your company. So No, you don't have to publish it. You can keep them internally, create your own repository, and share with who you want. But note that whoever receives the code is allowed to pass it on by the terms of the GPL. ...

0

Maybe try to use getOpenFileName without these parameters. I've done this before with: dialog = QtGui.QFileDialog() fname = dialog.getOpenFileName(None, "Import JSON", "", "JSON files (*.json)") and I've never had any problems like yours.

0

This post might help in your case. At least I had problems with PostGIS primary key missing and causing QGIS not to be able to edit the data stored in PostGIS. Unable to edit PostGIS DB using QGIS 2.10, works on 2.8

0

You are incorrectly setting the data source. Also sql string is not needed. The below code should work for you. Good luck :)

3

This document "Skeletonizing Polygons Using PostGIS" describes a process which utilises tools from PostGIS and GRASS, both of which might be callable. It mentions using PostGIS to create a skeleton of the vectors and cleaning it up using either PostGIS again or GRASS. There are existing tools from the Processing Toolbox which hopefully simplifies things ...

3

One, somewhat round-about option might be to use SAGA's grid skeletonization module (http://www.saga-gis.org/saga_module_doc/2.1.3/imagery_segmentation_1.html), either through QGIS or using the command line saga_cmd utility. You'd have to convert your polygon to a SAGA raster first. Otherwise, as stated by @Alpha-beta-soup, you could use v.skeleton from ...

1

It was obvious and I didn't read well the RTFM. See this discussion on the Spatialite mailing list. The answer is: SELECT ST_GeomFromText('POINT(1 2)', 4326); or SELECT MakePoint(1, 2, 4326); To make result as a text, do: SELECT hex(MakePoint(1, 2, 4326));

3

You can create instance vairiables with self keyword: def openSr(self): self.projSelector = QgsGenericProjectionSelector() self.projSelector.exec_() self.srText.setText(self.projSelector.selectedAuthId()) Now your self.projSelector variable is ready to use in other methods. dialog = CreateModelDialog(iface) ... dialog.projSelector ...

2

Not the neatest way of doing things, but you can achieve what you want by running this code into the QGIS Python console: delimited_dlg = QgsProviderRegistry.instance().selectWidget("delimitedtext", iface.mainWindow()) delimited_dlg.children()[1].children()[2].setText("/path/to/your/csv_file.csv") delimited_dlg.show() delimited_dlg is the dialog, which ...

0

There are basically two problems with the script you posted. The feature's attributes are not initialized. So the feature itself does not have any attributes (although the provider has). With other providers this would be less of a problem since when saved and retrieved, new features get created, but the memory provider saves the feature as they are. The ...

0

Well I think I found what my problem was: The tool does not like input = qgis.utils.iface.activeLayer(). In other words, the user must either specify the actual name of the layer loaded in the Table of Contents (especially if running in the Python Console of QGIS) or specify the path of the shapefile. import processing input = ...

2

Aloha! there is another way: LR = qgis.core.QgsRasterLayer("C:/Myfolder/test.tif", "test") LR.width() #some properties 550 LR.height() #some properties 556 LR.extent().toString() u'0.0000000000000000,-1001.0000000000000000 : 1001.0000000000000000,0.0000000000000000' V = LR.dataProvider().identify(QgsPoint(100,-100), QgsRaster.IdentifyFormatValue) ...

1

The problem was in the paths. I changed it to QgsApplication.setPrefixPath(os.getenv("QGISPATH")+"\\apps\\qgis", True) and now it worked fine.

0

Qt models are usually very generic and do not know anything about the data presented within. Therefore they allow the developer to specify all aspects of the data. The QgsAttributeTable model in contrast knows about the data presented within and reacts dynamically to reflect its properties by automatically returning appropriate headers. I assume that you ...

1

I think it's your path delimiters. On Windows, use either double-backslashes \\, or single backslashes in a raw string, like r"c:\foo\bar". I often use scripts on both Linux and Windows machines, and typically handle the different paths by checking the platform and conditionally using certain path styles, something like this: import platform, subprocess # ...

1

The problem is that Windows uses backslashes for paths, while unix-based systems use forward slashes. This simply means that Python cannot find the path to the shapefile since it points to a nonexisting location. For instance this line: print os.path.exists("../external/precincts/USA_precincts.shp") will need to be replaced with print ...

1

What you want to do is to copy the original layer to a memory layer with some conditions. If the original layer has fields and attributes, your script will not work because. you don't define any field in the memory layer (see pyQGIS manually copy all features with attributes from a layer into a memory layer ) If you work in the Python console, you don't ...

1

I've had no problems adding features to memlayer.dataProvider() as shown in http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/vector.html#memory-provider: # create layer vl = QgsVectorLayer("Point", "temporary_points", "memory") pr = vl.dataProvider() # add fields pr.addAttributes([QgsField("name", QVariant.String), ...

0

If I understood correctly, what you are looking for is the list comprehension functionality for Python. instead of creating a list using hardcoded indexes you can rewrite it in a more generic form : [ i for i in mylist ] So I think you can rewrite mytable.add_column("Column1", [my_list_a[0], my_list_a[1], my_list_a[2]) as ...

0

we are facing the same issue here. It seems related to a bug in PyQt4. See preloadForm method comment here for a workaround : http://qgis.org/api/classQgisInterface.html and here the issue raised to QT / Pyqt 4 by NathanW: http://forum.qt.io/topic/26562/crash-calling-c-method-using-quiloader-from-pyqt4

1

I don't really know how you got the CSV color ramp so I can't perfectly answer but you should adopt the following couple of functions layer.saveNamedStyle("your_raster_style.qml") and imagining a layer1 raster file layer1.loadNamedStyle("your_raster_style.qml") Not need to manually copy the style IMO.

1

It looks like your function does not work since you put your attributes into the string in the filter expression, which is why Python does not allocate the value you assign to it. Replace this line it = layer.getFeatures( QgsFeatureRequest().setFilterExpression ( u'"fieldname" = attribute' ) ) with it = layer.getFeatures( ...

1

The number of parameters are different in the function definition and the function call, so your filter expression will filter nothing, because it will substiture indexmf into attribute in your function and index will be undefined. I suppose your code would be clearer if your function would return the result list. For example def my_function(layer, ...

3

The shortest way to get the path to your plugin directory: import os plugin_path = os.path.dirname(__file__) So the path of your .qml file could be: qml_path = plugin_path + "/myFile.qml" Finally, you can load the .qml file to your QgsVectorLayer: myLayer.loadNamedStyle(qml_path)

3

import os path = os.path.dirname(os.path.abspath(__file__)) Now path variable stores your path to the plugin directory which contains plugin.py: >>> path >>> "/home/[user]/.qgis2/python/plugins/[plugindirectory]"

2

in the graphical modeller you have the opportunity to refactor fields wihtin a vector layer. There you can reorder fields like in the table Manager plugin. In a second step you could use this model with processing.runalg("modeler:youmodelname", inputlayer, outputlayer)in the console to iterate trough all desired files.

2

I had also some troubles with this, here is my solution for OSX 10.9.5: import os, sys sys.path.append('/Applications/QGis.app/Contents/Resources/python') from qgis.core import * app = QgsApplication([],True) QgsApplication.setPrefixPath(r"/Applications/QGIS.app/Contents/MacOS", True) QgsApplication.initQgis() layer = QgsVectorLayer('/tmp/myshape.shp', ...

2

There is a way. You need to check whether your menu is already present in the QGIS Menu Bar. If so, you can reuse it, otherwise, you create it. In the initGui method of each of your plugins, add the following code (see comments for details): self.menu = None # Check if the menu exists and get it for child in self.iface.mainWindow().menuBar().children(): ...

2

I guess a Memory Provider would suite your needs as It does not store data on disk, allowing developers to use it as a fast backend for some temporary layers. Based on your descriptions and the linked example from the cookbook I created some code. It is not fully tested and maybe you will have to tweak it a little: lyrs = ...

1

Your idea was actually fine. Raster layers' extent can be accessed via the extent() method. However, you would need to combine your rasters' extents before zooming in. Assuming your raster layers and the map are in the same reference system (i.e., no on-the-fly projection), you can zoom in to the extent of a desired group copying this code snippet to your ...

1

I think that this is not a numerical rounding issue, but it could be a problem with your point vector layer. I tried out Detlev script; as you can see at the next image (where point into green circle is only 8 mm from the line). Details can be observed at the next image where I used the Zoom In tool. Segment was effectively produced with only 8 mm of ...

1

QgsPoint objects store coordinates as double precision values. Following several documents on Python and data types this allows for a precision of 17 significant digits (eg http://floating-point-gui.de/formats/fp/). I tested the (my) script with a series of points with decreasing distances from a line. If you print out the distance, and the nearest point ...

0

You need to create an app object prior to referencing QgsApplication: from qgis.core import QgsApplication from PyQt4.QtGui import QApplication app = QApplication([])

3

No native way by my knowledge. Last time I used the fine code with a ConfigParser from Dockable MirrorMap plugin by Faunalia for an aboutbox. import ConfigParser import os import platform try: import resources except ImportError: import resources_rc class DlgAbout(QDialog, Ui_DlgAbout): def __init__(self, parent=None): ...

1

Not sure of what could be happening there, but the next code snippet has worked for me on my GNU/Linux machine: # Prepare the environment import sys from qgis.core import * from PyQt4.QtGui import * app = QApplication([]) QgsApplication.setPrefixPath("/usr", True) QgsApplication.initQgis() # Prepare processing framework ...

3

You just need to define the QgsFields object in this way: from PyQt4.QtCore import QVariant fields = QgsFields() fields.append(QgsField("mystring", QVariant.String)) fields.append(QgsField("myreal", QVariant.Double)) Then you can use it to create your feature: feat = QgsFeature(fields, fid) # fid should be an integer

1

In the case that I wanted to print a string rather than a numeric value as the return, i.e. 'case when "codigo" = 1 then "hello" end'... how would I code that? Apologies for listing this as an answer - I don't have enough reputation to post a comment. I'd appreciate it if someone could place this request in the correct place.

8

From the QGIS Documents: Geometry Handling, you can use the following code to get the length of any selected line(s): layer = qgis.utils.iface.activeLayer() features = layer.selectedFeatures() for f in features: geom = f.geometry() print "Length:", geom.length() Hope this helps!

4

You need to provide some imports and paths that are automatic when you use Python from within QGIS, but not outside. In addition to the libraries you import, start with: from qgis.core import * # supply path to where is your qgis installed QgsApplication.setPrefixPath("/path/to/qgis/installation", True) # load providers QgsApplication.initQgis() see: ...

6

This is an example of how to open the Processing "Join attributes" algorithm by pressing Ctrl+1 (you can copy and paste it into the QGIS Python console): # Function to open the "Join attributes" algorithm's UI # See http://gis.stackexchange.com/questions/156633/how-to-launch-processing-tool-user-interface-using-pyqgis from processing.core.Processing import ...

8

You don't need a special function (as "Ray Casting"), everything is in PyQGIS (contains() in PyQGIS Geometry Handling) polygons = [feature for feature in polygons.getFeatures()] points = [feature for feature in points.getFeatures()] for pt in points: point = pt.geometry() # only and not pt.geometry().asPolygon() for pol in polygons: poly ...

1

With some advice from a workmate I finally got it to work using within(). General logic get features of polygon(s) get features of points loop through each feature from polygon file, and for each: get geometry loop through all points get geometry of single point test if geometry is within geometry of polygon Here is the code: mitte_path = ...

5

You can use the "Ray Casting" algorithm that I have slightly adapted for using with PyQGIS: def point_in_poly(point,poly): x = point.x() y = point.y() n = len(poly) inside = False p1x,p1y = poly[0] for i in range(n+1): p2x,p2y = poly[i % n] if y > min(p1y,p2y): if y <= max(p1y,p2y): ...

4

I used this code: mapcanvas = iface.mapCanvas() layers = mapcanvas.layers() processing.runalg('qgis:selectbylocation', layers[0], layers[1], u'within', 0) with this situation: and it worked:

2

Following environment variable solved the problem: export LC_NUMERIC="en_US.UTF-8" Btw this also solved a problem with spatial queries against SpatiaLite databases, where in sqlite3_prepare statements a mixture of decimal point and comma occur.

1

Try this code: layer = iface.activeLayer() provider = layer.dataProvider() areas = [ feat.geometry().area() for feat in layer.getFeatures() ] field = QgsField("area", QVariant.Double) provider.addAttributes([field]) layer.updateFields() idx = layer.fieldNameIndex('area') for area in areas: new_values = {idx : float(area)} ...

1

Looking at the code that complains, it appears it is not getting an object (type) it expected. Make sure your layer loading works first —for starters I'd try absolute paths if you're not sure the working dir is where you expect it to be.

0

Before to set geometry of 'transformedLine' try out to print it. This object should have a form similar (if it is projected in meters) to this (for one feature): [(366179,4.46968e+06), (357711,4.44966e+06), (363870,4.43041e+06), (382100,4.41947e+06), (396590,4.41078e+06)] A list of QgsPoint. The another strange thing is in: pr.addFeatures([line]) You ...

7

A quick solution for transforming a space separated file containing "lon lat" in WGS84 to UTM33N but you don't get any other data: #!/bin/bash # for i in $( ls *.csv ); do gdaltransform -s_srs EPSG:4326 -t_srs EPSG:32633 <${i} > utm\${i} done That works and it preserves the order of the data so maybe another loop using e.g. awk to combine the ...

Top 50 recent answers are included