Azad Rasul
SmartRS

SmartRS

26- Creating your plugin

Azad Rasul's photo
Azad Rasul

Published on Jun 18, 2021

2 min read

Subscribe to my newsletter and never miss my upcoming articles

The first requirement for plugins is metadata.txt.

Use a text editor to create a metadata file:

[general]
name=TestPlugin
email=azad.rasul@soran.edu.iq
author=Azad Rasul
qgisMinimumVersion=3.0
description=This is an example plugin for greeting the world.
version=version 1.0

save it as "metadata" text document.

Second file is called "init".py which include classFactory() method.

You can use Python to create init file _init_.png

from .mainPlugin import TestPlugin
def classFactory(iface):
  return TestPlugin(iface)

Third necessary file contains the main logic of the plugin. It must have init(), initGui, and unload method. We name it mainPlugin.py file that includes:

import os
import sys
import inspect
from PyQt5.QtWidgets import QAction
from PyQt5.QtGui import QIcon

cmd_folder = os.path.split(inspect.getfile(inspect.currentframe()))[0]
###
class TestPlugin:

  def __init__(self, iface):
    self.iface = iface

  def initGui(self):
    icon = os.path.join(os.path.join(cmd_folder, 'logo.png'))
    self.action = QAction(QIcon(icon), 'Test plugins', self.iface.mainWindow())
    self.action.triggered.connect(self.run)
    # add toolbar button and menu item
    self.iface.addToolBarIcon(self.action)
    self.iface.addPluginToMenu("&Test plugins", self.action)


  def unload(self):
    # remove the plugin menu item and icon
    self.iface.removePluginMenu("&Test plugins", self.action)
    self.iface.removeToolBarIcon(self.action)
    del self.action

  def run(self):
    # create and show a configuration dialog or something similar
    self.iface.messageBar().pushMessage('Hello from TestPlugin!')

Save these three files and a logo in one folder and name it "TestPlugin" or the name of the plugin.

Then, copy the file and past it in QGIS 3 Plugins directory. On my computer it is:

C:\Users\Azad\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins

Restart QGIS software and now you can see your "TestPlugin" plugin in the list of installed plugins.

Another method is to use "Plugin Builder" to create your template plugin then modify it.

Did you find this article valuable?

Support Azad Rasul by becoming a sponsor. Any amount is appreciated!

Learn more about Hashnode Sponsors
 
Share this
Proudly part of