4

I have recently exported a model to a python script that is actually dependant on another Python Script I have converted from a previous model. Because the First Script/model F1 gets repeated three times (for all three vector types) and writing it three times is a hassle so I had to separate my completed model into two. But because of that I have a bit of trouble to convert these two scripts combined into 1 plug-in. Every tutorial I found spoke so far that of only one model to one script to one plug-in. But never have I found something like of where I convert two scripts, where the second script is dependant on the first script.

1 Answer 1

3

To add 2 or more scripts (i.e. algorithms) you need to add the new module (i.e. algorithm_name_algorithm.py file) into your plugin directory and then reference it in the provider module (i.e. plugin_name_provider.py).

First you tell the provider module to access the new algorithm from a different module by entering a line such as this at the top of you script:

from .new_algorithm import NewAlgorithm

Here .new_algorithm would be the same as the file name (i.e. new_algorithm.py) and NewAlgorithm would be the name of the class inside that file.

Next go down to the loadAlgorithms function (i.e. def loadAlgorithms(self)) and add the line:

self.addAlgorithm(NewAlgorithm())

That's it. As long as all the names match up between the 2 files you should now have 2 algorithms in your plug-in.

An alternative, If you want to do as little coding as possible is to add the models directly to your plugin without converting them to scripts.

First copy all the model files (*.model3) to your plug-in directory.

Second open the provider module (plugin_name_provider.py) and add the following 2 lines to the top:

import os
from qgis.core import QgsProcessingModelAlgorithm

Lastly, go down to you loadAlgorithms function and add the following lines:

for dirpath, dirnames, files in os.walk(os.path.dirname(__file__)):
    for file_name in files:
        if file_name.lower().endswith('.model3'):
            alg = QgsProcessingModelAlgorithm()
            alg.fromFile(os.path.join(dirpath, file_name))
            self.addAlgorithm(alg)

This bit of code will cycle through your plug-in directory and any subdirectories and add all models that you have placed in there to your plug-in.

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.