Hot answers tagged pyqgis
11
If you want to access your results in other Python scripts, try the pickle module.
simple example:
>>> a = [1, 2, 3, 4, 5]
>>> import pickle
>>> f1 = open('results.pickle', 'wb')
>>> pickle.dump(a, f1)
>>> f1.close()
Now the data is saved ('pickled') in the results.pickle file.
To load the pickled data:
...
11
StatusBar
You can use iface.mainWindow().statusBar() which returns a QStatusBar
iface.mainWindow().statusBar().showMessage( u"Hello World" )
In the python console for QGIS < 1.9 it would be:
qgis.utils.iface.mainWindow().statusBar().showMessage( u"Hello World" )
MessageBar
Starting from QGIS 2.0 there is also QgsMessageBar which is able to ...
9
You can use the addToolBar() API call via QgisInterface (i.e. iface) to create a custom toolbar:
class MyPlugin:
def __init__(self, iface):
# Save reference to the QGIS interface
self.iface = iface
def initGui(self):
# Add toolbar
self.toolbar = self.iface.addToolBar("My_ToolBar")
# Create actions
...
9
It is a problem of analytical geometry and the solution was given by Paul Bourke in 1998 (Minimum Distance betweena Point and a Line). The shortest distance from a point to a line or line segment is the perpendicular from this point to the line segment. Several versions of his algorithm have been proposed in various languages including Python as in ...
8
It sure is:
iface.messageBar().pushMessage("Header","MessageBody", QgsMessageBar.WARNING, 2)
the last arg is a timeout in seconds, if it's not supplied then it will stay until the user closes it.
You can even add you own control to the messagebar:
widget = iface.messageBar().createMessage("Test","Testing")
combo = QComboBox()
...
7
I do not know whether work for you or not , but you can check out gdallocationinfo. it is a raster query tool from gdal...
The gdallocationinfo utility provide a mechanism to query information
about a pixel given it's location in one of a variety of coordinate
systems. Several reporting options are provided.
$ gdallocationinfo utm.tif 256 256
...
6
If you know the python module for the plugin you can just run a import in the python console For example:
from fTools import somemodule
Then you can do somemodule.methodcall(). You will have to make sure, by looking at the code of the plugin, that it doesn't rely on any of it gui stuff. Otherwise you might get a nice UI pop up when you don't want it.
...
6
Calling layer.selectedFeatures() will return a list with your selected feature(s). You can then call feature.attributeMap() on each of the selected features to get a dictionary of each feature's attributes.
layer = qgis.utils.iface.activeLayer()
selected_features = layer.selectedFeatures()
for i in selected_features:
attrs = i.attributeMap()
for ...
6
how about...
provider = vector.dataProvider()
feat = QgsFeature()
allAttrs = provider.attributeIndexes()
provider.select(allAttrs)
while provider.nextFeature(feat):
geom = feat.geometry()
rect = geom.boundingBox() #get bounding box as QgsRectangle
5
There doesn't seem to be a way to directly find a feature object's parent layer or whether it's selected from a method in the QgsFeature class.
A similar approach to vlayer.selectedFeatures() is to test whether the feat.id() is in vlayer.selectedFeaturesIds(). QgsFeatureIds are not unique values compared with other vector layers, only within their own ...
5
This should get you started
from qgis.core import QgsVectorLayer, QgsFeature
layer = QgsVectorLayer(r"D:\fold\boundingBoxes.shp", "boundingBoxes", "ogr")
road_type_index = layer.fieldNameIndex("road_type")
buffer_distance_index = layer.fieldNameIndex("buffer_distance")
layer.select(layer.pendingAllAttributesList())
layer.startEditing()
for feature in ...
5
Renaud, if you are looking to just make contours and not specifically via the console, look to Nathan W's blog post on the core GdalTools plugin currently available in QGIS:
Generating contours using GDAL ( via shell or QGIS)
If you are looking to generate contours via a Python script or PyQGIS plugin, look to these resources:
GdalTools Plugin
(QGIS ...
5
In the Python console run the following:
import sys
sys.path
See if your PYTHONPATH entry is listed. I'm guessing not, since that environment variable is probably not available to QGIS's running Python.
To add your scripts folder to console's sys.path do a regular append():
sys.path.append('~/Scripts/python')
Then you should be able to import your ...
5
If you need to get the fields of a layer you can use QgsVectorLayer::pendingFields() in Python like so:
fields = layer.pendingFields()
which will give you something like this:
{0: <qgis.core.QgsField object at 0x46d9d40>,
1: <qgis.core.QgsField object at 0x46d9b00>,
2: <qgis.core.QgsField object at 0x46d9cb0>,
3: ...
5
There is a class you can inherit from called QgsMapTool which you can override the mouse events to handle user actions.
Like so: https://github.com/NathanW2/qmap/blob/master/src/plugin/point_tool.py
You can find objects under the mouse click for example using code like this:
searchRadius = (QgsTolerance.toleranceInMapUnits( 5, layer,
...
5
What kind of tasks are you referring to?
I use the following static class to benchmark my code.
I designed it to be static so that I can call the start/stop/show methods wherever is needed without worrying about passing references to the Timer back and forth.
The optional parameters allow me to have several running at once, any values will do but names ...
5
What you are looking for is the extentsChanged() signal. This is emitted every time, the map canvas is moved or zoomed.
The following code works from the python console:
from PyQt4.QtGui import QMessageBox
def info():
QMessageBox.information( iface.mapCanvas(), "Extents changed", "Pan or zoom occurred" )
iface.mapCanvas().extentsChanged.connect(info)
...
5
You should be able to do this (in a slightly modified form) with just command line options.
From http://docs.qgis.org/2.0/html/en/docs/user_manual/introduction/getting_started.html
Command line option --project
Starting QGIS with an existing project file is also possible. Just add
the command line option --project followed by your project name ...
4
You could craft your script to work with Gary Sherman's Script Runner plugin and run it from within QGIS. Re-running the script, after editing, should prompt Script Runner to reload the module and reflect your changes. See also: Script Runner's plugins.qgis.org listing.
The essentials are to make sure you have a run_script function, which gets called by ...
4
Have a look at the Memory provider as described in PyQGIS Cookbook.
Memory provider is intended to be used mainly by plugin or 3rd party app developers. It does not store data on disk, allowing developers to use it as a fast backend for some temporary layers.
# To avoid 'QVariant' is not defined error
from PyQt4.QtCore import *
# create layer
vl = ...
4
Just a little thing to add to the last reply.
To search for a SEXTANTE algorithm about a given topic, use Sextante.alglist(). For instance, in the case of searching for something containing "buffer", you would do
>>> from sextante.core.Sextante import Sextante
>>> Sextante.alglist("buffer")
And you would get:
Grid ...
4
Inspired by this question & answer as an example of how "easily" can one make its own solutions when using Open Source, I have tried to create my own code to selectively "explode" multipart features during an editing session.
I have explored the QGIS 1.8 API for the first time, and came out with this piece of code that seams to do the job:
layer = ...
4
Browsing the QGIS source code, I've found a specific function, called buildSupportedRasterFileFilter. This code works well in the QGIS python console:
from PyQt4.QtCore import *
a = QString()
QgsRasterLayer.buildSupportedRasterFileFilter(a)
# "a" contains a string that can be used in a Dialog Window.
...
Now I'm browsing for a similar method that excludes ...
4
I suppose your question does not include change detection, as your sample only concerns QgsMapCanvas.refresh()
Instead you have to call QgsRasterLayer.triggerRepaint()
If your layer is called myLayer:
myLayer.setCacheImage( None )
myLayer.triggerRepaint()
The same method exists for vector layers as well.
For low overhead file change notification I'd ...
3
You can add icons to the toolbar or menus. There is no toolbox. For more info check the pyqgis Cookbook http://www.qgis.org/pyqgis-cookbook/plugins.html
def initGui(self):
# create action that will start plugin configuration
self.action = QAction(QIcon(":/plugins/testplug/icon.png"), "Test plugin", self.iface.mainWindow())
...
3
$ c++filt _ZN28QgsCoordinateReferenceSystem19createFromUserInputE7QString
QgsCoordinateReferenceSystem::createFromUserInput(QString)
QgsCoordinateReferenceSystem::createFromUserInput(QString) is new in 1.8. Are you sure your core.so is linked to the current library? Check with ldd /usr/lib/python2.7/dist-packages/qgis/core.so | grep qgis_core.
Maybe you ...
3
"Will the scale bar be "at scale" ?"
Your scale bar's scale will be relative to an existing composer map item that is assigned to it: QgsComposerScaleBar.setComposerMap(mymap_item_obj_here). So you will need to create the composer map item first, so it's scale can be referenced by the scale bar.
"I cannnot find anything from that page ScalBar class"
...
3
Renaud, there are a couple of ways to do this:
Query QGIS's interface to find and trigger the appropriate menu
action.
Work directly with the already-loaded OpenLayers plugin.
Solution #1 is pretty straightforward. OpenLayers plugin offers a good solution to #2, which will help you understand working with other plugins as well. Here is how both are ...
3
Changing of attribute types simply isn't supported.
You can only QgsVectorLayer::addAttribute or QgsVectorLayer::deleteAttribute. Those two will only work while editing (ie. between QgsVectorLayer::startEditing() and QgsVectorLayer::commitChanges()) and then QgsVectorLayer::pendingFields() will reflect those changes and so will the UI.
When not editing ...
3
Short answer
qgis.utils.iface.activeLayer().crs().authid()
# returns: PyQt4.QtCore.QString(u'EPSG:26913')
Explanation
qgis.utils.iface.activeLayer() returns a reference to the active QgsMapLayer.
QgsMapLayer.crs() returns the crs or QgsCoordinateReferenceSystem for the layer.
QgsCoordinateReferenceSystem.authid() returns the Authority identifier for ...
Only top voted, non community-wiki answers of a minimum length are eligible