I am developing a QGIS plugin and got currently stuck at setting the geometry of a feature based on coordinates.

I retrieve coordinates through an SQL query, create a feature and try to set the geometry.

#fetch sql query
rec = dict_cur.fetchone()

#create feature
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(rec[1], rec[2])))

In the code above rec[1] and rec[2] holding the information about longitude and latitude. When requesting the type of rec[1] or rec[2] it comes back as <class 'decimal.Decimal'> and I can cast it to float. However, that doesn't change anything.

When I try to set the coordinates for QgsPoint then I am getting the following error message:

feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(rec[1], rec[2])))
TypeError: 'NoneType' object has no attribute '__getitem__'

The error is directely related to QgsPoint. When I seperate QgsPoint and try to provide the coordinates I am getting the same error message.

That is for my plugin. If I use the same code in the Python console of QGIS then it works.

Python is in version 2.7.10 QGIS version is 2.8.2-Wien


Below is piece of test code that runs without errors when called normally with python <filename>. The imports are the same as the ones that are included by default in the python console embedded into QGIS, as documented here.

from qgis.core import *
import qgis.utils

# pretend sql record
rec = [0.0, 1.0, 2.0]

#create feature
feature = QgsFeature()
feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(rec[1], rec[2])))

The code was tested on python 2.7.6 and QGIS version 2.12.3-Lyon, but I doubt there would have been changes to such a fundamental API between minor versions.

The error you are getting is indicative of trying to access something that is set to None:

>>> None[1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object has no attribute '__getitem__'

At least fetchone() from python's sqlite3 package would return (and therefore set rec to) None if no data was available. Perhaps the connection to the database is behaving differently in the two different environments in which you are testing your code.

If the problem persist, it would be helpful if you could edit the question to include the code that initializes the SQL connection and what packages you have imported.

  • Thanks for this eye opener! I think I am sitting for too long in front of the screen. Of course, if the query doesn't find something then it returns 'None'. I didn't catch that event, instead pump every return straight into the creation of feature, and continue setting the geometry. – Thomas Becker Feb 18 '16 at 16:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.