2

I am starting with QGIS python console. Naturally, I came across the PyQGIS Developer Cookbook. While trying to cut my way through it, I encountered a lot of problems with "undefined attributes and names".

Some of them are caused by not importing some library. I had the same problem as described here.

NameError: name 'QImage' is not defined

Even though I imported the PyQt4.QtGui library. At least, I thought:

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on N-PC
## Type help(iface) for more info and list of methods.
help(QImage)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'QImage' is not defined
import PyQt4.QtGui
help(QImage)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'QImage' is not defined
from PyQt4.QtGui import *
help(QImage)
Help on class QImage in module PyQt4.QtGui:

class QImage(QPaintDevice)
 |  QImage()
 |  QImage(QSize, QImage.Format)
 |  QImage(int, int, QImage.Format)

And the help goes on. Why did QGIS fail to load QImage by the 1st import command? Or what actually happened here? I am using QGIS 2.4.0, and I get the same issue in 2.0.1.

1

1 Answer 1

2

This more of a core python issue rather than a pyqgis issue.

You should note that QImage is a class in the QtGui module.

When you type import PyQt4.QtGui, you import the whole module. If you want to refer to the class QImage in this state, you'll have to give the complete qualified name of the class, such as: PyQt4.QtGui.QImage Importing the whole module is helpful, when you will use many classes in your code.

In case you are referring to just one class, you can import just that class, instead of importing the whole module. You can do this by running: from PyQt4.QtGui import QImage

When you use * in-place of the name of the class, like you are doing with from PyQt4.QtGui import *, it will import all the classes in the module. This is not recommended, since all those classes will be available in your code, and in-case you have another class of the same name, it will cause a conflict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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