Quantcast
Channel: Question and Answer » pyqgis
Viewing all 64 articles
Browse latest View live

PyQGIS – load PostGIS layer as editable

$
0
0

I can load a PostGIS layer on QGIS’ map canvas but “Toggle Editing” button comes “inactive”. How can I load vector layer as editable?

The code given below loads PostGIS layer on map canvas & “Toggle Editing” button comes “active” but once I run the script below in Python console; when I press “Toggle Editing” button, QGIS gives me an info message: “Start editing failed: Provider cannot be opened for editing”:

sql = "(SELECT * FROM tablename)"
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "database", "postgres", "password")
uri.setDataSource("", sql, "geom", "", "gid")
vlayer = QgsVectorLayer(uri.uri(), "abc", "postgres")
QgsMapLayerRegistry.instance().addMapLayer(vlayer)

# should the layer be set as "active" ???

vlayer.dataProvider()
vlayer.dataProvider().capabilities()
vlayer.startEditing()
iface.actionToggleEditing().setEnabled(True)

Can someone please give me a hint on how to load an editable layer programmatically?


Can we avoid using SIP library when writing standalone QGIS python script

$
0
0

I wanted to write a small custom python script using QGIS functionality. So I started with the QGIS documentation on the custom application section.

After having some troubles with the import qgis.core statement, which I could fix, I ran into the error message

ImportError: No module named sip

This one made me somewhat of a headache, as you could see here.

As I could not fix this one, I wonder why it’s so much of a problem. Also, the doc states

“PyQGIS bindings depend on SIP and PyQt4.”

So I wonder, why it actually complains. Shouldn’t it then come with the QGIS distribution? (Actually, there is a sip folder containing PyQT4 folder and also a sip.exe. But this does not seem to be of any effect.)

After all, my question is, is it possible to work around it, getting QGIS python running without SIP?

pyscripter : add a legend to my vector layer

$
0
0

I work on PyScripter, i managed to display a vector layer from Postgresql with a symbology.
But I have a difficulty to display a legend.

def main():

def init():

# appel de l’application et initialisation
a = QgsApplication(sys.argv, True)
QgsApplication.setPrefixPath(“C:/OSGeo4W/apps/qgis”, True)
QgsApplication.initQgis()
return a

def show_shape(app):

# definition a connection
uri = QgsDataSourceURI()
uri.setConnection("localhost", "5432", "stat", "postgres", "admin")
uri.setDataSource("public", "com", "the_geom", ' ', "gid")
uri.uri()

# création d'une fenêtre et chargement d'une couche
carte = QgsMapCanvas()
layer=QgsVectorLayer(uri.uri(), 'com', 'postgres')
if not layer.isValid():
   print "Layer failed to load!"

# add layer to the registry
QgsMapLayerRegistry.instance().addMapLayer(layer)
carte.setExtent(layer.extent())

# affichage de la couche dans une fenêtre
carte.setLayerSet( [ QgsMapCanvasLayer(layer) ] )
carte.show()

#personnaliser la symbologie
myTargetField = 'code'
myRangeList = []
myOpacity = 1

# Make our first symbol and range...
myMin = 0.0
myMax = 100.0
myLabel = '0.0-200'
myColour = QtGui.QColor('white')#ffee00
mySymbol1 = QgsSymbolV2.defaultSymbol(layer.geometryType())
mySymbol1.setColor(myColour)
mySymbol1.setAlpha(myOpacity)
myRange1 = QgsRendererRangeV2(myMin,myMax,mySymbol1,myLabel)
myRangeList.append(myRange1)

#now make two symbol and range...
myMin = 100.1
myMax = 102
myLabel = '200.1-500'
myColour = QtGui.QColor('yellow')#00eeff
mySymbol2 = QgsSymbolV2.defaultSymbol(layer.geometryType())
mySymbol2.setColor(myColour)
mySymbol2.setAlpha(myOpacity)
myRange2 = QgsRendererRangeV2(myMin,myMax,mySymbol2,myLabel)
myRangeList.append(myRange2)

myRenderer = QgsGraduatedSymbolRendererV2('', myRangeList)
myRenderer.setMode(QgsGraduatedSymbolRendererV2.EqualInterval)
myRenderer.setClassAttribute(myTargetField)

layer.setRendererV2(myRenderer)
QgsMapLayerRegistry.instance().addMapLayer(layer)
print "fine"

app.exec_()

app = init()
show_shape(app)

if name == “main“:
main()

PyQGIS: how to delete layer from TOC when attribute table is closed?

$
0
0

I’m developing plugin where I want to be able to edit non-spatial table inside the attribute table dialogue. As it seems that the only way to do so is to add this table to the TOC first, I do so. But it is pointless to keep this table inside the TOC after the editing is done and the attribute table is closed. I would like to remove table from TOC right after the attribute window is closed. Is there a way to catch the signal from the showAttributeTable() when it is destroyed? Or is there a way not to add table to TOC in the first place?

Here is the code that I use:

def qgisOpenTable(self, layer_name, schema, table, geom_column=None, subset=None):
      '''
      Opens table in QGIS attribute table window
      '''
      uri = QgsDataSourceURI()
      uri.setConnection(self.server, self.port, self.db_name, self.login, self.password)  
      uri.setDataSource(schema, table, geom_column, subset)
      vlayer = QgsVectorLayer(uri.uri(), layer_name, "postgres")
      QgsMapLayerRegistry.instance().addMapLayer(vlayer)
      layer_id = vlayer.id()
      i = iface.showAttributeTable(vlayer)

      # I would like to have something like this:
      i.destroyed.connect(QgsMapLayerRegistry.instance().removeMapLayer(layer_id))

The only workaround that came to my mind is to remove table after some time, but this is suboptimal.

PyQGIS: How to get the list of valid layers in TOC?

$
0
0

To get the list of TOC layer names I used the approach suggested here:

for layer in QgsMapLayerRegistry.instance().mapLayers().values():
    print layer.name()

But this method is not reliable due to it is able to catch “phantom” layers that are created when the preview option in DB Manager plugin is used (see this ticket) and were never added to TOC by user. Here is what happens:

>>>def laylist():
>>>  l=[]
>>>  for layer in QgsMapLayerRegistry.instance().mapLayers().values():
>>>    item = layer.name()
>>>    l.append(item)
>>>  print l
# There is only one layer 'buf' (a shp-file) in QGIS TOC. Check the TOC
>>>laylist()
[u'buf']
# Now open DM Manager, connect to the PostGIS DB and preview one of the spatially enabled tables ('park_kvartal3_utm') without adding them to TOC
# Check TOC again:
>>>laylist()
[u'park_kvartal3_utm', u'buf']
# Now in DB Manager select another spatial table ('itog_region_utm') and preview it without adding it to TOC
>>>laylist()
[u'park_kvartal3_utm', u'itog_region_utm', u'buf']
# Close DB Manager and catch exception. 
Exception RuntimeError: 'wrapped C/C++ object of type PGVectorTable has been deleted' in <bound method PGTableDataModel.__del__ of <db_manager.db_plugins.postgis.data_model.PGTableDataModel object at 0x7f17550dedf8>> ignored
# Check TOC content again after the DB Manager is closed. Notice: no layer was added to TOC by user during DB Manager session. The names of table remains:
>>>laylist()
[u'park_kvartal3_utm', u'itog_region_utm', u'buf']

However scripts from the Processing Toolbox displays only valid user-added layers in corresponding comboboxes, which indicates that there is another method for fetching layer names (or filtering valid ones) is implemented. How to get only layers that are displayed at TOC?

How to set CRS in QGIS using pyQGIS

$
0
0

This question is very similar to these one , but it’s doesn’t work for me.
This is my try:
……..

vlayer.setCrs(QgsCoordinateReferenceSystem(25830))
iface.mapCanvas().mapRenderer().setDestinationCrs(QgsCoordinateReferenceSystem(25830))

But the dialog pop up asking for CRS to choose, and when I ask for the CRS of the layer, it show a diferent CRS:

print "CRS: " + vlayer.crs().geographicCRSAuthId()

It show CRS: EPSG:4258 and It must be 25830

Labeling layers with Python in QGIS. LinePlacementFlags

$
0
0

How could I set LinePlacementFlags with Python in QGIS?
My code is something like:

palyr = QgsPalLayerSettings()
palyr.readFromLayer(layer)
palyr.enabled = True
palyr.fieldName = "attribute"

Then I’ve tried:

palyr.placement= QgsPalLayerSettings.Line

And my labels are on the line. I want them above the line, but I can’t figure how to do this.
I found there is LinePlacementFlags type. But

palyr.LinePlacementFlags= QgsPalLayerSettings.AboveLine

didn’t work.

How to change the “application_name” of a PostGIS-connection in QGIS?

$
0
0

PostGIS offers a view called pg_stat_activity, where you can see all the active connections to the database. This view includes the interesting column application_name. When a connection comes from a QGIS instance, the text “QGIS” appears there.

An application can send this parameter to PostGIS in the connection string, and I suppose that QGIS do it so. The connection string looks than more or less like that:

host=... port=... dbname=... user=... password=... application_name=QGIS

I would like to change this value in QGIS to include the username (that I will get from the operating system). Instead of “QGIS”, I would like to see something like “QGIS for user1″. Is there a was to do that, may be by changing the connection string using a pyQGIS script or any other solution?

Edit:

I just tried following thing: using the python console I made use of the function setEncodedUri which seems allow all possible connection parameters. But it doesn’t work: The application_name appears in the layer properties in QGIS but in PostGIS I still just see “QGIS” and nothing more. This are the lines I was using for this test:

    uri = QgsDataSourceURI()
    uri.setEncodedUri("host=...&port=...&dbname=...&user=...&password=...&application_name=QGIS for user1")
    uri.setDataSource("MySchema", "MyTable", "wkb_geometry", "")
    vlayer = QgsVectorLayer(uri.uri(), "MyLayerName", "postgres")
    QgsMapLayerRegistry.instance().addMapLayer(vlayer)

Edit2: I had a look in the source code of QGIS 2.8: the trick with setEncodedUri can’t work, because the code calls SET application_name='QGIS' just after opening the connection and that overwrites my setting!

I’m still looking for a working solution…

Edit3

It possible to set the environment variable PGOPTIONS to something like “-c application_name=QGISuser1” or even easier the environment varaible PGAPPNAME (see fallback_application_name) before starting QGIS. It’s used to change some postgres configuration variables for the current session. I tried it with over variables and it worked. But as QGIS overwrites the value of application_name after opening the connection, it doesn’t work for this variable. And I’m now thinking, that there are probably no ways to do what I want with the current version of QGIS.


Number of intersected features from one layer per feature from second layer

$
0
0

How can I get number of intersecting features from one layer per feature from second layer using any component from QGIS 2.8 (GRASS, SAGA, Python scripting…)? Result should be stored in new attribute column.

PyQgis – saga:catchmentareaparallel parameters

$
0
0

in PyQGis i want to use saga:catchmentareaparallel algorithme, in the parametres there is an optionnel arguments , and i don’t want to use theme , what is the value should i put on the argument?? i try to put null and “” but unfortuntly not working . please help

processing.runalg('saga:catchmentareaparallel', elevation, sinkroute, weight, material, target, step, method, dolinear, linearthrs, linearthrs_grid, chdir_grid, convergence, carea, cheight, cslope, accu_tot, accu_left, accu_right, caspect, flwpath)

Error: Algorithm not found (QGIS)

$
0
0

I wrote the following code using QGIS’API.

import os

from qgis.core import *
import qgis.utils

prefix_path = os.environ['QGIS_PREFIX_PATH']
QgsApplication.setPrefixPath(prefix_path, True)
QgsApplication.initQgis()
app = QgsApplication([], True)

import processing
from processing import *

class DummyInterface(object):
    def __init__(self):
        self.destCrs = None
    def __getattr__(self, *args, **kwargs):
        def dummy(*args, **kwargs):
            return DummyInterface()
        return dummy
    def __iter__(self):
        return self
    def next(self):
        raise StopIteration
    def layers(self):
        # simulate iface.legendInterface().layers()
        return qgis.core.QgsMapLayerRegistry.instance().mapLayers().values()
iface = DummyInterface()
plugin = processing.classFactory(iface)

uri = "file:///C:UsersTabrezDesktopimportPoint.csv?crs=epsg:4326&delimiter=%s&xField=%s&yField=%s" % (",", "lon", "lat")
layer = QgsVectorLayer(uri, "importPoints", "delimitedtext")
layer1 = iface.addVectorLayer(uri, "importPoints", "delimitedtext")
extent = layer.extent()
xmin = extent.xMinimum()
xmax = extent.xMaximum()
ymin = extent.yMinimum()
ymax = extent.yMaximum()
outputExtent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(ymax)
radius = 0.05
cellSize = 0.005
print cellSize
processing.runandload("saga:kerneldensityestimation", layer, "weightage", radius, 0, outputExtent, cellSize, "D:/test/raster.tif")

iter = layer.getFeatures()
pointCount = len(list(iter))
probabilityFailure = [[0.846], [0.846, 0.846], [0.28, 0.50, 0.72], [0.21, 0.39, 0.61, 0.79], [0.17, 0.32, 0.50, 0.68, 0.83], [0.14, 0.27, 0.42, 0.58, 0.73, 0.86], [0.12, 0.23, 0.36, 0.50, 0.64, 0.77, 0.88], [0.10, 0.20, 0.32, 0.44, 0.56, 0.68, 0.80, 0.90], [0.09, 0.18, 0.28, 0.39, 0.50, 0.61, 0.72, 0.82, 0.91], [0.08, 0.16, 0.26, 0.35, 0.45, 0.55, 0.65, 0.74, 0.84, 0.92], [0.07, 0.15, 0.23, 0.32, 0.41, 0.50, 0.59, 0.68, 0.77, 0.85, 0.93]]
for i in probabilityFailure:
    print i
os.system("gdal_contour -a 0.21 -fl 0.01 " + " D:/test/raster.tif " + " " +  "D:/test/contour")
QgsApplication.exitQgis()

This line is giving me error:

processing.runandload("saga:kerneldensityestimation", layer, "weightage", radius, 0, outputExtent, cellSize, "D:/test/raster.tif")

I am very new to python and QGIS.

different way to build qgis python standalone application

$
0
0

There seems to be 2 different ways to start a Python QGIS standalone script.
The official tutorial is using :

from qgis.core import *
# supply path to where is your qgis installed
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
# load providers
QgsApplication.initQgis()

But I have also seen code looking like this :

from qgis.core.contextmanagers import qgisapp
with qgisapp() as app:
    #do stuff

For example here and here.

I didn’t see any reference to the latter method on the official doc.

Does anybody know if there is a difference between the two ?

QGIS 2.8 starts with an error and I am not able to run Python console

$
0
0

I have installed QGIS 2.8 – Wien on Linux Red Hat 7. Unfortunately when I start the application I got this python error:

{Couldn't load plugin 'processing' from ['/usr/share/qgis/python', '/home/qgisosr/.qgis2/python', '/home/qgisosr/.qgis2/python/plugins', '/usr/share/qgis/python/plugins', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.7/site-packages', '/home/qgisosr/.qgis2//python', '/usr/share/qgis/python/plugins/fTools/tools']


Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 196, in loadPlugin
    __import__(packageName)
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/__init__.py", line 29, in 
    from processing.tools.general import *
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/tools/general.py", line 28, in 
    from processing.core.Processing import Processing
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/core/Processing.py", line 44, in 
    from processing.gui.Postprocessing import handleAlgorithmResults
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/gui/Postprocessing.py", line 36, in 
    from processing.gui.ResultsDialog import ResultsDialog
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/gui/ResultsDialog.py", line 33, in 
    from processing.ui.ui_DlgResults import Ui_DlgResults
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/plugins/processing/ui/ui_DlgResults.py", line 61, in 
    from QtWebKit.QWebView import QWebView
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named QtWebKit.QWebView

Python version:
2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)]

QGIS version:
2.8.1-Wien Wien, exported

Python path: ['/usr/share/qgis/python', u'/home/qgisosr/.qgis2/python', u'/home/qgisosr/.qgis2/python/plugins', '/usr/share/qgis/python/plugins', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.7/site-packages', u'/home/qgisosr/.qgis2//python', '/usr/share/qgis/python/plugins/fTools/tools']}

I his close and QGIS stars.
If I try to launch Python console I get this error:

{Failed to open Python console:

Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/console/__init__.py", line 26, in 
    from console import show_console
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/console/console.py", line 29, in 
    from console_settings import optionsDialog
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/console/console_settings.py", line 24, in 
    from console_compile_apis import PrepareAPIDialog
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/console/console_compile_apis.py", line 28, in 
    from ui_console_compile_apis import Ui_APIsDialogPythonConsole
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
  File "/usr/share/qgis/python/console/ui_console_compile_apis.py", line 70, in 
    from Qsci.qsciscintilla import QsciScintilla
  File "/usr/lib64/python2.7/site-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named Qsci.qsciscintilla

Python version:
2.7.5 (default, Feb 11 2014, 07:46:25)
[GCC 4.8.2 20140120 (Red Hat 4.8.2-13)]

QGIS version:
2.8.1-Wien ‘Wien’, exported

Python path:
['/usr/share/qgis/python', u'/home/qgisosr/.qgis2/python', u'/home/qgisosr/.qgis2/python/plugins', '/usr/share/qgis/python/plugins', '/usr/lib64/python27.zip', '/usr/lib64/python2.7', '/usr/lib64/python2.7/plat-linux2', '/usr/lib64/python2.7/lib-tk', '/usr/lib64/python2.7/lib-old', '/usr/lib64/python2.7/lib-dynload', '/usr/lib64/python2.7/site-packages', '/usr/lib64/python2.7/site-packages/gtk-2.0', '/usr/lib64/python2.7/site-packages/wx-2.8-gtk2-unicode', '/usr/lib/python2.7/site-packages', u'/home/qgisosr/.qgis2//python', '/usr/share/qgis/python/plugins/fTools/tools']}

Anybody had this issue?

How to create empty polygon shapefiles with the same field names using python?

$
0
0

I’m new to python scripting in GIS and I have a list with species names, for every species in the list I want to create an empty polygon shapefile with the same fields inside the attribute. I read How to create a new Shapefile with the same attributes as an existing one? but for about 650 polygons its very difficult to get done by hand.

Ideally I would like to done this by using python.

Can anyone help me?

How to create a plugin GUI for QGIS 2.8.2?

$
0
0

I create a pluging with the pluging builder in Qgis 2.8.2. I went to the folder of my pluging : C:OSGeo4W64appsqgispythonpluginsyu in order to visualize al the files that the pluging builder created. After i launch the OSGeo4w batch file, in order to create the .ui file of my pluging by using the command:

pyuic4 -o ....

Here’s the error that i have:
enter image description here


QGIS Export Shapefile

$
0
0

i am trying to export selected feature using pyqgis.

till now i have tried these codes. after using this i can select feature but dont know how to export selected feature to new shapefile.

canvas= iface.mapCanvas()
AllLayers=canvas.layers()
for i in AllLayers:
    it = i.getFeatures( QgsFeatureRequest().setFilterExpression ( u'"Country" = 'India'' ) )
    i.setSelectedFeatures( [ f.id() for f in it ] )
    print "Filter Applied"

have tried this code :- but this is just creating a duplicate of source file ( i need selected Only)

_writer = QgsVectorFileWriter.writeAsVectorFormat(i,r"C:UsersXYZDesktopNewFile.shp","utf-8",None,"ESRI Shapefile")

If Anybody know please help. thanks in advance

PyQGIS – controlling the proxy

$
0
0

I operate behind a firewall at work, and so to access the many very awesome plugins and other external goodies for QGIS I need to use a proxy.
We also have our own WMS server – which doesn’t like the proxy.
To access the internal WMS, I need the proxy off, to access an external WFS I need it on.

Is there a way, using PyQGIS, to control the proxy (as found in Settings > Options > Network)?

Does anyone know of any examples I can refer to?

With thanks,

Failed to create memory layers in QGIS application on Linux

$
0
0

I have written a python class which reads properties of map layers from an XML file and creates appropriate memory layers. I have developed and tested this code with QGIS 2.8.2 on a Windows 7 machine (importing the class at the python console and calling the class methods). As the module should be used in a Linux environment I did the same successfully with QGIS 2.8.2 on CentOs 7 – all map layers were successfully created and symbolized.

Then I refactored the code to fit in the framework of a QGIS standalone application. There are major problems with threads and such stuff, but the app starts and comes up with all layers created, and working methods.

Now comes the strange part. In the standalone CentOs version the creation of memory layers doesn’t work – layers are not valid. Even a simplified test without field definitions, no crs doesn’t work.

layer = QgsVectorLayer(type + '?crs=EPSG:' + str(epsg) + fields, layer_name, 'memory')

Hundreds of lines of code before and after this line are the same in all versions. Has anybody an idea how to handle this problem? Maybe a bug?

PyQGIS standalone script does not work. Error “QGraphicsScene::addItem: item has already been added to this scene”

$
0
0

I try to test a PyQGIS standalone script which should just show one Shapefile.
Sounds pretty simple but does not work.

Here is my script:

from PyQt4 import *
from PyQt4 import *
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
import sys
import os

qgishome = "C:OSGeo4W64appsqgis"

app = QgsApplication([], True)
QgsApplication.setPrefixPath(qgishome, True)
QgsApplication.initQgis()

canvas = QgsMapCanvas()
canvas.setCanvasColor(Qt.yellow)
canvas.enableAntiAliasing(True)
canvas.show()

layer = QgsVectorLayer(r"C:/daten/polygons.shp", "Testdaten", "ogr")
reg = QgsMapLayerRegistry.instance()
reg.addMapLayer(layer)
canvas.setExtent(layer.extent())
canvas.setLayerSet([QgsMapCanvasLayer(layer)])
QgsApplication.exitQgis()

app.exec_()

app.exitQgis()

The Window openes, I can see the yellow background but the Layer is not shown. instad of that there is an error message:

QGraphicsScene::addItem: item has already been added to this scene
QObject::connect: Cannot connect (null)::repaintRequested() to QgsMapCanvas::ref
resh()
QObject::connect: Cannot connect (null)::layerCrsChanged() to QgsMapCanvas::laye
rCrsChange()

Sometimes this also brings python to crash, so that a windows error reporting is opened.

I loaded the neccessary environmental variables, which should be ok, as I can import qgis.core and qgis.gui without problems.

does anyone has an idea what’s the problem?

Iteratively Change Object's Instance Attributes PyQGIS

$
0
0

I am trying to create new instance attributes (NOT feature attributes) for a collection of features in a vector layer in PyQGIS. I’m getting some weird results and am wondering if this is even possible. For instance, I can change the instance attributes of a single feature:

feat = iface.activeLayers().getFeatures().next()

feat.NEW = ‘attribute’

And it seems to commit to that feature:

dir(feat)

['NEW', 'class', 'delattr', 'delitem', 'dict', 'doc', 'format', 'geo_interface', 'getattribute', 'getitem', 'hash', 'init', 'iter', 'module', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setitem', 'sizeof', 'str', 'subclasshook', 'weakref', 'attribute', 'attributes', 'deleteAttribute', 'fieldNameIndex', 'fields', 'geometry', 'geometryAndOwnership', 'id', 'initAttributes', 'isValid', 'setAttribute', 'setAttributes', 'setFeatureId', 'setFields', 'setGeometry', 'setGeometryAndOwnership', 'setValid']

feat.NEW

‘attribute’

However, when I try to iterate through the features using a feature iterator, I get no such luck!

for feat in iface.activeLayer().getFeatures():

feat.NEW = ‘attribute’

Then check:

feat = iface.activeLayer().getFeatures().next()

feat.NEW

Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘QgsFeature’ object has no attribute ‘NEW’

I’m assuming that the feature iterator creates some objects that have access to the features within the layer but does not actually point to the feature objects themselves… does anyone know of a way to iteratively change the instance attributes of PyQGIS objects? Is this even possible?

Viewing all 64 articles
Browse latest View live