17. 编写处理插件

根据您要开发的插件的类型,将其功能添加为处理算法(或其中的一组)可能是更好的选择。这将在QGIS中提供更好的集成、附加功能(因为它可以在处理的组件中运行,例如建模器或批处理接口),以及更快的开发时间(因为处理将占据大部分工作)。

要分发这些算法,您应该创建一个新的插件,将它们添加到处理工具箱中。插件应该包含一个算法提供程序,它必须在插件实例化时注册。

17.1. 从头开始创建

要从头开始创建包含算法提供程序的插件,可以使用插件生成器执行以下步骤:

  1. 安装 Plugin Builder 插件

  2. 使用插件生成器创建一个新插件。当plugin Builder询问您要使用的模板时,选择“Processing Provider”。

  3. 创建的插件包含一个具有单一算法的提供程序。提供程序文件和算法文件都有完整的注释,并包含有关如何修改提供程序和添加其他算法的信息。有关详细信息,请参阅它们。

17.2. 更新插件

如果您想要将现有插件添加到处理中,则需要添加一些代码。

  1. 在您的 metadata.txt 文件中,您需要添加一个变量:

    hasProcessingProvider=yes
    
  2. 在您的插件使用 initGui 方法,您需要修改一些代码行,如下所示:

     1from qgis.core import QgsApplication
     2from processing_provider.provider import Provider
     3
     4class YourPluginName():
     5
     6    def __init__(self):
     7        self.provider = None
     8
     9    def initProcessing(self):
    10        self.provider = Provider()
    11        QgsApplication.processingRegistry().addProvider(self.provider)
    12
    13    def initGui(self):
    14        self.initProcessing()
    15
    16    def unload(self):
    17        QgsApplication.processingRegistry().removeProvider(self.provider)
    
  3. 您可以创建文件夹 processing_provider 里面有三个文件:

    • __init__.py 里面什么都没有。这是制作有效的Python包所必需的。

    • provider.py 它将创建处理提供程序并公开您的算法。

       1from qgis.core import QgsProcessingProvider
       2
       3from processing_provider.example_processing_algorithm import ExampleProcessingAlgorithm
       4
       5
       6class Provider(QgsProcessingProvider):
       7
       8    def loadAlgorithms(self, *args, **kwargs):
       9        self.addAlgorithm(ExampleProcessingAlgorithm())
      10        # add additional algorithms here
      11        # self.addAlgorithm(MyOtherAlgorithm())
      12
      13    def id(self, *args, **kwargs):
      14        """The ID of your plugin, used for identifying the provider.
      15
      16        This string should be a unique, short, character only string,
      17        eg "qgis" or "gdal". This string should not be localised.
      18        """
      19        return 'yourplugin'
      20
      21    def name(self, *args, **kwargs):
      22        """The human friendly name of your plugin in Processing.
      23
      24        This string should be as short as possible (e.g. "Lastools", not
      25        "Lastools version 1.0.1 64-bit") and localised.
      26        """
      27        return self.tr('Your plugin')
      28
      29    def icon(self):
      30        """Should return a QIcon which is used for your provider inside
      31        the Processing toolbox.
      32        """
      33        return QgsProcessingProvider.icon(self)
      
    • example_processing_algorithm.py 其中包含示例算法文件。复制/粘贴 script template file 并根据您的需要进行更新。

  4. 现在您可以在QGIS中重新加载您的插件,并且应该在处理工具箱和建模器中看到您的示例脚本。