New answers tagged

0

if you are using PyQgis 2.x registry = QgsMapLayerRegistry.instance() urlWithParams = "crs=EPSG:21037&IgnoreGetMapUrl=1&featureCount=10&format=image/png&styles=&layers=parcels&url=http://localhost:8060/geoserver/cadastralWsp/wms%3FCQL_FILTER=BBOX(geom, 579465,125671,664692,167717)" rlayer = QgsRasterLayer (urlWithParams , "...


0

There is an Ipython console(A kernel for Jupyter) for QGIS as a plugin, which you can add from QGIS official plugin repository or download from Github and copy to the plugin folder in QGIS. https://github.com/elpaso/qgis-ipythonconsole


2

I think you can do that just with the great internal tool from QGIS3 and without any knowledge of python. All within the graphical interface. You can access to the importing format (extension) by clicking in the '...' in the output element. Here you have the complete video with the process (I can't even upload here the complete gif...). Here are some ...


1

I use Mac and QGIS 3.4 and got the same error. After checking the PyQt5 folder in QGIS, I found there is no QtChart file in the folder, which is the reason why we cannot import it. And the version of PyQt5 in QGIS is 5.11.3 The folder for PyQt5 in QGIS is /Applications/QGIS3.app/Contents/Resources/python/PyQt5 I have an anaconda version of PyQt5, which ...


2

Try the code snippet below. After calling geometry(), we can string together calls to constGet() and vertices(), then traverse the vertex iterator (or use list comprehension to store the vertices in a list) and call x(), y() and z() on the vertex point objects to access the X, Y & Z values: layerT = QgsProject.instance().mapLayersByName('tPolygonLayer')[...


1

I would suggest using the Atlas feature of QGIS, which does exactly what you need. Automating the creation of maps is the job of the Atlas feature, a real ace of QGIS when it comes to production. It is very easy to master and ensures powerful results. From any layout, access the Atlas feature by clicking on the Altas menu item: There are also many ...


1

To update the extents of a layer after making any changes to its data source, use the QgsVectorLayer::updateExtents() method: layer.updateExtents()


1

You could use traceback: import sys import traceback try: print("Hello world!") os.mkdir("aaa") except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() formatted_exception = traceback.format_exception(exc_type, exc_value, exc_traceback) print("My Exception has been caught: {} ".format(e)) print(repr(...


2

Since you tagged pyqgis, here is a python solution which you can run from the python console. A couple of notes on the script. Since you say have around 80 polygon layers, the script below takes all polygon layers in the current project and stores them in a list, so when you run this script you should make sure your project does not contain any polygon ...


3

This works for me: if iface.mapCanvas().isCachingEnabled(): lyr.triggerRepaint() else: iface.mapCanvas().refresh()


1

I would try this approach: Merge all the layers into one (without fusing the polygons) Run the "Union" command to properly split overlapping polygons, while retaining all information. Create a second layer, let's call it "MaxP", with polygons split at each intersection, and only keeping the maximum value found among the original polygons at that position. ...


3

You could use Point Sampling Tool plugin. Note) If you run Point Sampling Tool plugin on a polygon layer which has overlaps, the tool take the attribute value only from the top feature found at the location. (1) Merge all polygon layers (which produces a polygon layer with a lot of overlapping polygons). (2) Run Order by expression tool (Processing ...


0

If you want to stick to python, you can parse the CSV using the built-in csv library or using pandas: https://realpython.com/python-csv/ Once you have parsed the CSV, you can construct the polygons using shapely: https://pypi.org/project/Shapely/ Finally, you can save the polygons using pyshp/shapefile: https://pypi.org/project/pyshp/


0

This still works with PyCharm >= 2019. You may just need to change the Python interpreter that you reference in your PyCharm project. I use the below .bat file to start PyCharm then set the project interpreter to point to OSGEO4W_ROOT\bin\python-qgis.bat, python3.exe in the same directory may also work. @echo off SET OSGEO4W_ROOT=C:\OSGeo4W64 call "%...


0

I found the answer but it's really costly to do that. When you want to use another Python interpreter you must not call o4w_env.bat since it calls many .bat files in advance which you don't want. You will only need relevant DLL and libraries from QGIS, and nothing more. Based on this, you need to add those relevant directories to your PATH in a batch file. ...


2

Try to use this .bat file to launch PyCharm: @ECHO off set OSGEO4W_ROOT=C:\OSGeo4W64 call "%OSGEO4W_ROOT%\bin\o4w_env.bat" call "%OSGEO4W_ROOT%\bin\qt5_env.bat" call "%OSGEO4W_ROOT%\bin\py3_env.bat" path %OSGEO4W_ROOT%\apps\qgis\bin;%PATH% set QGIS_PREFIX_PATH=%OSGEO4W_ROOT%\apps\qgis set GDAL_FILENAME_IS_UTF8=YES set VSI_CACHE=TRUE set VSI_CACHE_SIZE=...


3

If you zoom close enough you will see that the polygon on the left does not match with the border of the polygon on the right. To make them match add new verticis to the right side polygon at the connection points and snap them to correcponding vertices of the left side polygon. It is possible that polygons do share a common boundary but when the material ...


1

You could just iterate using a for loop instead: def feature_deleted(self, fid): for feature in self.layer.dataProvider().getFeatures(QgsFeatureRequest(fid)): print(feature.attributes())


2

The values are in the QGIS3.ini and under QGIS, in the properties > Advanced tab > core > Layout > searchPathsForTemplates. I modify the values with the following code : new_template_dir = "/home/me/my_custom_template_dir" app = QgsApplication.instance() params = QgsSettings( app.qgisSettingsDirPath() + "QGIS/QGIS3.ini", QSettings.IniFormat ) params....


1

Here's the right batch file. It works for me, i use windows10, PyCharm Community Edition 2019.2.2 and OSGEO-QGIS3.8. SET OSGEO4W_ROOT=C:\OSGeo4W64 SET QGISNAME=qgis SET QGIS=%OSGEO4W_ROOT%\apps\%QGISNAME% SET QGIS_PREFIX_PATH=%QGIS% SET PYCHARM="C:\Program Files\JetBrains\PyCharm Community Edition 2019.2.2\bin\pycharm64.exe" set PYTHONPATH=%OSGEO4W_ROOT%\...


1

To edit vector layers in PyQGIS you either use the layer methods or the layer.dataProvider() methods. The former allows you to use handy edit commands like undo/redo and roll back, whereas the latter directly commits changes to the data source (and does it even faster than the former). As seen in your code, you're using the latter, but your use case ...


2

I think the error is persisting because your c_sel argument is not a vector layer object either. I would not worry about using the Select By Location processing algorithm and just work directly with the point feature geometries and their relationships to the buffers. I created some test layers as a 'mock-up' and put together the script below which should ...


1

Working code: from PyQt4.QtCore import QVariant from qgis.core import (QgsFeature, QgsField, QgsFields, QgsGeometry, QgsPoint, QgsVectorFileWriter) from qgis.utils import QGis, iface #iface.legendInterface().layers() sluoksniu_saras=iface.legendInterface().layers() for cL in sluoksniu_saras: fn='D:\\Ko\\'+cL.name() geom_name = {0: 1, 1: 2, 2: 3} ...


0

This is due to the limitations of finite-precision floating point arithmetic (similar to the well-known issues with round-off when doing arithmetic calculation). It's usually not possible to represent the exact value of the intersection point of two line segments with double-precision endpoints, using double-precision numbers. Also, there is usually round-...


1

Found the issue. Specifically this code: # GetNextFeature handles interleaved reading correctly for ily in range (0,nly): layer = ds.GetLayerByIndex(ily) I initially replaced it with: # GetNextFeature handles interleaved reading correctly for ily in (0,1,2,4,3): layer = ds.GetLayerByIndex(ily) ...which appeared to work. It ensures Layer 4 ("...


2

After erasing some repeated lines in your code and changing 'run' processing method by 'runAndLoadResults' (also modifying 'DISTANCE' : 100 with 'DISTANCE' : leng/2), I tried your code out and it worked. for layer in QgsProject.instance().mapLayers().values(): features = layer.getFeatures() coluna = QgsField('Length', QVariant.Double) res = ...


0

You can do this using the matplotlib.backends.backend_qt4agg backend. The snippet below comes from a QGIS plugin but the key principles are a FigureCanvas which is used to create a widget added to a graphicsView from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from .lineStringGraph_dialog import lineStringGraphDialog #This is ...


0

If you mean the Identify tool, the source code is on GitHub.


2

The qgis:selectbylocation tool requires two input vector layers. The first input you used is buffer which is just a geometry feature. Try storing your buffer features in a new memory layer and use this as the first input layer.


1

It's mentioned in the API for QGIS 2.16 that you need to set the overrideGeometryType parameter: includeZ - set to true to include z dimension in output. This option is only valid if overrideGeometryType is set. Try including this parameter in your code. Edit: In response to your comment, you could try something like the following where I assumed you ...


4

ConvertGeometryFromWkt creates a geometry from a WKT file. Your title suggests you are trying to create a WKT file - ie. the reverse operation. The error makes sense in this context. WKT is a string (ie. text), and "polygons" isn't. If you are trying to convert a shapefile into a WKT file, then the ogr2ogr command line utility is probably a better way of ...


2

The geometry column must not be defined in the table definition. In the table definition you just define all other columns besides the 1 or n geometry columns. To define these you need the PostGIS AddGeometryColumn function, refer to https://postgis.net/docs/AddGeometryColumn.html In your case: CREATE TABLE cad.polygon( id_polygon serial NOT NULL, ...


1

Ok, I finally discovered that I was not running native Python (the one linked to QGIS), but with Anacondas's one... On Pycharm, you can change it quite easily. Go to File -> Settings -> Project -> Project Interpreter, and choose the relevant kernel. On Jupyter (Linux), you can choose the kernel in Kernel -> Change kernel. If the one you want is ...


2

Found my own solution: Geopackage provides an "fid" column as primary key in the attribute table when adding it to a QGIS project. On default, it reads this column instead of QGIS-internal feature IDs on commit. In order to force QGIS to create a new primary key instead of using the old one (which has been duplicated together with the feature), I simply ...


3

Good question. It is not obvious, but you need to copy your script algorithms to a specific folder to make your standalone script able to run them. You can easily see where your script algorithms should be located by adding a couple of lines to your standalone script: from processing.script import ScriptUtils print("Folder for script algorithms:", ...


0

Another possibility is via "Ocispatial": from qgis.PyQt.QtWidgets import * from PyQt5.QtCore import * from PyQt5.QtGui import * from qgis.PyQt.QtSql import QSqlDatabase, QSqlQuery from PyQt5.QtWidgets import QTableView, QApplication import sys #qgis.utils.iface.messageBar().pushMessage("Autosave", u"blba : "+str(QSqlDatabase.drivers())) # Check if the ...


0

# splitting the string list_of_fieldnames = ['PT', 'BC', 'cd', 'f1', 'f2', 'f3'] string1 = 'PT 100BC 20cd 19' string2 = 'f3 3f1 1PT 100cd 19' for string in [string1, string2]: for field in list_of_fieldnames: string = string.replace(field, ',' + field) list_of_fields_and_values = string.split(',') print(list_of_fields_and_values) ...


3

The TypeError is correct: argument 2 has unexpected type 'QgsVectorLayer'. It can be easily corroborated with help(QgsLayerTreeGroup.insertChildNode). So, I used following code for creating a memory layer: point = QgsPointXY(395065.34243502904, 4443021.813507973) epsg = 32612 uri = "Point?crs=epsg:" + str(epsg) + "&field=id:integer""&index=yes" ...


1

Unfortunately it seems like this issue can not be solved easily. So for me, it was easier to just switch to another tools and not use QGIS processing (which is a damn shame...) So I rewrote most processing via GeoPandas, Shapely, GDAL, numpy and it is working as expected. I can delete files just fine now. def select_by_location(select_from, overlay, output,...


0

Following code has an example of parameters dictionary and, I modified some little thing in your code because you are tagged this question with qgis-3 and 'runandload' doesn't exist as processing method in pyqgis3. I also modified 'layer_name' for working with my own layers. import qgis.core import processing def __init__(self, iface): self.iface = ...


0

I adapted Germán Carrillo's code to import xyz files (I use it to import river cross sections). As the fields in my cross profile tables are separated by multiple spaces, what results in adding several empty columns if I use " " as decimal separator, I added a piece of code to replace the spaces by a comma (consecutive spaces are replaced by one coma). For ...


1

Another example of importing module into PyQgis: Save in: '../ToolsFiles/File1.py def HelloWorld(): return "Welcome to PyQgis" Save in: '../ToolsFiles/File2.py' def HelloWorld2(): return "Welcome to PyQgis 2" Save in: '../Code.py' and execute next lines inside console Qgis. import sys tools = "..//ToolsFiles" #variable# sys.path.append(tools) ...


1

Managed it with this code, with explanation: fields = difflayer.fields() features_A = layer_A.selectedFeatures() features_B = layer_B.getFeatures() outgoingFeatureList = [] for f in features_A: compFeature = QgsGeometry() localFeature = QgsGeometry() outgoingFeature = QgsFeature() localFeature = f.geometry(...


0

I think you have done the script properly. That means, there are inputs and there is also an output (that's why you can chain your script in the modeler). I guess you are only missing one detail. In the last algorithm (Basic statistics for fields), you need to give the output a name when configuring it in the modeler. Once you do so, you'll see a green ...


2

To get the answer on your question I recommend you to use QGIS Python API: To iterate over all features in the layer use qgis.core.QgsVectorLayer.getFeatures To iterate over selected features use qgis.core.QgsVectorLayer.getSelectedFeatures Then get features geometry with qgis.core.QgsFeature.geometry And finally use qgis.core.QgsGeometry.difference


0

QGIS 3.4 does not allow for exporting models as scripts, this was reintroduced in 3.6 (see Exporting processing modeler as Python script in QGIS 3? ) So I am assuming you have used a higher version of QGIS (3.6+) to export your script, and are then trying to run the script in 3.4. Like this question: QGIS 3.8 model to Python script, not working in 3.4 And ...


1

You probably need to properly take care of escaping in strings. Basically \ is used as escape characters. You either need to replace it with / in your path which is unproblematic wrt escaping. Or use \\ or use r"C:\yourpath" to specify that it's a raw string.


2

You can try using this snippet layer = iface.activeLayer() request = QgsFeatureRequest(iface.mapCanvas().extent()) request.setFlags(QgsFeatureRequest.ExactIntersect) for f in layer.getFeatures(request): print (f.id()) This feature request will only use features that intersect canvas view. Found here


1

I actually found the solution myself: for feature in iface.activeLayer().getFeatures(iface.mapCanvas().extent()): print(feature.id())


1

Remove space in your output_gpkg.You can try typing another layer name and you will see how the first one loads as well. for example : output_gpkg = r'W:\srm\wml\Workarea\mamcgirr\Q_universal_overlap_tool\work\qscript_outputs\one_status_common_datasets_debug_version_dqu_shape_2.gpkg |layername = INVENT' to load the correct layer you must remove all spaces ...


Top 50 recent answers are included