[GIS] QGIS plugin: Problems importing resources (resources_rc) file – plugin doesn’t load – PATH problems

pyqgispyqtqgis-plugins

I'm building qgis plugin and I can't find solution for this error.

File "/usr/lib/python2.7/dist-packages/qgis/utils.py", line 478, in _import
    mod = _builtin_import(name, globals, locals, fromlist, level)
ImportError: No module named resources_napoved_rc

For everybody that will be asking I've built python resources file:

pyrcc4 -o resources_napoved_rc.py resources_napoved.qrc

I still can't find a way to make it work. I always get same error.

On top of the script I have:

import resources_napoved_rc.py

I'm using ui file directly from qtbuilder. Any ideas how to go forward ? I'm assuming this must be some kind of path problem or something similar.

Best Answer

This problem is caused by uic not working properly. I am not sure exactly why but I can show the symptoms and a workaround.

The initial plugin .ui file has an empty resources element:

<resources/>

When you edit the resources for the plugin in QtDesigner this changes to:

<resources>
  <include location="resources.qrc"/>
</resources>

This is the source of the problem. If you change the .qrc file in that include tag to resourcesXXX.qrc the error will change to No module named resourcesXXX_rc.

Note: the following is based upon a plugin build with 'test' entered into all fields of the QGIS plugin builder.

In the test_dialog.py file the following lines compile the .ui file:

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'test_dialog_base.ui'))

This is where the error is occurring.

Edit your .ui file to change back to <resources/> and the problem is resolved. Until you edit your dialog in QtDesigner again. You must make this edit to the .ui file after each time you edit your dialog.

The solution to this is to change your plugin to work like earlier versions of the plugin worked. This involves replacing the uic call and the class lines in the _dialog.py file. Replace these lines:

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'test_dialog_base.ui'))

class testDialog(QtGui.QDialog, FORM_CLASS):

with:

from test_dialog_base import Ui_testDialogBase

class testDialog(QDockWidget, Ui_testDialogBase):

You will now have to run

pyuic4 -x test_dialog_base.ui > test_dialog_base.py

when you first create your plugin and each time you edit your plugin dialog with QtDesigner. This was the old plugin method.

Whether to edit the .ui file or the run pyuic4 each time is your choice.

Related Question