7

I want to create my own custom forms using Python for QGIS, and since some of the forms will share some definitions and objects I would like to have my own classes for all of them. For that, when I try to import my classes in the python logic form file I get this error with the following tries:

  • With import comDef I get ImportError: No module named 'comDef'
  • With from .comDef import * I get SystemError: Parent module '' not loaded, cannot perform relative import
  • With from comDef import * I get ImportError: No module named 'comDef'

These custom forms are located in a folder where the custom python logics and custom classes are.

Can you provide any hint about this issue?

0

2 Answers 2

2

I've been struggling with something similar, and here is my understanding of how the imports work:

  • With 'import comDef' and 'from comDef import * ' is looking for the comDef python module (comDef.py file) in the Libs folder for that instance of python. QGIS has it's own Python instance, so in the case of QGIS3 on my Windows PC this location is here: "C:\Program Files\QGIS 3.4\apps\Python37\Lib", this may be in a different location on your computer.
  • With 'from .comDef import *' this is looking for comDef.py in the same folder as the script which imported the module.

So in your case, because you want to use a module between lots of your plugins you want to store it in the Python Libs folder for your QGIS. If you wanted to share the plugin, I'm not sure how you can put a .py file in the Libs folder on install.

Here is a post on how imports work in Python 3: https://stackoverflow.com/questions/12172791/changes-in-import-statement-python3

2

The from .comDef import line is right if you want to reference to a module directly in the directory of your plugin (where the pb_tool.cfg is located)


How I solved it was editing the pb_tool.cfg file:

[files]
#Python files that should be deployed with the plugin
python_files: __init__.py yournewcoolfile.py
ADD YOUR MODULE NAMES HERE, same line, space as divider
...
...
# Other directories to be deployed with the plugin.
# These must be subdirectories under the plugin directory
extra_dirs:
yourfoldername
yourcoolfoldername
Add dir name of subdir of plugin here, divider is a new row, I used a Tab before

The [files] should also include the names from your main.py and your main_dialog.py by default.


What I did before (Ubuntu 18.04):

  • create a Plugin following these instructions: Building a Python Plugin by qgistutorials.com
  • tried to run make from the plugin dir
  • installed pb_tool after make told me to use it :D
  • ran pb_tool deploy from plugin dir(add -y if you're doing it doing over and over again like me :D)

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.