New answers tagged

0

This is a quick response but this code work perfectly,and you can refresh featurecount on QgsLayerTreeView. l = iface.activeLayer() l.setSubsetString('gemarkungsnummer in ('2760','2765','2771','2780','2786','2800','2811','2817','2836')') qgisTView = qgis.utils.iface.layerTreeView() actions=qgisTView.defaultActions () actions.showFeatureCount () actions....


2

I think you need to add from qgis.utils import qgsfunction into your code. You can also remove the other imports as they're not necessary. So something like this should work: from qgis.utils import qgsfunction @qgsfunction(args="auto", group='Custom') def sp_split(value1, feature, parent): return value1.split(",")[2]


0

It would seem that the Statist plugin does not recognise the qlonglong type fields but does recognise integer fields. So you could create a new field using the Field Calculator and copy over the values using the name of the qlonglong field as the expression.


0

I once had issues using the currentIndex() method (which might be unrelated to the issue you have). Instead, I use the currentText() method to identify the layer and add attribute fields: from PyQt4.QtCore import QVariant selectedLayerIndex = self.dlg.comboBox.currentText() selectedLayer = QgsMapLayerRegistry.instance().mapLayersByName(selectedLayerIndex)[...


6

The slashes are going the wrong way in the url directory path to the shp. Python interprets "\" as line return. Use "/" instead or "r" in front of the string path. "C:/Data/scripts/...etc" Or r"C:\Data\scripts...etc"


1

For R users, I wrote a quick R function that batch renames the .shp file and all files associated. It's pretty bare bones, and there is no error checking, etc., so if it fails you'll need to do a little investigation. # Function to rename shapefile (.shp) and all associated files # fpath = full file path of any of the associated files (character) # newName =...


0

Have you tried processing.runandload() ? I'm using that when I run a grass:v.voronoi function and that works fine.


1

You should understand that when you save the file from the QgsRenderer as in your code: piperenderer = pipelayer.renderer() pipe.set(piperenderer.clone()) file_writer.writeRaster(pipe... You are not saving the raster styled, instead you are saving the actual RGB file that represents that visualization, so it is not classified or styled, but it is like you'...


0

Spatial indexes will use features bounding box to simplify and speed up things. If you need the correct answer you will need to: Get distance from the nearestFeature returned by the index; Filter up all features inside the bounding box of the feature of interest expanded by the distance calculated previously. Calculate distances from the feature of ...


1

In case there are those who may run into the same issue, here is my solution (that works beautifully!) from qgis.core import * from qgis.gui import * from PyQt4.QtCore import * source_dir = '/home/cassandra/desktop/file_formats/ENC_ROOT/US6SP10M/shapefiles/SOUNDG.shp' name = 'SOUNDG' output_dir = '/home/cassandra/desktop/file_formats/ENC_ROOT/US6SP10M/...


0

I'm three years late, but hopefully whoever else might be stuck on an issue like this will benefit from my answer. # adds a LineLayerStyle (Arrow, dotted) # layer being a vector layer object of QgsVectorLayer() def setLineLayerStyle(self, layer, style): if(style == "arrow"): sl = QgsSymbolLayerV2Registry.instance()....


1

You're creating a new canvas, not referencing the main window canvas. Use canvas = iface.mapCanvas() instead of canvas = QgsMapCanvas()


0

If you don't find another solution for this, consider creating a VIEW in PostgreSQL and then add that as a layer. This has the added benefit that you can change the query in the database without touching your Python code. (So, for example, if you have several users using QGIS with this code installed, you can update all of them immediately by updating the ...


0

I think you cannot make an intersection of 2 or more tables inside a WHERE clause in uri.setDataSource(). You are supposed to query only the table that you are adding.


1

Bit of a convoluted process but this should work (make dbf layer vector layer, convert dbf to csv, then convert csv to delim layer, and finally convert delim layer to shp): DBFlyr = QgsVectorLayer(myDBFPath, 'anyName', "ogr") myCSVPath = 'C:/Temp/myCSV.csv' QgsVectorFileWriter.writeAsVectorFormat(DBFlyr, myCSVPath, "utf-8", None, "CSV") uri='file:///'+ ...


0

I haven't seem graduated symbol documentation quite like that before. This code might be a bit more comprehensible and will probably solve your problem because I too use PyCharm IDE and I have used these graduated symbols many times. # create graduated marker symbol based on ('label', 'lower_range', 'upper_range', 'color') colorRamp = (('label1', ...


2

Categorized symbols and graduated symbols are applied in pretty much the same way. The only difference is that graduated symbols are taking into account certain ranges, whereas, categorized is simply taking in the actual field value. Quite honestly, you could literally replicate the code given from the PyQGis cookbook site: http://docs.qgis.org/testing/...


1

In answer to my own question...The QMessageBox was called upon execution of the plugin so it only makes sense the main dialog closed after calling the QMessageBox. The quick answer was to create a separate push button allowing the user to validate the entries at any point. Ultimately what I'd like is to have some sort of object listening in the background ...


1

In a plugin of mine I have a similair problem and I use the ogr library to delete shape files. You could try something like this: from osgeo import ogr driver = ogr.GetDriverByName('ESRI Shapefile') driver.DeleteDataSource('path_to_your_shape.shp') More informations about python and ogr you can find here: osgeo.ogr


0

I had to deal with this same problem today. QGis was removed from the system because libgdal1h was marking conflicting dependencies. I found out these conflicts were coming from the QGis PPA itself. I removed it from my sources.list and then created a reference to the UbuntuGis-Unstable PPA. After that was just a matter of running: sudo apt update &&...


2

The proper way to dealing with this is to use an alias. You can use addAttributeAlias for this (as usual, check the documentation for this) This way it will not only be used in python-preprocessed forms but also in the attribute table and other places.


5

I think that your issue is only a "Zoom In" problem. I'm going to render to tif these random points with Raster-> Conversion -> Rasterize (Vector to Raster) Tool (cell resolution 30 x 30) of QGIS; equivalent to your standalone Python script. Loaded raster layer looks as if no point had been rasterized. However, with point layer as first layer, 'Zoom In'...


1

It looks like you forgot to match your call to app.initQgis() with a call to app.exitQgis(). Add that after the call to app.exec_() and the segfault disappears.


1

The following PyQGIS line should do the trick: self.contourLayer.setCustomProperty("labeling/labelPerPart", "true") As soon as you run such line, you should get the 'Label every part of multi-features' checkbox toggled in the properties dialog. I'm using QGIS 2.14.2.


1

There are two modules in QGIS Python included: Scipy csgraph: http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.csgraph.dijkstra.html NetworkX: http://networkx.readthedocs.io/en/stable/reference/algorithms.shortest_paths.html Both modules are efficient and written in C.


1

I have my qml styles in a fix path (c:/pyqgis_data/Styles/). So, to load arrows_red_orange.qml (exclusively for point layers), next lines at the Python Console of QGIS work: >>>layer = iface.activeLayer() >>>if layer.geometryType() == QGis.Point: >>>...layer.loadNamedStyle('c:/pyqgis_data/Styles/arrows_red_orange.qml') >>&...


1

Replace your method with this. You only need change self.iface.mainWindow() for self. def select_input_file(self): filename = QFileDialog.getOpenFileName(self, "Choose input file ", os.getcwd(), "*.qml") if fileName=="": return self.d.lineEdit.setText(filename) return The dialog closed when you click ok button.


2

Do this in that way: def select_input_file(self): self.d.lineEdit.setText(QFileDialog.getOpenFileName(None, "Choose input file ", os.getcwd(), "*.qml")) Without this iface as a parameter.


1

You have to do this: fontStyle['value'] = '\x65' You can read more about the unicode here: https://docs.python.org/2/howto/unicode.html


0

As this was marked as a software bug, there's not much to do until it's fixed. But an alternative solution to the particular problem I was facing is very simple and maybe even easier than the proposed original plan. I was trying to create a raster that reflected the frequency of intersections it had with my point vector layer (this was to show where ...


0

This error is a Qgis bug,on a macbook platform,actually. https://hub.qgis.org/issues/14682


1

After a night without sleep, I fixed it myself: selectedLayerIndex = self.dlg.cbox_layer.currentIndex() selectedLayer = layers[selectedLayerIndex] # get unique values fni = selectedLayer.fieldNameIndex('firebrary') unique_values = selectedLayer.dataProvider().uniqueValues(fni) # define categories ...


2

In this case, it is preferable to use itertools module to avoid repeated indexes. I assumed one feature for each shapefile in next situation: Next code prints all the names of the shapefiles that overlap with each other. import itertools mapcanvas = iface.mapCanvas() layers = mapcanvas.layers() feats = [] for layer in layers: for feat in layer....


0

One workaround I've found is to open up the .qgs project file in a text editor (they're in a sort of plain-text xml type format) after the fact and batch change all the font declarations with regex - I think they should ALL be in the .qgs file, unless perhaps there are some plug-ins that store them elsewhere. Sorry I don't remember exactly what they look ...


1

This example work perfectly. from PyQt4.QtCore import * lyr = iface.activeLayer() lyr.startEditing() provider = lyr.dataProvider() provider.addAttributes([QgsField("newAttribute", QVariant.Double)]) lyr.updateFields() lyr.commitChanges()


0

Thank's a lot @xunilk ! I change the coordinates of the points I want in my layer with a QgsCoordinateTransform instance and now it works ! Here is the way I did (you cans translate the comments if you don't understand what i'm doing...): # On commence par creer une liste des points qgis delimitant la zone de chantier points = [] # On ajoute maintenant ...


1

You can simply write something like: if self.dlg.myCheckBox.isChecked(): doSomething() else: doSomethingElse() Note that if you want something more dynamic (ie perform an action everytime the checkbox is checked/unchecked), you will have to use PyQt signals.


0

I was thinking about difficoult soulution and I just overwrote it all. It was so simple. I must just import dialog for second window, add a method to open new dialog and add a line in init to react when button pushed.


0

I've only used the Graduated Symbol renderer; however, the categorized symbol marker seems to be quite similar. I was also seeking what you were and here was my solution: # replace QgsSymbolV2.defaultSymbol(layer.geometryType()) # with sym = QgsMarkerSymbolV2.createSimple({'name' : 'triangle', 'color' : 'red'}) 'triangle' in place of whatever marker you ...


1

Start with: symbol = QgsSymbolV2.defaultSymbol(layer.geometryType()) renderer = QgsSingleSymbolRendererV2(symbol) Now you have 10 types of fill: Simple fill, QgsSimpleFillSymbolLayerV2 Gradient fill, QgsGradientFillSymbolLayerV2 Centroid fill, QgsCentroidFillSymbolLayerV2 Line pattern fill, QgsLinePatternFillSymbolLayer Point pattern fill, ...


0

So, it was a ssl certificate validation problem. The python used by QGIS didn't recognize the organism that had signed my API's ssl certificate. There were a possible work around here (telling urllib2 to ignore certificate validation) but it calls urllib2.HTTPSHandler() which has been implemented in a python version posterior to the one QGIS uses. The ...


0

You need to use QgsCoordinateReferenceSystem and QgsCoordinateTransform classes. I tried out next code to transform polygon vector layer of next image from EPSG: 32612 to EPSG: 4326. layer = iface.activeLayer() crsSrc = QgsCoordinateReferenceSystem(32612) crsDest = QgsCoordinateReferenceSystem(4326) xform = QgsCoordinateTransform(crsSrc, crsDest) ...


1

You can create a new dialog as a class, even in your main .py file. class NewDialog(QtGui.QWidget): def __init__(self, parent): super(NewDialog, self).__init__(parent) Than in your main class you can put function like that: ... def open_new_dialog(self): self.nd = NewDialog(self) self.nd.show() ... This function creates a new dialog and ...


0

I think your error is found in the for-loop syntax. Try the following: ValList = [] for j in lstFields: ValList.append(layer.GetFeature(1).GetField(j)) Note that in your case, if you have already chosen a feature, change the last line to: ValList.append(Feature.GetField(j)) The results in my case are given below. > lstFields = ['data1', 'data3'] # ...


2

This works for me: from PyQt4.QtGui import QGroupBox, QCheckBox, QDialog, QHBoxLayout d = QDialog() gb = QGroupBox("Groupbox") gb.setEnabled(False) cb = QCheckBox("Set active") l = QHBoxLayout(d) l.addWidget(gb) l.addWidget(cb) cb.stateChanged.connect(toggleGroupBox) def toggleGroupBox(state): if state > 0: gb.setEnabled(True) else: ...


1

Here it is. Changes to your code are provided below, followed by an explanation. layer = qgis.utils.iface.activeLayer() expression = "/"MTFCC/" = /"H3010 /" " # note that I've modified this line processing.runalg("qgis:selectbyexpression", layer, expression, 0) Using processing.alghelp("qgis:selectbyexpression") I have seen that the function uses QString ...


0

I'm not 100% sure, but I think you may have to set the coordinate system of the canvas as well. There is a post here that indicates this: http://gis.stackexchange.com/a/151867 For example, the answer there shows code like the following: mycrs = QgsCoordinateReferenceSystem(32611) iface.mapCanvas().mapRenderer().setDestinationCrs(mycrs) I would suggest ...


1

Basically, you have to use signals to detect the "change layer" event and update your field combobox accordingly. Here is a simplified example (assuming you already have the run and initGui methods defined): In run(self): layers = QgsMapLayerRegistry.instance().mapLayers().values() # Create list with all layers # layers = self.iface.legendInterface()....


0

The PYTHONPATH must be added to the environment variables. This Path is the folder in which the file pydevd.py is. In my case, this is the following path: C:\eclipse\eclipse\plugins\org.python.pydev_4.4.0.201510052309\pysrc. After restarting, the module pydevd can be imported.


1

The destructor you linked to above is for cleaning up the registry once when QGIS ends and it's nothing python code should care about (or can even access). What you are looking for is an unregisterWidget function, which is not available at the moment. You can open a feature request for that. For now, just try not re-registering the factory.



Top 50 recent answers are included