SHARE
TWEET

Untitled

a guest Oct 13th, 2019 92 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. """
  3. /***************************************************************************
  4. VectorWorker
  5.                                 A QGIS plugin
  6. OOLinGIS Lab 1 Var 3
  7. Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
  8.                              -------------------
  9.        begin                : 2019-09-16
  10.        git sha              : $Format:%H$
  11.        copyright            : (C) 2019 by Niyaz Lutfullin
  12.        email                : user@ugatu.su
  13. ***************************************************************************/
  14.  
  15. /***************************************************************************
  16. *                                                                         *
  17. *   This program is free software; you can redistribute it and/or modify  *
  18. *   it under the terms of the GNU General Public License as published by  *
  19. *   the Free Software Foundation; either version 2 of the License, or     *
  20. *   (at your option) any later version.                                   *
  21. *                                                                         *
  22. ***************************************************************************/
  23. """
  24. from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, Qt
  25. from qgis.PyQt.QtGui import QIcon, QTransform
  26. from qgis.PyQt.QtWidgets import QAction
  27. # Initialize Qt resources from file resources.py
  28. from .resources import *
  29.  
  30. # Import the code for the DockWidget
  31. from .vector_worker_dockwidget import VectorWorkerDockWidget
  32. from qgis.core import QgsProject, QgsGeometry, QgsPointXY, QgsFeature, QgsCoordinateTransform
  33. import os.path
  34. import math
  35.  
  36.  
  37. class VectorWorker:
  38.     """QGIS Plugin Implementation."""
  39.  
  40.     def __init__(self, iface):
  41.         """Constructor.
  42.  
  43.        :param iface: An interface instance that will be passed to this class
  44.            which provides the hook by which you can manipulate the QGIS
  45.            application at run time.
  46.        :type iface: QgsInterface
  47.        """
  48.         # Save reference to the QGIS interface
  49.         self.iface = iface
  50.  
  51.         self.selected_feature = None
  52.         self.active_layer = None
  53.  
  54.         # initialize plugin directory
  55.         self.plugin_dir = os.path.dirname(__file__)
  56.  
  57.         # initialize locale
  58.         locale = QSettings().value('locale/userLocale')[0:2]
  59.         locale_path = os.path.join(
  60.             self.plugin_dir,
  61.             'i18n',
  62.             'VectorWorker_{}.qm'.format(locale))
  63.  
  64.         if os.path.exists(locale_path):
  65.             self.translator = QTranslator()
  66.             self.translator.load(locale_path)
  67.             QCoreApplication.installTranslator(self.translator)
  68.  
  69.         # Declare instance attributes
  70.         self.actions = []
  71.         self.menu = self.tr(u'&Vector Worker (Lab 1)')
  72.         # TODO: We are going to let the user set this up in a future iteration
  73.         self.toolbar = self.iface.addToolBar(u'VectorWorker')
  74.         self.toolbar.setObjectName(u'VectorWorker')
  75.  
  76.         #print "** INITIALIZING VectorWorker"
  77.  
  78.         self.pluginIsActive = False
  79.         self.dockwidget = None
  80.  
  81.  
  82.     # noinspection PyMethodMayBeStatic
  83.     def tr(self, message):
  84.         """Get the translation for a string using Qt translation API.
  85.  
  86.        We implement this ourselves since we do not inherit QObject.
  87.  
  88.        :param message: String for translation.
  89.        :type message: str, QString
  90.  
  91.        :returns: Translated version of message.
  92.        :rtype: QString
  93.        """
  94.         # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
  95.         return QCoreApplication.translate('VectorWorker', message)
  96.  
  97.  
  98.     def add_action(
  99.         self,
  100.         icon_path,
  101.         text,
  102.         callback,
  103.         enabled_flag=True,
  104.         add_to_menu=True,
  105.         add_to_toolbar=True,
  106.         status_tip=None,
  107.         whats_this=None,
  108.         parent=None):
  109.         """Add a toolbar icon to the toolbar.
  110.  
  111.        :param icon_path: Path to the icon for this action. Can be a resource
  112.            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
  113.        :type icon_path: str
  114.  
  115.        :param text: Text that should be shown in menu items for this action.
  116.        :type text: str
  117.  
  118.        :param callback: Function to be called when the action is triggered.
  119.        :type callback: function
  120.  
  121.        :param enabled_flag: A flag indicating if the action should be enabled
  122.            by default. Defaults to True.
  123.        :type enabled_flag: bool
  124.  
  125.        :param add_to_menu: Flag indicating whether the action should also
  126.            be added to the menu. Defaults to True.
  127.        :type add_to_menu: bool
  128.  
  129.        :param add_to_toolbar: Flag indicating whether the action should also
  130.            be added to the toolbar. Defaults to True.
  131.        :type add_to_toolbar: bool
  132.  
  133.        :param status_tip: Optional text to show in a popup when mouse pointer
  134.            hovers over the action.
  135.        :type status_tip: str
  136.  
  137.        :param parent: Parent widget for the new action. Defaults None.
  138.        :type parent: QWidget
  139.  
  140.        :param whats_this: Optional text to show in the status bar when the
  141.            mouse pointer hovers over the action.
  142.  
  143.        :returns: The action that was created. Note that the action is also
  144.            added to self.actions list.
  145.        :rtype: QAction
  146.        """
  147.  
  148.         icon = QIcon(icon_path)
  149.         action = QAction(icon, text, parent)
  150.         action.triggered.connect(callback)
  151.         action.setEnabled(enabled_flag)
  152.  
  153.         if status_tip is not None:
  154.             action.setStatusTip(status_tip)
  155.  
  156.         if whats_this is not None:
  157.             action.setWhatsThis(whats_this)
  158.  
  159.         if add_to_toolbar:
  160.             self.toolbar.addAction(action)
  161.  
  162.         if add_to_menu:
  163.             self.iface.addPluginToMenu(
  164.                 self.menu,
  165.                 action)
  166.  
  167.         self.actions.append(action)
  168.  
  169.         return action
  170.  
  171.  
  172.     def initGui(self):
  173.         """Create the menu entries and toolbar icons inside the QGIS GUI."""
  174.  
  175.         icon_path = ':/plugins/vector_worker/icon.png'
  176.         self.add_action(
  177.             icon_path,
  178.             text=self.tr(u''),
  179.             callback=self.run,
  180.             parent=self.iface.mainWindow())
  181.  
  182.     @staticmethod
  183.     def load_opened_layers_names():
  184.         opened_layers = QgsProject.instance().mapLayers().values()
  185.         return [layer.name() for layer in opened_layers]
  186.  
  187.     def change_selected_feature(self):
  188.         vectors = self.active_layer.selectedFeatures()
  189.         if vectors:
  190.             first_vector = vectors[0]
  191.             self.selected_feature = first_vector
  192.             self.dockwidget.startBtn.setEnabled(True)
  193.             self.dockwidget.selectedVector.setText(str(first_vector.id()))
  194.         else:
  195.             self.selected_feature = None
  196.             self.dockwidget.selectedVector.setText('None')
  197.             self.dockwidget.startBtn.setEnabled(False)
  198.  
  199.     def get_increased_polygon(self):
  200.         selected_polygon = self.selected_feature.geometry()
  201.         increase_param = int(self.dockwidget.increaseByEdit.text())
  202.         polygon = QgsFeature()
  203.         selected_polygon.transform(QTransform().scale(increase_param, increase_param))
  204.         polygon.setGeometry(selected_polygon)
  205.         selected_layer = self.dockwidget.layerSelector.currentText()
  206.         layer = QgsProject.instance().mapLayersByName(selected_layer)[0]
  207.         layer.dataProvider().addFeatures([polygon])
  208.         layer.commitChanges()
  209.  
  210.     #--------------------------------------------------------------------------
  211.  
  212.     def onClosePlugin(self):
  213.         """Cleanup necessary items here when plugin dockwidget is closed"""
  214.  
  215.         print("** CLOSING VectorWorker")
  216.  
  217.         # disconnects
  218.         self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)
  219.  
  220.         # remove this statement if dockwidget is to remain
  221.         # for reuse if plugin is reopened
  222.         # Commented next statement since it causes QGIS crashe
  223.         # when closing the docked window:
  224.         # self.dockwidget = None
  225.  
  226.         self.pluginIsActive = False
  227.         self.dockwidget.layerSelector.clear()
  228.  
  229.  
  230.     def unload(self):
  231.         """Removes the plugin menu item and icon from QGIS GUI."""
  232.  
  233.         print("** UNLOAD VectorWorker")
  234.  
  235.         for action in self.actions:
  236.             self.iface.removePluginMenu(
  237.                 self.tr(u'&Vector Worker (Lab 1)'),
  238.                 action)
  239.             self.iface.removeToolBarIcon(action)
  240.         # remove the toolbar
  241.         del self.toolbar
  242.  
  243.     #--------------------------------------------------------------------------
  244.  
  245.     def run(self):
  246.         """Run method that loads and starts the plugin"""
  247.  
  248.         if not self.pluginIsActive:
  249.             self.pluginIsActive = True
  250.  
  251.             print("** STARTING VectorWorker")
  252.  
  253.             # dockwidget may not exist if:
  254.             #    first run of plugin
  255.             #    removed on close (see self.onClosePlugin method)
  256.             if self.dockwidget == None:
  257.                 # Create the dockwidget (after translation) and keep reference
  258.                 self.dockwidget = VectorWorkerDockWidget()
  259.  
  260.             # connect to provide cleanup on closing of dockwidget
  261.             self.dockwidget.closingPlugin.connect(self.onClosePlugin)
  262.             self.dockwidget.startBtn.clicked.connect(self.get_increased_polygon)
  263.  
  264.             # show the dockwidget
  265.             # TODO: fix to allow choice of dock location
  266.             self.iface.addDockWidget(Qt.TopDockWidgetArea, self.dockwidget)
  267.             self.dockwidget.show()
  268.  
  269.             opened_layers = self.load_opened_layers_names()
  270.             self.active_layer = self.iface.activeLayer()
  271.             self.active_layer.selectionChanged.connect(self.change_selected_feature)
  272.             self.active_layer.setAutoRefreshEnabled(True)
  273.             self.dockwidget.layerSelector.addItems(opened_layers)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top