class QScatterPlugin: def __init__(self, iface): self.iface = iface overrideLocale = QSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value('locale/userLocale', '') qmPath = '{}/i18n/qscatter_{}.qm'.format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) def initGui(self): self.actionRun = QAction( self.tr('QScatter'), self.iface.mainWindow()) self.actionRun.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'qscatter.svg'))) self.actionRun.setWhatsThis( self.tr('Interactive scatter plot')) self.actionRun.setObjectName('runQScatter') self.actionAbout = QAction( self.tr('About...'), self.iface.mainWindow()) self.actionAbout.setIcon( QgsApplication.getThemeIcon('/mActionHelpContents.svg')) self.actionAbout.setWhatsThis(self.tr('About QScatter')) self.actionRun.setObjectName('aboutQScatter') self.iface.addPluginToVectorMenu( self.tr('QScatter'), self.actionRun) self.iface.addPluginToVectorMenu( self.tr('QScatter'), self.actionAbout) self.iface.addVectorToolBarIcon(self.actionRun) self.actionRun.triggered.connect(self.run) self.actionAbout.triggered.connect(self.about) def unload(self): self.iface.removePluginVectorMenu( self.tr('QScatter'), self.actionRun) self.iface.removePluginVectorMenu( self.tr('QScatter'), self.actionAbout) self.iface.removeVectorToolBarIcon(self.actionRun) def run(self): dlg = QScatterDialog(self.iface) dlg.show() dlg.exec_() def about(self): dlg = AboutDialog() dlg.exec_() def tr(self, text): return QCoreApplication.translate('QScatter', text)
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False): if actionText is None: if (QgsGui.higFlags() & QgsGui.HigMenuTextIsTitleCase) and not (alg.flags() & QgsProcessingAlgorithm.FlagDisplayNameIsLiteral): alg_title = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase) else: alg_title = alg.displayName() actionText = alg_title + QCoreApplication.translate('Processing', '…') action = QAction(icon or alg.icon(), actionText, iface.mainWindow()) alg_id = alg.id() action.setData(alg_id) action.triggered.connect(lambda: _executeAlgorithm(alg_id)) action.setObjectName("mProcessingUserMenu_%s" % alg_id) if menuName: menu = getMenu(menuName, iface.mainWindow().menuBar()) submenu = getMenu(submenuName, menu) submenu.addAction(action) if addButton: global algorithmsToolbar if algorithmsToolbar is None: algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms')) algorithmsToolbar.setObjectName("ProcessingAlgorithms") algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar')) algorithmsToolbar.addAction(action)
class QConsolidatePlugin: def __init__(self, iface): self.iface = iface locale = QgsApplication.locale() qmPath = '{}/i18n/qconsolidate_{}.qm'.format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) def initGui(self): self.actionRun = QAction(self.tr('QConsolidate'), self.iface.mainWindow()) self.actionRun.setIcon(QIcon(os.path.join(pluginPath, 'icons', 'qconsolidate.svg'))) self.actionRun.setObjectName('runQConsolidate') self.actionAbout = QAction(self.tr('About QConsolidate…'), self.iface.mainWindow()) self.actionAbout.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg')) self.actionRun.setObjectName('aboutQConsolidate') self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionRun) self.iface.addPluginToMenu(self.tr('QConsolidate'), self.actionAbout) self.iface.addToolBarIcon(self.actionRun) self.actionRun.triggered.connect(self.run) self.actionAbout.triggered.connect(self.about) self.taskManager = QgsApplication.taskManager() def unload(self): self.iface.removePluginMenu(self.tr('QConsolidate'), self.actionRun) self.iface.removePluginMenu(self.tr('QConsolidate'), self.actionAbout) self.iface.removeToolBarIcon(self.actionRun) def run(self): dlg = QConsolidateDialog() if dlg.exec_(): task = dlg.task() task.consolidateComplete.connect(self.completed) task.errorOccurred.connect(self.errored) self.taskManager.addTask(task) def about(self): d = AboutDialog() d.exec_() def tr(self, text): return QCoreApplication.translate('QConsolidate', text) def completed(self): self.iface.messageBar().pushSuccess(self.tr('QConsolidate'), self.tr('Project consolidated successfully.')) def errored(self, error): self.iface.messageBar().pushWarning(self.tr('QConsolidate'), error)
class DBManagerPlugin: def __init__(self, iface): self.iface = iface self.dlg = None def initGui(self): self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"), self.iface.mainWindow()) self.action.setObjectName("dbManager") self.action.triggered.connect(self.run) # Add toolbar button and menu item if hasattr(self.iface, 'addDatabaseToolBarIcon'): self.iface.addDatabaseToolBarIcon(self.action) else: self.iface.addToolBarIcon(self.action) if hasattr(self.iface, 'addPluginToDatabaseMenu'): self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) def unload(self): # Remove the plugin menu item and icon if hasattr(self.iface, 'removePluginDatabaseMenu'): self.iface.removePluginDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.removePluginMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) if hasattr(self.iface, 'removeDatabaseToolBarIcon'): self.iface.removeDatabaseToolBarIcon(self.action) else: self.iface.removeToolBarIcon(self.action) if self.dlg is not None: self.dlg.close() def run(self): # keep opened only one instance if self.dlg is None: from .db_manager import DBManager self.dlg = DBManager(self.iface) self.dlg.destroyed.connect(self.onDestroyed) self.dlg.show() self.dlg.raise_() self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized) self.dlg.activateWindow() def onDestroyed(self, obj): self.dlg = None
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False): action = QAction(icon or alg.icon(), actionText or alg.displayName(), iface.mainWindow()) action.triggered.connect(lambda: _executeAlgorithm(alg)) action.setObjectName("mProcessingUserMenu_%s" % alg.id()) if menuName: menu = getMenu(menuName, iface.mainWindow().menuBar()) submenu = getMenu(submenuName, menu) submenu.addAction(action) if addButton: global algorithmsToolbar if algorithmsToolbar is None: algorithmsToolbar = iface.addToolBar('ProcessingAlgorithms') algorithmsToolbar.addAction(action)
class OAWPlugin: def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.toolbar = self.iface.addToolBar(CODE + ' Toolbar') self.toolbar.setObjectName('oaw_toolbar') self.help_action = None self.dialog = None self.executor = Executor.GET_INSTANCE() self.scheduler = Scheduler.GET_INSTANCE() def initGui(self): self.dialog = PanelWidget(self.iface, self.iface.mainWindow()) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dialog) self.dialog.hide() self.executor.on_slots_changed += self.dialog.widget_new.on_slots_changed self.dialog.widget_settings.on_changed += self.executor.on_settings_changed self.dialog.widget_settings.init_widget() # Help icon = QIcon(os.path.dirname(__file__) + '/images/help-icon.png') self.help_action = QAction(icon, "Help", self.iface.mainWindow()) self.help_action.setObjectName('oaw_help') self.help_action.triggered.connect(self.help) self.iface.addPluginToMenu(CODE, self.help_action) def unload(self): self.iface.removePluginMenu(CODE, self.help_action) self.iface.removeDockWidget(self.dialog) del self.toolbar self.dialog = None def help(self): """ Display a help page :return: """ self.show_dialog() url = QUrl.fromLocalFile(os.path.dirname(__file__) + "/index.html").toString() webbrowser.open(url, new=2) def show_dialog(self): """ Show the plugin docked widget. """ self.dialog.show()
def cancelform(self, *args, **kwargs): showDialog = kwargs.get("showDialog", False) if showDialog: dlg = PickActionDialog(msg="Discard form changes?") self.expandAction = QAction(QIcon(":/icons/expand"), "Expand Panel", self) discardaction = QAction("Discard", self, triggered=self._cancel_form) discardaction.setObjectName("discard") noaction = QAction("No", self) dlg.addactions([noaction, discardaction]) dlg.exec_() else: self._cancel_form(*args)
def create_action(action_name, action_group, icon_num=None, text=None): """ Creates a new action with selected parameters """ icon = None icon_folder = global_vars.plugin_dir + '/icons/' icon_path = icon_folder + icon_num + '.png' if os.path.exists(icon_path): icon = QIcon(icon_path) if icon is None: action = QAction(text, action_group) else: action = QAction(icon, text, action_group) action.setObjectName(action_name) return action
class GeocatBridge: def __init__(self, iface): self.iface = iface readServers() self.provider = BridgeProvider() self.pluginFolder = os.path.dirname(__file__) localePath = "" self.locale = QSettings().value("locale/userLocale")[0:2] if os.path.exists(self.pluginFolder): localePath = os.path.join(self.pluginFolder, "i18n", "bridge_" + self.locale + ".qm") self.translator = QTranslator() if os.path.exists(localePath): self.translator.load(localePath) QCoreApplication.installTranslator(self.translator) def initGui(self): iconPublish = QIcon( os.path.join(os.path.dirname(__file__), "icons", "publish_button.png")) self.actionPublish = QAction( iconPublish, QCoreApplication.translate("GeocatBridge", "Publish"), self.iface.mainWindow()) self.actionPublish.setObjectName("startPublish") self.actionPublish.triggered.connect(self.publishClicked) self.iface.addPluginToWebMenu("GeoCatBridge", self.actionPublish) self.iface.addWebToolBarIcon(self.actionPublish) QgsApplication.processingRegistry().addProvider(self.provider) def unload(self): removeTempFolder() self.iface.removePluginWebMenu("GeoCatBridge", self.actionPublish) self.iface.removeWebToolBarIcon(self.actionPublish) QgsApplication.processingRegistry().removeProvider(self.provider) def publishClicked(self): dialog = BridgeDialog(self.iface.mainWindow()) dialog.exec_()
class StatistPlugin: def __init__(self, iface): self.iface = iface locale = QgsApplication.locale() qmPath = "{}/i18n/statist_{}.qm".format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) def initGui(self): self.actionRun = QAction(self.tr("Statist"), self.iface.mainWindow()) self.actionRun.setIcon(QIcon(os.path.join(pluginPath, "icons", "statist.png"))) self.actionRun.setObjectName("runStatist") self.iface.registerMainWindowAction(self.actionRun, "Shift+S") self.actionAbout = QAction(self.tr("About Statist…"), self.iface.mainWindow()) self.actionAbout.setIcon(QgsApplication.getThemeIcon("/mActionHelpContents.svg")) self.actionRun.setObjectName("aboutStatist") self.iface.addPluginToVectorMenu(self.tr("Statist"), self.actionRun) self.iface.addPluginToVectorMenu(self.tr("Statist"), self.actionAbout) self.iface.addVectorToolBarIcon(self.actionRun) self.actionRun.triggered.connect(self.run) self.actionAbout.triggered.connect(self.about) def unload(self): self.iface.unregisterMainWindowAction(self.actionRun) self.iface.removePluginVectorMenu(self.tr("Statist"), self.actionRun) self.iface.removePluginVectorMenu(self.tr("Statist"), self.actionAbout) self.iface.removeVectorToolBarIcon(self.actionRun) def run(self): dlg = StatistDialog() dlg.show() dlg.exec_() def about(self): d = AboutDialog() d.exec_() def tr(self, text): return QCoreApplication.translate("Statist", text)
def _build_add_service_menu(self, widget): menu = QMenu() save_action = QAction(self.tr('Save Current Configuration As…'), parent=menu) save_action.setObjectName('save_action') menu.addAction(save_action) save_action.triggered.connect(self._save_configuration) import_action = QAction(self.tr('Import from File…'), parent=menu) menu.addAction(import_action) import_action.triggered.connect(self._import_configuration) create_new_action = QAction(self.tr('Create New Service…'), parent=menu) menu.addAction(create_new_action) create_new_action.triggered.connect(self._create_configuration) menu.aboutToShow.connect(lambda: self._menu_about_to_show(menu)) widget.setMenu(menu)
def addAboutMenu(menuName, parentMenuFunction=None): ''' Adds an 'about...' menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added ''' parentMenuFunction = parentMenuFunction or iface.addPluginToMenu namespace = _callerName().split(".")[0] aboutAction = QAction( QgsApplication.getThemeIcon('/mActionHelpContents.svg'), "About...", iface.mainWindow()) aboutAction.setObjectName(namespace + "about") aboutAction.triggered.connect(lambda: openAboutDialog(namespace)) parentMenuFunction(menuName, aboutAction) global _aboutActions _aboutActions[menuName] = aboutAction
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False): if actionText is None: actionText = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase) + QCoreApplication.translate('Processing', '…') action = QAction(icon or alg.icon(), actionText, iface.mainWindow()) action.setData(alg.id()) action.triggered.connect(lambda: _executeAlgorithm(alg)) action.setObjectName("mProcessingUserMenu_%s" % alg.id()) if menuName: menu = getMenu(menuName, iface.mainWindow().menuBar()) submenu = getMenu(submenuName, menu) submenu.addAction(action) if addButton: global algorithmsToolbar if algorithmsToolbar is None: algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms')) algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar')) algorithmsToolbar.addAction(action)
def addSettingsMenu(menuName, parentMenuFunction=None): ''' Adds a 'open settings...' menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the settings menu is to be added :param parentMenuFunction: a function from QgisInterface to indicate where to put the container plugin menu. If not passed, it uses addPluginToMenu ''' parentMenuFunction = parentMenuFunction or iface.addPluginToMenu namespace = _callerName().split(".")[0] settingsAction = QAction( QgsApplication.getThemeIcon('/mActionOptions.svg'), "Plugin Settings...", iface.mainWindow()) settingsAction.setObjectName(namespace + "settings") settingsAction.triggered.connect(lambda: openSettingsDialog(namespace)) parentMenuFunction(menuName, settingsAction) global _settingActions _settingActions[menuName] = settingsAction
def addHelpMenu(menuName, parentMenuFunction=None): ''' Adds a help menu to the plugin menu. This method should be called from the initGui() method of the plugin :param menuName: The name of the plugin menu in which the about menu is to be added. ''' parentMenuFunction = parentMenuFunction or iface.addPluginToMenu namespace = _callerName().split(".")[0] path = "file://{}".format( os.path.join(os.path.dirname(_callerPath()), "docs", "html", "index.html")) helpAction = QAction(QgsApplication.getThemeIcon('/mActionHelpAPI.png'), "Plugin help...", iface.mainWindow()) helpAction.setObjectName(namespace + "help") helpAction.triggered.connect(lambda: openHelp(path)) parentMenuFunction(menuName, helpAction) global _helpActions _helpActions[menuName] = helpAction
class HeightmapExport(object): """Implement a QGIS Plugin.""" def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # Declare instance attributes self.action = None self.menu = '&Heightmap Export' self.window = True def initGui(self): """Create the menu entries and a toolbar icon in the QGIS GUI.""" icon = QIcon(":/plugins/HeightmapExport/HeightmapExport.png") parent = self.iface.mainWindow() self.action = QAction(icon, "Heightmap Export", parent) self.action.setObjectName("Heightmap Export") self.action.setStatusTip("Export 16-bit PNG heightmaps") self.action.triggered.connect(self.run) self.iface.addPluginToRasterMenu(self.menu, self.action) self.iface.addRasterToolBarIcon(self.action) def unload(self): """Remove the plugin menu entry and icon from QGIS GUI.""" self.iface.removePluginRasterMenu(self.menu, self.action) self.iface.removeRasterToolBarIcon(self.action) def run(self): """Run the plugin.""" hmexport = HeightmapExportDialog(self.iface) hmexport.exec_() if hmexport.extent: self.iface.mapCanvas().scene().removeItem(hmexport.extent)
def addAlgorithmEntry(alg, menuName, submenuName, object_name, actionText=None, icon=None, addButton=False): if actionText is None: if (QgsGui.higFlags() & QgsGui.HigMenuTextIsTitleCase) and not ( alg.flags() & QgsProcessingAlgorithm.FlagDisplayNameIsLiteral): alg_title = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase) else: alg_title = alg.displayName() actionText = alg_title + QCoreApplication.translate('Processing', '…') action = QAction(icon or alg.icon(), actionText, iface.mainWindow()) alg_id = alg.id() action.setData(alg_id) action.triggered.connect(lambda: _executeAlgorithm(alg_id)) action.setObjectName("mProcessingUserMenu_%s" % alg_id) if menuName: menu = getMenu(menuName, iface.mainWindow().menuBar()) submenu = getMenu(submenuName, menu) submenu.setObjectName(object_name) submenu.addAction(action) if addButton: global algorithmsToolbar if algorithmsToolbar is None: algorithmsToolbar = iface.addToolBar( QCoreApplication.translate('MainWindow', 'Processing Algorithms')) algorithmsToolbar.setObjectName("ProcessingAlgorithms") algorithmsToolbar.setToolTip( QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar')) algorithmsToolbar.addAction(action)
def _fill_arc_menu(self): """ Fill add arc menu """ # disconnect and remove previuos signals and actions actions = self.menu.actions() for action in actions: action.disconnect() self.menu.removeAction(action) del action action_group = self.action.property('action_group') # Update featurecatvalues global_vars.feature_cat = tools_gw.manage_feature_cat() # Get list of different arc types features_cat = global_vars.feature_cat if features_cat is not None: list_feature_cat = tools_os.get_values_from_dictionary( features_cat) for feature_cat in list_feature_cat: if feature_cat.feature_type.upper() == 'ARC': obj_action = QAction(str(feature_cat.id), action_group) obj_action.setObjectName(feature_cat.id) obj_action.setProperty('action_group', action_group) if f"{feature_cat.shortcut_key}" not in global_vars.shortcut_keys: obj_action.setShortcut( QKeySequence(str(feature_cat.shortcut_key))) try: obj_action.setShortcutVisibleInContextMenu(True) except Exception: pass self.menu.addAction(obj_action) obj_action.triggered.connect( partial(self.info_feature.add_feature, feature_cat)) obj_action.triggered.connect( partial(self._save_last_selection, self.menu, feature_cat))
class RiverGISPlugin(object): def __init__(self, iface): self.iface = iface self.dlg = None def initGui(self): rg_icon = QIcon(icon_path('rivergis.svg')) self.action = QAction(rg_icon, 'RiverGIS', self.iface.mainWindow()) self.action.setObjectName('rivergis') self.action.triggered.connect(self.run) # Add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu( QApplication.translate('RiverGIS', 'RiverGIS'), self.action) def unload(self): # Remove the plugin menu item and icon self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu( QApplication.translate('RiverGIS', 'RiverGIS'), self.action) if self.dlg is not None: self.dlg.close() def run(self): # keep opened only one instance if self.dlg is None: from .rivergis import RiverGIS self.dlg = RiverGIS(self.iface) self.dlg.destroyed.connect(self.onDestroyed) self.dlg.show() self.dlg.raise_() self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized) self.dlg.activateWindow() def onDestroyed(self, obj): self.dlg = None
def do_init_defects_menu(self): """Inititializes the defects menu: - load defects - import defects - export defects Import and Export defects use some external python excel library. xlsxwriter, openpyxl """ menubar = self.toolbar.findChild(QMenuBar, 'VeriSO.Main.LoadDefectsMenuBar') menu = menubar.findChild(QMenu, 'VeriSO.Main.LoadDefectsMenu') menu.setTitle(_translate(self.module, "Defects", None)) action = QAction(_translate(self.module, "Load defects layer", None), self.iface.mainWindow()) action.setObjectName("VeriSOModule.LoadDefectsAction") action.triggered.connect(self.do_load_defects_wrapper) menu.addAction(action) action = QAction( QCoreApplication.translate(self.module, "Import defects layer"), self.iface.mainWindow()) action.setObjectName("VeriSOModule.ImportDefectsAction") action.triggered.connect(self.do_import_defects) menu.addAction(action) action = QAction( QCoreApplication.translate(self.module, "Export defects layer .xlsx"), self.iface.mainWindow()) action.setObjectName("VeriSOModule.ExportDefectsAction") action.triggered.connect(self.do_export_defects) menu.addAction(action) action = QAction( QCoreApplication.translate(self.module, "Export defects layer .shp"), self.iface.mainWindow()) action.setObjectName("VeriSOModule.ExportDefectsShpAction") action.triggered.connect(self.do_export_defects_shp) menu.addAction(action) menubar.addMenu(menu) self.toolbar.insertWidget(self.beforeAction, menubar)
class RasterTransparencyPlugin: def __init__(self, iface): self.iface = iface locale = QgsApplication.locale() qmPath = "{}/i18n/rastertransparency_{}.qm".format(pluginPath, locale) if os.path.exists(qmPath): self.translator = QTranslator() self.translator.load(qmPath) QCoreApplication.installTranslator(self.translator) self.factory = TransparencyPanelFactory() def initGui(self): self.actionAbout = QAction(self.tr("About RasterTransparency…"), self.iface.mainWindow()) self.actionAbout.setIcon(QgsApplication.getThemeIcon("/mActionHelpContents.svg")) self.actionAbout.setObjectName("aboutRasterTransparency") self.actionAbout.triggered.connect(self.about) self.iface.addPluginToRasterMenu(self.tr("Raster transparency"), self.actionAbout) self.iface.registerMapLayerConfigWidgetFactory(self.factory) def unload(self): self.iface.removePluginRasterMenu(self.tr("Raster transparency"), self.actionAbout) self.iface.unregisterMapLayerConfigWidgetFactory(self.factory) def about(self): d = AboutDialog() d.exec_() def tr(self, text): return QCoreApplication.translate("RasterTransparency", text)
class SearchLayers: def __init__(self, iface): self.iface = iface self.searchDialog = None def initGui(self): # Create the menu items in the Plugin menu and attach the icon to the toolbar icon = QIcon(os.path.dirname(__file__) + "/icon.png") self.searchAction = QAction(icon, "Search Layers", self.iface.mainWindow()) self.searchAction.setObjectName('searchLayers') self.searchAction.triggered.connect(self.showSearchDialog) self.iface.addToolBarIcon(self.searchAction) self.iface.addPluginToMenu("Search Layers", self.searchAction) # Help icon = QIcon(os.path.dirname(__file__) + '/help.png') self.helpAction = QAction(icon, "Help", self.iface.mainWindow()) self.helpAction.setObjectName('searchLayersHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToMenu('Search Layers', self.helpAction) def unload(self): self.iface.removePluginMenu('Search Layers', self.searchAction) self.iface.removePluginMenu('Search Layers', self.helpAction) self.iface.removeToolBarIcon(self.searchAction) def showSearchDialog(self): if self.searchDialog is None: # All the work is done in the LayerSearchDialog self.searchDialog = LayerSearchDialog(self.iface, self.iface.mainWindow()) self.searchDialog.show() def help(self): '''Display a help page''' url = QUrl.fromLocalFile(os.path.dirname(__file__) + "/index.html").toString() webbrowser.open(url, new=2)
class GeocatBridge: def __init__(self, iface): self.iface = iface self._win = iface.mainWindow() self.main_dialog = None self.action_publish = None self.action_help = None self.action_styleviewer = None self.widget_styleviewer = StyleviewerWidget() self.widget_styleviewer.hideEvent = partial(self.styleviewerHidden) self.widget_styleviewer.showEvent = partial(self.styleviewerShown) self._layerSignals = LayerStyleEventManager() # Load server configuration from QSettings manager.loadConfiguredServers() self.name = meta.getAppName() self.provider = None self.locale = QSettings().value("locale/userLocale")[0:2] locale_path = files.getLocalePath(f"bridge_{self.locale}") self.translator = QTranslator() if os.path.exists(locale_path): self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) self.qgis_hook = sys.excepthook def plugin_hook(t, value, tb): """ Exception handling (catch all) """ error_list = traceback.format_exception(t, value, tb) trace = "".join(error_list) if meta.PLUGIN_NAMESPACE in trace.lower(): try: # Show error report dialog handleError(error_list) except Exception as err: # Swallow all exceptions here, to avoid entering an endless loop feedback.logWarning( f"A failure occurred while handling an exception: {err}" ) # TODO: Once Bridge is more mature, the code below should be uncommented # try: # # Close/disable the plugin to avoid messing up things # self.unload() # except Exception as err: # feedback.logWarning(f"A failure occurred while unloading the Bridge plugin: {err}") else: # Handle regular QGIS exception self.qgis_hook(t, value, tb) sys.excepthook = plugin_hook @staticmethod def openDocUrl(): """ Opens the web-based documentation in a new tab of the default browser. """ full_url = f"{meta.getDocsUrl()}/v{meta.getVersion()}/" webbrowser.open_new_tab(full_url) def initProcessing(self): """ Initializes and adds a processing provider. """ self.provider = BridgeProvider() QgsApplication.processingRegistry().addProvider(self.provider) # noqa def initGui(self): self.initProcessing() # Publish / main dialog menu item + toolbar button self.action_publish = QAction( QIcon(files.getIconPath("publish_button")), QCoreApplication.translate(self.name, "Publish"), self._win) self.action_publish.setObjectName("startPublish") self.action_publish.triggered.connect(self.bridgeButtonClicked) self.iface.addPluginToWebMenu(self.name, self.action_publish) self.iface.addWebToolBarIcon(self.action_publish) # Register dockable StyleViewer widget (also registers to View > Panels) but keep hidden self.iface.addDockWidget(Qt.RightDockWidgetArea, self.widget_styleviewer) self.widget_styleviewer.hide() # StyleViewer menu item self.action_styleviewer = QAction( QIcon(files.getIconPath("symbology")), QCoreApplication.translate(self.name, "StyleViewer"), self._win) self.action_styleviewer.setObjectName("StyleViewer") self.action_styleviewer.triggered.connect(self.widget_styleviewer.show) self.iface.addPluginToWebMenu(self.name, self.action_styleviewer) # Help menu item self.action_help = QAction( QgsApplication.getThemeIcon('/mActionHelpContents.svg'), "Plugin Help...", self._win) self.action_help.setObjectName(f"{self.name} Help") self.action_help.triggered.connect(self.openDocUrl) self.iface.addPluginToWebMenu(self.name, self.action_help) # Add layer event handlers QgsProject().instance().layersAdded.connect(self.layersAdded) QgsProject().instance().layersWillBeRemoved.connect( self.layersWillBeRemoved) def unload(self): files.removeTempFolder() # Remove layer event handlers try: QgsProject().instance().layersAdded.disconnect(self.layersAdded) QgsProject().instance().layersWillBeRemoved.disconnect( self.layersWillBeRemoved) except TypeError: # Event handlers were never connected in the first place: # initGui() was probably never called, so abort the unload method if self.qgis_hook and self.qgis_hook != sys.excepthook: sys.excepthook = self.qgis_hook return self._layerSignals.clear() # Remove StyleViewer button and close StyleViewer self.action_styleviewer.triggered.disconnect( self.widget_styleviewer.show) self.iface.removePluginWebMenu(self.name, self.action_styleviewer) self.closeDialog(self.widget_styleviewer) # Remove Publish button and close Publish dialog self.action_publish.triggered.disconnect(self.bridgeButtonClicked) self.iface.removePluginWebMenu(self.name, self.action_publish) self.iface.removeWebToolBarIcon(self.action_publish) self.closeDialog(self.main_dialog) # Remove Help button self.iface.removePluginWebMenu(self.name, self.action_help) # Remove processing provider QgsApplication.processingRegistry().removeProvider( self.provider) # noqa sys.excepthook = self.qgis_hook def layersAdded(self, layers): for lyr in layers: self._layerSignals.connect(lyr, self.widget_styleviewer.updateLayer) def layersWillBeRemoved(self, layer_ids): layer_ids = frozenset(layer_ids) for lyr_id in layer_ids: self._layerSignals.disconnect(lyr_id) def bridgeButtonClicked(self): """ Opens the Bridge Publish dialog. This will always create a new BridgeDialog instance.""" # Since the BridgeDialog is a modal window, the Bridge button cannot be clicked if the dialog is open. # Therefore, we don't need to check if there is a current (open) dialog or not. self.closeDialog(self.main_dialog) self.main_dialog = BridgeDialog(self.iface.mainWindow()) self.main_dialog.show() def styleviewerHidden(self, event: QHideEvent): """ Detaches the 'currentLayerChanged' event handler from the StyleViewer widget if it is hidden. """ if self.iface and self.widget_styleviewer: try: self.iface.currentLayerChanged.disconnect( self.widget_styleviewer.updateForCurrentLayer) except TypeError: # currentLayerChanged was never connected pass event.accept() def styleviewerShown(self, event: QShowEvent): """ Attaches the 'currentLayerChanged' event handler to the StyleViewer widget if it is shown. Also calls 'updateForCurrentLayer' to make sure that the initial view is refreshed. """ if self.iface and self.widget_styleviewer: self.iface.currentLayerChanged.connect( self.widget_styleviewer.updateForCurrentLayer) self.widget_styleviewer.updateForCurrentLayer() event.accept() @staticmethod def closeDialog(dialog: QWidget): """ Closes (hides) and destroys the given dialog. """ if dialog is None: return None dialog.hide() dialog.destroy()
def addMenus(self): if self.profilesMenu is not None: self.profilesMenu.clear() self.actions = defaultdict(list) settings = QSettings() defaultProfile = settings.value('profilesplugin/LastProfile', 'Default', str) autoLoad = settings.value('profilesplugin/AutoLoad', False, bool) for k, v in profiles.items(): action = QAction(k, self.iface.mainWindow()) action.setCheckable(True) if k == defaultProfile and autoLoad: action.setChecked(True) action.triggered.connect(lambda _, menuName=k: self.applyProfile(menuName)) action.setObjectName('mProfilesPlugin_' + k) self.actions[v.group].append(action) actions = self.iface.mainWindow().menuBar().actions() settingsMenu = None self.profilesGroup = QActionGroup(self.iface.mainWindow()) if self.profilesMenu is None: for action in actions: if action.menu().objectName() == 'mSettingsMenu': settingsMenu = action.menu() self.profilesMenu = QMenu(settingsMenu) self.profilesMenu.setObjectName('mProfilesPlugin') self.profilesMenu.setTitle(self.tr('Profiles')) settingsMenu.addMenu(self.profilesMenu) break if self.profilesMenu is not None: for k,v in self.actions.items(): submenu = QMenu(self.profilesMenu) submenu.setObjectName('mProfilesPlugin_submenu_' + k) submenu.setTitle(k) for action in v: self.profilesGroup.addAction(action) submenu.addAction(action) self.profilesMenu.addMenu(submenu) self.profilesMenu.addSeparator() settings = QSettings() def _setAutoLoad(): settings.setValue('profilesplugin/AutoLoad', self.autoloadAction.isChecked()) self.autoloadAction = QAction(self.tr('Auto-load last profile on QGIS start'), iface.mainWindow()) self.autoloadAction.setCheckable(True) autoLoad = settings.value('profilesplugin/AutoLoad', False, bool) self.autoloadAction.setChecked(autoLoad) self.autoloadAction.setObjectName('mProfilesPluginAutoLoad') self.autoloadAction.triggered.connect(_setAutoLoad) self.profilesMenu.addAction(self.autoloadAction) self.saveProfileAction = QAction(self.tr('Profiles manager...'), self.iface.mainWindow()) self.saveProfileAction.setObjectName('mProfilesPluginProfilesManager') self.saveProfileAction.triggered.connect(self.saveProfile) self.profilesMenu.addAction(self.saveProfileAction) self.showHelpAction = QAction(self.tr('Help'), self.iface.mainWindow()) self.showHelpAction.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg')) self.showHelpAction.setObjectName('mProfilesPluginShowHelp') self.showHelpAction.triggered.connect(self.showHelp) self.profilesMenu.addAction(self.showHelpAction)
class ProcessingPlugin: def __init__(self, iface): self.iface = iface self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider(self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) Processing.initialize() def initGui(self): self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction(self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction(self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', 'Graphical &Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, QKeySequence('Ctrl+Alt+M').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QgsApplication.getThemeIcon("/mIconHistory.svg"), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction(self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect(self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() def openProcessingOptions(self): self.iface.showOptionsDialog(self.iface.mainWindow(), currentPage='processingOptions') def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.iface.attributesToolBar().removeAction(self.toolboxAction) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.toolbox.deleteLater() self.menu.deleteLater() # delete temporary output files folder = QgsProcessingUtils.tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) # also delete temporary help files folder = tempHelpFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) self.iface.deregisterLocatorFilter(self.locator_filter) self.iface.unregisterCustomDropHandler(self.drop_handler) QgsApplication.dataItemProviderRegistry().removeProvider(self.item_provider) removeMenus() Processing.deinitialize() def openToolbox(self, show): self.toolbox.setUserVisible(show) def toolboxVisibilityChanged(self, visible): self.toolboxAction.setChecked(visible) def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById('model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class ProcessingPlugin: def __init__(self, iface): self.iface = iface Processing.initialize() def initGui(self): self.commander = None self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = self.toolbox.toggleViewAction() self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QIcon(os.path.join(cmd_folder, 'images', 'alg.png'))) self.toolboxAction.setText(self.tr('&Toolbox')) self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T') self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'model.png')), self.tr('Graphical &Modeler...'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M') self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'history.gif')), self.tr('&History...'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H') self.menu.addAction(self.historyAction) self.configAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'config.png')), self.tr('&Options...'), self.iface.mainWindow()) self.configAction.setObjectName('configAction') self.configAction.triggered.connect(self.openConfig) self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C') self.menu.addAction(self.configAction) self.resultsAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'results.png')), self.tr('&Results Viewer...'), self.iface.mainWindow()) self.resultsAction.setObjectName('resultsAction') self.resultsAction.triggered.connect(self.openResults) self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R') self.menu.addAction(self.resultsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.commanderAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'commander.png')), self.tr('&Commander'), self.iface.mainWindow()) self.commanderAction.setObjectName('commanderAction') self.commanderAction.triggered.connect(self.openCommander) self.menu.addAction(self.commanderAction) self.iface.registerMainWindowAction(self.commanderAction, self.tr('Ctrl+Alt+D')) initializeMenus() createMenus() def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.menu.deleteLater() # delete temporary output files folder = tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.configAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterMainWindowAction(self.commanderAction) removeMenus() def openCommander(self): if self.commander is None: self.commander = CommanderWindow( self.iface.mainWindow(), self.iface.mapCanvas()) self.commander.prepareGui() self.commander.show() def openToolbox(self): if self.toolbox.isVisible(): self.toolbox.hide() else: self.toolbox.show() def openModeler(self): dlg = ModelerDialog() dlg.exec_() if dlg.update: algList.reloadProvider('model') def openResults(self): dlg = ResultsDialog() dlg.show() dlg.exec_() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def openConfig(self): dlg = ConfigDialog(self.toolbox) dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class ProcessingPlugin(object): def __init__(self, iface): self.iface = iface self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) Processing.initialize() def initGui(self): self.commander = None self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() resultsList.resultAdded.connect(self.resultsDock.fillTree) self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = self.toolbox.toggleViewAction() self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.toolboxAction.setText(self.tr('&Toolbox')) self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T') self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), self.tr('Graphical &Modeler...'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M') self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'history.svg')), self.tr('&History...'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H') self.menu.addAction(self.historyAction) self.resultsAction = self.resultsDock.toggleViewAction() self.resultsAction.setObjectName('resultsAction') self.resultsAction.setIcon( QgsApplication.getThemeIcon("/processingResult.svg")) self.resultsAction.setText(self.tr('&Results Viewer')) self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R') self.menu.addAction(self.resultsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.commanderAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'commander.svg')), self.tr('&Commander'), self.iface.mainWindow()) self.commanderAction.setObjectName('commanderAction') self.commanderAction.triggered.connect(self.openCommander) self.menu.addAction(self.commanderAction) self.iface.registerMainWindowAction(self.commanderAction, self.tr('Ctrl+Alt+D')) self.menu.addSeparator() initializeMenus() createMenus() def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.menu.deleteLater() # delete temporary output files folder = tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterMainWindowAction(self.commanderAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) removeMenus() Processing.deinitialize() def openCommander(self): if self.commander is None: self.commander = CommanderWindow( self.iface.mainWindow(), self.iface.mapCanvas()) self.commander.prepareGui() self.commander.show() def openToolbox(self): if self.toolbox.isVisible(): self.toolbox.hide() else: self.toolbox.show() def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById('model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class ProcessingPlugin: def __init__(self, iface): self.iface = iface self.options_factory = None self.drop_handler = None self.item_provider = None self.locator_filter = None self.edit_features_locator_filter = None self.initialized = False self.initProcessing() def initProcessing(self): if not self.initialized: self.initialized = True Processing.initialize() def initGui(self): self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider(self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) # Invalidate the locator filter for in-place when active layer changes iface.currentLayerChanged.connect(lambda _: self.iface.invalidateLocatorResults()) self.edit_features_locator_filter = InPlaceAlgorithmLocatorFilter() iface.registerLocatorFilter(self.edit_features_locator_filter) self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction(self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction(self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', 'Graphical &Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, QKeySequence('Ctrl+Alt+M').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QgsApplication.getThemeIcon("/mIconHistory.svg"), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction(self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect(self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.toolbox.processingToolbar.addSeparator() self.editInPlaceAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Features In-Place'), self.iface.mainWindow()) self.editInPlaceAction.setObjectName('editInPlaceFeatures') self.editInPlaceAction.setCheckable(True) self.editInPlaceAction.toggled.connect(self.editSelected) self.menu.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addSeparator() self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() # In-place editing button state sync self.iface.currentLayerChanged.connect(self.sync_in_place_button_state) self.iface.mapCanvas().selectionChanged.connect(self.sync_in_place_button_state) self.iface.actionToggleEditing().triggered.connect(partial(self.sync_in_place_button_state, None)) self.sync_in_place_button_state() def sync_in_place_button_state(self, layer=None): """Synchronise the button state with layer state""" if layer is None: layer = self.iface.activeLayer() old_enabled_state = self.editInPlaceAction.isEnabled() new_enabled_state = layer is not None and layer.type() == QgsMapLayerType.VectorLayer self.editInPlaceAction.setEnabled(new_enabled_state) if new_enabled_state != old_enabled_state: self.toolbox.set_in_place_edit_mode(new_enabled_state and self.editInPlaceAction.isChecked()) def openProcessingOptions(self): self.iface.showOptionsDialog(self.iface.mainWindow(), currentPage='processingOptions') def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.iface.attributesToolBar().removeAction(self.toolboxAction) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.toolbox.deleteLater() self.menu.deleteLater() # delete temporary output files folder = QgsProcessingUtils.tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) # also delete temporary help files folder = tempHelpFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) self.iface.deregisterLocatorFilter(self.locator_filter) self.iface.deregisterLocatorFilter(self.edit_features_locator_filter) self.iface.unregisterCustomDropHandler(self.drop_handler) QgsApplication.dataItemProviderRegistry().removeProvider(self.item_provider) removeMenus() Processing.deinitialize() def openToolbox(self, show): self.toolbox.setUserVisible(show) def toolboxVisibilityChanged(self, visible): self.toolboxAction.setChecked(visible) def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById('model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message) def editSelected(self, enabled): self.toolbox.set_in_place_edit_mode(enabled)
class DBManagerPlugin(object): def __init__(self, iface): self.iface = iface self.dlg = None def initGui(self): self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"), self.iface.mainWindow()) self.action.setObjectName("dbManager") self.action.triggered.connect(self.run) # Add toolbar button and menu item if hasattr(self.iface, 'addDatabaseToolBarIcon'): self.iface.addDatabaseToolBarIcon(self.action) else: self.iface.addToolBarIcon(self.action) if hasattr(self.iface, 'addPluginToDatabaseMenu'): self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) self.layerAction = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "Update Sql Layer"), self.iface.mainWindow()) self.layerAction.setObjectName("dbManagerUpdateSqlLayer") self.layerAction.triggered.connect(self.onUpdateSqlLayer) self.iface.addCustomActionForLayerType(self.layerAction, "", QgsMapLayer.VectorLayer, False) for l in list(QgsProject.instance().mapLayers().values()): self.onLayerWasAdded(l) QgsProject.instance().layerWasAdded.connect(self.onLayerWasAdded) def unload(self): # Remove the plugin menu item and icon if hasattr(self.iface, 'removePluginDatabaseMenu'): self.iface.removePluginDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.removePluginMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) if hasattr(self.iface, 'removeDatabaseToolBarIcon'): self.iface.removeDatabaseToolBarIcon(self.action) else: self.iface.removeToolBarIcon(self.action) self.iface.removeCustomActionForLayerType(self.layerAction) QgsProject.instance().layerWasAdded.disconnect(self.onLayerWasAdded) if self.dlg is not None: self.dlg.close() def onLayerWasAdded(self, aMapLayer): if hasattr(aMapLayer, 'dataProvider') and aMapLayer.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: uri = QgsDataSourceUri(aMapLayer.source()) table = uri.table() if table.startswith('(') and table.endswith(')'): self.addCustomActionForLayer(self.layerAction, aMapLayer) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') # url.queryItemValue('uid') # url.queryItemValue('geometry') def onUpdateSqlLayer(self): l = self.iface.activeLayer() if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: table = QgsDataSourceUri(l.source()).table() if table.startswith('(') and table.endswith(')'): self.run() self.dlg.runSqlLayerWindow(l) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') # url.queryItemValue('uid') # url.queryItemValue('geometry') def run(self): # keep opened only one instance if self.dlg is None: from .db_manager import DBManager self.dlg = DBManager(self.iface) self.dlg.destroyed.connect(self.onDestroyed) self.dlg.show() self.dlg.raise_() self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized) self.dlg.activateWindow() def onDestroyed(self, obj): self.dlg = None
class DBManagerPlugin(object): def __init__(self, iface): self.iface = iface self.dlg = None def initGui(self): self.action = QAction( QgsApplication.getThemeIcon('dbmanager.svg'), QApplication.translate("DBManagerPlugin", "DB Manager…"), self.iface.mainWindow()) self.action.setObjectName("dbManager") self.action.triggered.connect(self.run) # Add toolbar button and menu item if hasattr(self.iface, 'addDatabaseToolBarIcon'): self.iface.addDatabaseToolBarIcon(self.action) else: self.iface.addToolBarIcon(self.action) if hasattr(self.iface, 'addPluginToDatabaseMenu'): self.iface.addPluginToDatabaseMenu( QApplication.translate("DBManagerPlugin", None), self.action) else: self.iface.addPluginToMenu( QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) def unload(self): # Remove the plugin menu item and icon if hasattr(self.iface, 'databaseMenu'): self.iface.databaseMenu().removeAction(self.action) else: self.iface.removePluginMenu( QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) if hasattr(self.iface, 'removeDatabaseToolBarIcon'): self.iface.removeDatabaseToolBarIcon(self.action) else: self.iface.removeToolBarIcon(self.action) if self.dlg is not None: self.dlg.close() def onUpdateSqlLayer(self): # Be able to update every Db layer from Postgres, Spatialite and Oracle l = self.iface.activeLayer() if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: self.run() self.dlg.runSqlLayerWindow(l) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') # url.queryItemValue('uid') # url.queryItemValue('geometry') def run(self): # keep opened only one instance if self.dlg is None: from .db_manager import DBManager self.dlg = DBManager(self.iface) self.dlg.destroyed.connect(self.onDestroyed) self.dlg.show() self.dlg.raise_() self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized) self.dlg.activateWindow() def onDestroyed(self, obj): self.dlg = None
class GdalTools: def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = [] def initGui(self): if not valid: return if int(self.QgisVersion) < 1: QMessageBox.warning( self.iface.getMainWindow(), "Gdal Tools", QCoreApplication.translate("GdalTools", "QGIS version detected: ") + unicode(self.QgisVersion) + ".xx\n" + QCoreApplication.translate("GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled.")) return None from .tools.GdalTools_utils import GdalConfig, LayerRegistry self.GdalVersionNum = GdalConfig.versionNum() LayerRegistry.setIface(self.iface) # find the Raster menu rasterMenu = None menu_bar = self.iface.mainWindow().menuBar() actions = menu_bar.actions() rasterText = QCoreApplication.translate("QgisApp", "&Raster") for a in actions: if a.menu() is not None and a.menu().title() == rasterText: rasterMenu = a.menu() break if rasterMenu is None: # no Raster menu, create and insert it before the Help menu self.menu = QMenu(rasterText, self.iface.mainWindow()) lastAction = actions[len(actions) - 1] menu_bar.insertMenu(lastAction, self.menu) else: self.menu = rasterMenu self._menuActions.append(self.menu.addSeparator()) # projections menu (Warp (Reproject), Assign projection) self.projectionsMenu = QMenu(QCoreApplication.translate("GdalTools", "Projections"), self.iface.mainWindow()) self.projectionsMenu.setObjectName("projectionsMenu") self.warp = QAction(QIcon(":/icons/warp.png"), QCoreApplication.translate("GdalTools", "Warp (Reproject)..."), self.iface.mainWindow()) self.warp.setObjectName("warp") self.warp.setStatusTip(QCoreApplication.translate("GdalTools", "Warp an image into a new coordinate system")) self.warp.triggered.connect(self.doWarp) self.projection = QAction(QIcon(":icons/projection-add.png"), QCoreApplication.translate("GdalTools", "Assign Projection..."), self.iface.mainWindow()) self.projection.setObjectName("projection") self.projection.setStatusTip(QCoreApplication.translate("GdalTools", "Add projection info to the raster")) self.projection.triggered.connect(self.doProjection) self.extractProj = QAction(QIcon(":icons/projection-export.png"), QCoreApplication.translate("GdalTools", "Extract Projection..."), self.iface.mainWindow()) self.extractProj.setObjectName("extractProj") self.extractProj.setStatusTip(QCoreApplication.translate("GdalTools", "Extract projection information from raster(s)")) self.extractProj.triggered.connect(self.doExtractProj) self.projectionsMenu.addActions([self.warp, self.projection, self.extractProj]) # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB) self.conversionMenu = QMenu(QCoreApplication.translate("GdalTools", "Conversion"), self.iface.mainWindow()) self.conversionMenu.setObjectName("conversionMenu") if self.GdalVersionNum >= 1300: self.rasterize = QAction(QIcon(":/icons/rasterize.png"), QCoreApplication.translate("GdalTools", "Rasterize (Vector to Raster)..."), self.iface.mainWindow()) self.rasterize.setObjectName("rasterize") self.rasterize.setStatusTip(QCoreApplication.translate("GdalTools", "Burns vector geometries into a raster")) self.rasterize.triggered.connect(self.doRasterize) self.conversionMenu.addAction(self.rasterize) if self.GdalVersionNum >= 1600: self.polygonize = QAction(QIcon(":/icons/polygonize.png"), QCoreApplication.translate("GdalTools", "Polygonize (Raster to Vector)..."), self.iface.mainWindow()) self.polygonize.setObjectName("polygonize") self.polygonize.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a polygon feature layer from a raster")) self.polygonize.triggered.connect(self.doPolygonize) self.conversionMenu.addAction(self.polygonize) self.translate = QAction(QIcon(":/icons/translate.png"), QCoreApplication.translate("GdalTools", "Translate (Convert Format)..."), self.iface.mainWindow()) self.translate.setObjectName("translate") self.translate.setStatusTip(QCoreApplication.translate("GdalTools", "Converts raster data between different formats")) self.translate.triggered.connect(self.doTranslate) self.paletted = QAction(QIcon(":icons/24-to-8-bits.png"), QCoreApplication.translate("GdalTools", "RGB to PCT..."), self.iface.mainWindow()) self.paletted.setObjectName("paletted") self.paletted.setStatusTip(QCoreApplication.translate("GdalTools", "Convert a 24bit RGB image to 8bit paletted")) self.paletted.triggered.connect(self.doPaletted) self.rgb = QAction(QIcon(":icons/8-to-24-bits.png"), QCoreApplication.translate("GdalTools", "PCT to RGB..."), self.iface.mainWindow()) self.rgb.setObjectName("rgb") self.rgb.setStatusTip(QCoreApplication.translate("GdalTools", "Convert an 8bit paletted image to 24bit RGB")) self.rgb.triggered.connect(self.doRGB) self.conversionMenu.addActions([self.translate, self.paletted, self.rgb]) # extraction menu (Clipper, Contour) self.extractionMenu = QMenu(QCoreApplication.translate("GdalTools", "Extraction"), self.iface.mainWindow()) self.extractionMenu.setObjectName("extractionMenu") if self.GdalVersionNum >= 1600: self.contour = QAction(QIcon(":/icons/contour.png"), QCoreApplication.translate("GdalTools", "Contour..."), self.iface.mainWindow()) self.contour.setObjectName("contour") self.contour.setStatusTip(QCoreApplication.translate("GdalTools", "Builds vector contour lines from a DEM")) self.contour.triggered.connect(self.doContour) self.extractionMenu.addAction(self.contour) self.clipper = QAction(QIcon(":icons/raster-clip.png"), QCoreApplication.translate("GdalTools", "Clipper..."), self.iface.mainWindow()) self.clipper.setObjectName("clipper") #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") ) self.clipper.triggered.connect(self.doClipper) self.extractionMenu.addActions([self.clipper]) # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve) self.analysisMenu = QMenu(QCoreApplication.translate("GdalTools", "Analysis"), self.iface.mainWindow()) self.analysisMenu.setObjectName("analysisMenu") if self.GdalVersionNum >= 1600: self.sieve = QAction(QIcon(":/icons/sieve.png"), QCoreApplication.translate("GdalTools", "Sieve..."), self.iface.mainWindow()) self.sieve.setObjectName("sieve") self.sieve.setStatusTip(QCoreApplication.translate("GdalTools", "Removes small raster polygons")) self.sieve.triggered.connect(self.doSieve) self.analysisMenu.addAction(self.sieve) if self.GdalVersionNum >= 1500: self.nearBlack = QAction(QIcon(":/icons/nearblack.png"), QCoreApplication.translate("GdalTools", "Near Black..."), self.iface.mainWindow()) self.nearBlack.setObjectName("nearBlack") self.nearBlack.setStatusTip(QCoreApplication.translate("GdalTools", "Convert nearly black/white borders to exact value")) self.nearBlack.triggered.connect(self.doNearBlack) self.analysisMenu.addAction(self.nearBlack) if self.GdalVersionNum >= 1700: self.fillNodata = QAction(QIcon(":/icons/fillnodata.png"), QCoreApplication.translate("GdalTools", "Fill nodata..."), self.iface.mainWindow()) self.fillNodata.setObjectName("fillNodata") self.fillNodata.setStatusTip(QCoreApplication.translate("GdalTools", "Fill raster regions by interpolation from edges")) self.fillNodata.triggered.connect(self.doFillNodata) self.analysisMenu.addAction(self.fillNodata) if self.GdalVersionNum >= 1600: self.proximity = QAction(QIcon(":/icons/proximity.png"), QCoreApplication.translate("GdalTools", "Proximity (Raster Distance)..."), self.iface.mainWindow()) self.proximity.setObjectName("proximity") self.proximity.setStatusTip(QCoreApplication.translate("GdalTools", "Produces a raster proximity map")) self.proximity.triggered.connect(self.doProximity) self.analysisMenu.addAction(self.proximity) if self.GdalVersionNum >= 1500: self.grid = QAction(QIcon(":/icons/grid.png"), QCoreApplication.translate("GdalTools", "Grid (Interpolation)..."), self.iface.mainWindow()) self.grid.setObjectName("grid") self.grid.setStatusTip(QCoreApplication.translate("GdalTools", "Create raster from the scattered data")) self.grid.triggered.connect(self.doGrid) self.analysisMenu.addAction(self.grid) if self.GdalVersionNum >= 1700: self.dem = QAction(QIcon(":icons/dem.png"), QCoreApplication.translate("GdalTools", "DEM (Terrain Models)..."), self.iface.mainWindow()) self.dem.setObjectName("dem") self.dem.setStatusTip(QCoreApplication.translate("GdalTools", "Tool to analyze and visualize DEMs")) self.dem.triggered.connect(self.doDEM) self.analysisMenu.addAction(self.dem) #self.analysisMenu.addActions( [ ] ) # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog)) self.miscellaneousMenu = QMenu(QCoreApplication.translate("GdalTools", "Miscellaneous"), self.iface.mainWindow()) self.miscellaneousMenu.setObjectName("miscellaneousMenu") if self.GdalVersionNum >= 1600: self.buildVRT = QAction(QIcon(":/icons/vrt.png"), QCoreApplication.translate("GdalTools", "Build Virtual Raster (Catalog)..."), self.iface.mainWindow()) self.buildVRT.setObjectName("buildVRT") self.buildVRT.setStatusTip(QCoreApplication.translate("GdalTools", "Builds a VRT from a list of datasets")) self.buildVRT.triggered.connect(self.doBuildVRT) self.miscellaneousMenu.addAction(self.buildVRT) self.merge = QAction(QIcon(":/icons/merge.png"), QCoreApplication.translate("GdalTools", "Merge..."), self.iface.mainWindow()) self.merge.setObjectName("merge") self.merge.setStatusTip(QCoreApplication.translate("GdalTools", "Build a quick mosaic from a set of images")) self.merge.triggered.connect(self.doMerge) self.info = QAction(QIcon(":/icons/raster-info.png"), QCoreApplication.translate("GdalTools", "Information..."), self.iface.mainWindow()) self.info.setObjectName("info") self.info.setStatusTip(QCoreApplication.translate("GdalTools", "Lists information about raster dataset")) self.info.triggered.connect(self.doInfo) self.overview = QAction(QIcon(":icons/raster-overview.png"), QCoreApplication.translate("GdalTools", "Build Overviews (Pyramids)..."), self.iface.mainWindow()) self.overview.setObjectName("overview") self.overview.setStatusTip(QCoreApplication.translate("GdalTools", "Builds or rebuilds overview images")) self.overview.triggered.connect(self.doOverview) self.tileindex = QAction(QIcon(":icons/tiles.png"), QCoreApplication.translate("GdalTools", "Tile Index..."), self.iface.mainWindow()) self.tileindex.setObjectName("tileindex") self.tileindex.setStatusTip(QCoreApplication.translate("GdalTools", "Build a shapefile as a raster tileindex")) self.tileindex.triggered.connect(self.doTileIndex) self.miscellaneousMenu.addActions([self.merge, self.info, self.overview, self.tileindex]) self._menuActions.append(self.menu.addMenu(self.projectionsMenu)) self._menuActions.append(self.menu.addMenu(self.conversionMenu)) self._menuActions.append(self.menu.addMenu(self.extractionMenu)) if not self.analysisMenu.isEmpty(): self._menuActions.append(self.menu.addMenu(self.analysisMenu)) self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu)) self.settings = QAction(QCoreApplication.translate("GdalTools", "GdalTools Settings..."), self.iface.mainWindow()) self.settings.setObjectName("settings") self.settings.setStatusTip(QCoreApplication.translate("GdalTools", "Various settings for Gdal Tools")) self.settings.triggered.connect(self.doSettings) self.menu.addAction(self.settings) self._menuActions.append(self.settings) def unload(self): if not valid: return for a in self._menuActions: self.menu.removeAction(a) def doBuildVRT(self): from .tools.doBuildVRT import GdalToolsDialog as BuildVRT d = BuildVRT(self.iface) self.runToolDialog(d) def doContour(self): from .tools.doContour import GdalToolsDialog as Contour d = Contour(self.iface) self.runToolDialog(d) def doRasterize(self): from .tools.doRasterize import GdalToolsDialog as Rasterize d = Rasterize(self.iface) self.runToolDialog(d) def doPolygonize(self): from .tools.doPolygonize import GdalToolsDialog as Polygonize d = Polygonize(self.iface) self.runToolDialog(d) def doMerge(self): from .tools.doMerge import GdalToolsDialog as Merge d = Merge(self.iface) self.runToolDialog(d) def doSieve(self): from .tools.doSieve import GdalToolsDialog as Sieve d = Sieve(self.iface) self.runToolDialog(d) def doProximity(self): from .tools.doProximity import GdalToolsDialog as Proximity d = Proximity(self.iface) self.runToolDialog(d) def doNearBlack(self): from .tools.doNearBlack import GdalToolsDialog as NearBlack d = NearBlack(self.iface) self.runToolDialog(d) def doFillNodata(self): from .tools.doFillNodata import GdalToolsDialog as FillNodata d = FillNodata(self.iface) self.runToolDialog(d) def doWarp(self): from .tools.doWarp import GdalToolsDialog as Warp d = Warp(self.iface) self.runToolDialog(d) def doGrid(self): from .tools.doGrid import GdalToolsDialog as Grid d = Grid(self.iface) self.runToolDialog(d) def doTranslate(self): from .tools.doTranslate import GdalToolsDialog as Translate d = Translate(self.iface) self.runToolDialog(d) def doInfo(self): from .tools.doInfo import GdalToolsDialog as Info d = Info(self.iface) self.runToolDialog(d) def doProjection(self): from .tools.doProjection import GdalToolsDialog as Projection d = Projection(self.iface) self.runToolDialog(d) def doOverview(self): from .tools.doOverview import GdalToolsDialog as Overview d = Overview(self.iface) self.runToolDialog(d) def doClipper(self): from .tools.doClipper import GdalToolsDialog as Clipper d = Clipper(self.iface) self.runToolDialog(d) def doPaletted(self): from .tools.doRgbPct import GdalToolsDialog as RgbPct d = RgbPct(self.iface) self.runToolDialog(d) def doRGB(self): from .tools.doPctRgb import GdalToolsDialog as PctRgb d = PctRgb(self.iface) self.runToolDialog(d) def doTileIndex(self): from .tools.doTileIndex import GdalToolsDialog as TileIndex d = TileIndex(self.iface) self.runToolDialog(d) def doExtractProj(self): from .tools.doExtractProj import GdalToolsDialog as ExtractProj d = ExtractProj(self.iface) d.exec_() def doDEM(self): from .tools.doDEM import GdalToolsDialog as DEM d = DEM(self.iface) self.runToolDialog(d) def runToolDialog(self, dlg): dlg.show_() dlg.exec_() del dlg def doSettings(self): from .tools.doSettings import GdalToolsSettingsDialog as Settings d = Settings(self.iface) d.exec_()
class GdalTools(object): def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = str(Qgis.QGIS_VERSION_INT) except: self.QgisVersion = str(Qgis.qgisVersion)[0] if Qgis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator) # The list of actions added to menus, so we can remove them when unloading the plugin self._menuActions = [] def initGui(self): if not valid: return if int(self.QgisVersion) < 1: QMessageBox.warning( self.iface.getMainWindow(), "Gdal Tools", QCoreApplication.translate("GdalTools", "QGIS version detected: ") + str(self.QgisVersion) + ".xx\n" + QCoreApplication.translate( "GdalTools", "This version of Gdal Tools requires at least QGIS version 1.0.0\nPlugin will not be enabled." )) return None from .tools.GdalTools_utils import GdalConfig, LayerRegistry self.GdalVersionNum = GdalConfig.versionNum() LayerRegistry.setIface(self.iface) # find the Raster menu rasterMenu = None menu_bar = self.iface.mainWindow().menuBar() actions = menu_bar.actions() rasterText = QCoreApplication.translate("QgisApp", "&Raster") for a in actions: if a.menu() is not None and a.menu().title() == rasterText: rasterMenu = a.menu() break if rasterMenu is None: # no Raster menu, create and insert it before the Help menu self.menu = QMenu(rasterText, self.iface.mainWindow()) lastAction = actions[len(actions) - 1] menu_bar.insertMenu(lastAction, self.menu) else: self.menu = rasterMenu self._menuActions.append(self.menu.addSeparator()) # projections menu (Warp (Reproject), Assign projection) self.projectionsMenu = QMenu( QCoreApplication.translate("GdalTools", "Projections"), self.iface.mainWindow()) self.projectionsMenu.setObjectName("projectionsMenu") self.warp = QAction( QIcon(":/icons/warp.png"), QCoreApplication.translate("GdalTools", "Warp (Reproject)..."), self.iface.mainWindow()) self.warp.setObjectName("warp") self.warp.setStatusTip( QCoreApplication.translate( "GdalTools", "Warp an image into a new coordinate system")) self.warp.triggered.connect(self.doWarp) self.projection = QAction( QIcon(":icons/projection-add.png"), QCoreApplication.translate("GdalTools", "Assign Projection..."), self.iface.mainWindow()) self.projection.setObjectName("projection") self.projection.setStatusTip( QCoreApplication.translate("GdalTools", "Add projection info to the raster")) self.projection.triggered.connect(self.doProjection) self.extractProj = QAction( QIcon(":icons/projection-export.png"), QCoreApplication.translate("GdalTools", "Extract Projection..."), self.iface.mainWindow()) self.extractProj.setObjectName("extractProj") self.extractProj.setStatusTip( QCoreApplication.translate( "GdalTools", "Extract projection information from raster(s)")) self.extractProj.triggered.connect(self.doExtractProj) self.projectionsMenu.addActions( [self.warp, self.projection, self.extractProj]) # conversion menu (Rasterize (Vector to raster), Polygonize (Raster to vector), Translate, RGB to PCT, PCT to RGB) self.conversionMenu = QMenu( QCoreApplication.translate("GdalTools", "Conversion"), self.iface.mainWindow()) self.conversionMenu.setObjectName("conversionMenu") if self.GdalVersionNum >= 1300: self.rasterize = QAction( QIcon(":/icons/rasterize.png"), QCoreApplication.translate("GdalTools", "Rasterize (Vector to Raster)..."), self.iface.mainWindow()) self.rasterize.setObjectName("rasterize") self.rasterize.setStatusTip( QCoreApplication.translate( "GdalTools", "Burns vector geometries into a raster")) self.rasterize.triggered.connect(self.doRasterize) self.conversionMenu.addAction(self.rasterize) if self.GdalVersionNum >= 1600: self.polygonize = QAction( QIcon(":/icons/polygonize.png"), QCoreApplication.translate("GdalTools", "Polygonize (Raster to Vector)..."), self.iface.mainWindow()) self.polygonize.setObjectName("polygonize") self.polygonize.setStatusTip( QCoreApplication.translate( "GdalTools", "Produces a polygon feature layer from a raster")) self.polygonize.triggered.connect(self.doPolygonize) self.conversionMenu.addAction(self.polygonize) self.translate = QAction( QIcon(":/icons/translate.png"), QCoreApplication.translate("GdalTools", "Translate (Convert Format)..."), self.iface.mainWindow()) self.translate.setObjectName("translate") self.translate.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats")) self.translate.triggered.connect(self.doTranslate) self.paletted = QAction( QIcon(":icons/24-to-8-bits.png"), QCoreApplication.translate("GdalTools", "RGB to PCT..."), self.iface.mainWindow()) self.paletted.setObjectName("paletted") self.paletted.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert a 24bit RGB image to 8bit paletted")) self.paletted.triggered.connect(self.doPaletted) self.rgb = QAction( QIcon(":icons/8-to-24-bits.png"), QCoreApplication.translate("GdalTools", "PCT to RGB..."), self.iface.mainWindow()) self.rgb.setObjectName("rgb") self.rgb.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert an 8bit paletted image to 24bit RGB")) self.rgb.triggered.connect(self.doRGB) self.conversionMenu.addActions( [self.translate, self.paletted, self.rgb]) # extraction menu (Clipper, Contour) self.extractionMenu = QMenu( QCoreApplication.translate("GdalTools", "Extraction"), self.iface.mainWindow()) self.extractionMenu.setObjectName("extractionMenu") if self.GdalVersionNum >= 1600: self.contour = QAction( QIcon(":/icons/contour.png"), QCoreApplication.translate("GdalTools", "Contour..."), self.iface.mainWindow()) self.contour.setObjectName("contour") self.contour.setStatusTip( QCoreApplication.translate( "GdalTools", "Builds vector contour lines from a DEM")) self.contour.triggered.connect(self.doContour) self.extractionMenu.addAction(self.contour) self.clipper = QAction( QIcon(":icons/raster-clip.png"), QCoreApplication.translate("GdalTools", "Clipper..."), self.iface.mainWindow()) self.clipper.setObjectName("clipper") #self.clipper.setStatusTip( QCoreApplication.translate( "GdalTools", "Converts raster data between different formats") ) self.clipper.triggered.connect(self.doClipper) self.extractionMenu.addActions([self.clipper]) # analysis menu (DEM (Terrain model), Grid (Interpolation), Near black, Proximity (Raster distance), Sieve) self.analysisMenu = QMenu( QCoreApplication.translate("GdalTools", "Analysis"), self.iface.mainWindow()) self.analysisMenu.setObjectName("analysisMenu") if self.GdalVersionNum >= 1600: self.sieve = QAction( QIcon(":/icons/sieve.png"), QCoreApplication.translate("GdalTools", "Sieve..."), self.iface.mainWindow()) self.sieve.setObjectName("sieve") self.sieve.setStatusTip( QCoreApplication.translate("GdalTools", "Removes small raster polygons")) self.sieve.triggered.connect(self.doSieve) self.analysisMenu.addAction(self.sieve) if self.GdalVersionNum >= 1500: self.nearBlack = QAction( QIcon(":/icons/nearblack.png"), QCoreApplication.translate("GdalTools", "Near Black..."), self.iface.mainWindow()) self.nearBlack.setObjectName("nearBlack") self.nearBlack.setStatusTip( QCoreApplication.translate( "GdalTools", "Convert nearly black/white borders to exact value")) self.nearBlack.triggered.connect(self.doNearBlack) self.analysisMenu.addAction(self.nearBlack) if self.GdalVersionNum >= 1700: self.fillNodata = QAction( QIcon(":/icons/fillnodata.png"), QCoreApplication.translate("GdalTools", "Fill nodata..."), self.iface.mainWindow()) self.fillNodata.setObjectName("fillNodata") self.fillNodata.setStatusTip( QCoreApplication.translate( "GdalTools", "Fill raster regions by interpolation from edges")) self.fillNodata.triggered.connect(self.doFillNodata) self.analysisMenu.addAction(self.fillNodata) if self.GdalVersionNum >= 1600: self.proximity = QAction( QIcon(":/icons/proximity.png"), QCoreApplication.translate("GdalTools", "Proximity (Raster Distance)..."), self.iface.mainWindow()) self.proximity.setObjectName("proximity") self.proximity.setStatusTip( QCoreApplication.translate("GdalTools", "Produces a raster proximity map")) self.proximity.triggered.connect(self.doProximity) self.analysisMenu.addAction(self.proximity) if self.GdalVersionNum >= 1500: self.grid = QAction( QIcon(":/icons/grid.png"), QCoreApplication.translate("GdalTools", "Grid (Interpolation)..."), self.iface.mainWindow()) self.grid.setObjectName("grid") self.grid.setStatusTip( QCoreApplication.translate( "GdalTools", "Create raster from the scattered data")) self.grid.triggered.connect(self.doGrid) self.analysisMenu.addAction(self.grid) if self.GdalVersionNum >= 1700: self.dem = QAction( QIcon(":icons/dem.png"), QCoreApplication.translate("GdalTools", "DEM (Terrain Models)..."), self.iface.mainWindow()) self.dem.setObjectName("dem") self.dem.setStatusTip( QCoreApplication.translate( "GdalTools", "Tool to analyze and visualize DEMs")) self.dem.triggered.connect(self.doDEM) self.analysisMenu.addAction(self.dem) #self.analysisMenu.addActions( [ ] ) # miscellaneous menu (Build overviews (Pyramids), Tile index, Information, Merge, Build Virtual Raster (Catalog)) self.miscellaneousMenu = QMenu( QCoreApplication.translate("GdalTools", "Miscellaneous"), self.iface.mainWindow()) self.miscellaneousMenu.setObjectName("miscellaneousMenu") if self.GdalVersionNum >= 1600: self.buildVRT = QAction( QIcon(":/icons/vrt.png"), QCoreApplication.translate( "GdalTools", "Build Virtual Raster (Catalog)..."), self.iface.mainWindow()) self.buildVRT.setObjectName("buildVRT") self.buildVRT.setStatusTip( QCoreApplication.translate( "GdalTools", "Builds a VRT from a list of datasets")) self.buildVRT.triggered.connect(self.doBuildVRT) self.miscellaneousMenu.addAction(self.buildVRT) self.merge = QAction( QIcon(":/icons/merge.png"), QCoreApplication.translate("GdalTools", "Merge..."), self.iface.mainWindow()) self.merge.setObjectName("merge") self.merge.setStatusTip( QCoreApplication.translate( "GdalTools", "Build a quick mosaic from a set of images")) self.merge.triggered.connect(self.doMerge) self.info = QAction( QIcon(":/icons/raster-info.png"), QCoreApplication.translate("GdalTools", "Information..."), self.iface.mainWindow()) self.info.setObjectName("info") self.info.setStatusTip( QCoreApplication.translate( "GdalTools", "Lists information about raster dataset")) self.info.triggered.connect(self.doInfo) self.overview = QAction( QIcon(":icons/raster-overview.png"), QCoreApplication.translate("GdalTools", "Build Overviews (Pyramids)..."), self.iface.mainWindow()) self.overview.setObjectName("overview") self.overview.setStatusTip( QCoreApplication.translate("GdalTools", "Builds or rebuilds overview images")) self.overview.triggered.connect(self.doOverview) self.tileindex = QAction( QIcon(":icons/tiles.png"), QCoreApplication.translate("GdalTools", "Tile Index..."), self.iface.mainWindow()) self.tileindex.setObjectName("tileindex") self.tileindex.setStatusTip( QCoreApplication.translate( "GdalTools", "Build a shapefile as a raster tileindex")) self.tileindex.triggered.connect(self.doTileIndex) self.miscellaneousMenu.addActions( [self.merge, self.info, self.overview, self.tileindex]) self._menuActions.append(self.menu.addMenu(self.projectionsMenu)) self._menuActions.append(self.menu.addMenu(self.conversionMenu)) self._menuActions.append(self.menu.addMenu(self.extractionMenu)) if not self.analysisMenu.isEmpty(): self._menuActions.append(self.menu.addMenu(self.analysisMenu)) self._menuActions.append(self.menu.addMenu(self.miscellaneousMenu)) self.settings = QAction( QCoreApplication.translate("GdalTools", "GdalTools Settings..."), self.iface.mainWindow()) self.settings.setObjectName("settings") self.settings.setStatusTip( QCoreApplication.translate("GdalTools", "Various settings for Gdal Tools")) self.settings.triggered.connect(self.doSettings) self.menu.addAction(self.settings) self._menuActions.append(self.settings) def unload(self): if not valid: return for a in self._menuActions: self.menu.removeAction(a) def doBuildVRT(self): from .tools.doBuildVRT import GdalToolsDialog as BuildVRT d = BuildVRT(self.iface) self.runToolDialog(d) def doContour(self): from .tools.doContour import GdalToolsDialog as Contour d = Contour(self.iface) self.runToolDialog(d) def doRasterize(self): from .tools.doRasterize import GdalToolsDialog as Rasterize d = Rasterize(self.iface) self.runToolDialog(d) def doPolygonize(self): from .tools.doPolygonize import GdalToolsDialog as Polygonize d = Polygonize(self.iface) self.runToolDialog(d) def doMerge(self): from .tools.doMerge import GdalToolsDialog as Merge d = Merge(self.iface) self.runToolDialog(d) def doSieve(self): from .tools.doSieve import GdalToolsDialog as Sieve d = Sieve(self.iface) self.runToolDialog(d) def doProximity(self): from .tools.doProximity import GdalToolsDialog as Proximity d = Proximity(self.iface) self.runToolDialog(d) def doNearBlack(self): from .tools.doNearBlack import GdalToolsDialog as NearBlack d = NearBlack(self.iface) self.runToolDialog(d) def doFillNodata(self): from .tools.doFillNodata import GdalToolsDialog as FillNodata d = FillNodata(self.iface) self.runToolDialog(d) def doWarp(self): from .tools.doWarp import GdalToolsDialog as Warp d = Warp(self.iface) self.runToolDialog(d) def doGrid(self): from .tools.doGrid import GdalToolsDialog as Grid d = Grid(self.iface) self.runToolDialog(d) def doTranslate(self): from .tools.doTranslate import GdalToolsDialog as Translate d = Translate(self.iface) self.runToolDialog(d) def doInfo(self): from .tools.doInfo import GdalToolsDialog as Info d = Info(self.iface) self.runToolDialog(d) def doProjection(self): from .tools.doProjection import GdalToolsDialog as Projection d = Projection(self.iface) self.runToolDialog(d) def doOverview(self): from .tools.doOverview import GdalToolsDialog as Overview d = Overview(self.iface) self.runToolDialog(d) def doClipper(self): from .tools.doClipper import GdalToolsDialog as Clipper d = Clipper(self.iface) self.runToolDialog(d) def doPaletted(self): from .tools.doRgbPct import GdalToolsDialog as RgbPct d = RgbPct(self.iface) self.runToolDialog(d) def doRGB(self): from .tools.doPctRgb import GdalToolsDialog as PctRgb d = PctRgb(self.iface) self.runToolDialog(d) def doTileIndex(self): from .tools.doTileIndex import GdalToolsDialog as TileIndex d = TileIndex(self.iface) self.runToolDialog(d) def doExtractProj(self): from .tools.doExtractProj import GdalToolsDialog as ExtractProj d = ExtractProj(self.iface) d.exec_() def doDEM(self): from .tools.doDEM import GdalToolsDialog as DEM d = DEM(self.iface) self.runToolDialog(d) def runToolDialog(self, dlg): dlg.show_() dlg.exec_() del dlg def doSettings(self): from .tools.doSettings import GdalToolsSettingsDialog as Settings d = Settings(self.iface) d.exec_()
def add_action( self, name, icon_path, text, callback, toggle_flag=False, enabled_flag=True, checkable_flag=False, visible_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param name: Objectname of the action. Serves also as key for the stored actions. :type name: str :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param toggle_flag: A flag indicating if the action should connect the toggled or triggered signal by default. Defaults to triggered (False) :type toggle_flag: bool :param checkable_flag: A flag indicating if the action should be checkable by default. Defaults to False. :type checkable: bool :param visible_flag: A flag indicating if the action should be displayed by default. Defaults to True. :type visible: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.setObjectName(name) if toggle_flag: action.toggled.connect(callback) else: action.triggered.connect(callback) action.setEnabled(enabled_flag) action.setCheckable(checkable_flag) action.setVisible(visible_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions[name] = action return action
class LatLonTools: digitizerDialog = None def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.crossRb = QgsRubberBand(self.canvas, QgsWkbTypes.LineGeometry) self.crossRb.setColor(Qt.red) self.provider = LatLonToolsProvider() self.toolbar = self.iface.addToolBar('Lat Lon Tools Toolbar') self.toolbar.setObjectName('LatLonToolsToolbar') def initGui(self): '''Initialize Lot Lon Tools GUI.''' # Initialize the Settings Dialog box self.settingsDialog = SettingsWidget(self, self.iface, self.iface.mainWindow()) self.mapTool = CopyLatLonTool(self.settingsDialog, self.iface) self.showMapTool = ShowOnMapTool(self.iface) # Add Interface for Coordinate Capturing icon = QIcon(os.path.dirname(__file__) + "/images/copyicon.png") self.copyAction = QAction(icon, "Copy Latitude, Longitude", self.iface.mainWindow()) self.copyAction.setObjectName('latLonToolsCopy') self.copyAction.triggered.connect(self.startCapture) self.copyAction.setCheckable(True) self.toolbar.addAction(self.copyAction) self.iface.addPluginToMenu("Lat Lon Tools", self.copyAction) # Add Interface for External Map icon = QIcon(os.path.dirname(__file__) + "/images/mapicon.png") self.externMapAction = QAction(icon, "Show in External Map", self.iface.mainWindow()) self.externMapAction.setObjectName('latLonToolsExternalMap') self.externMapAction.triggered.connect(self.setShowMapTool) self.externMapAction.setCheckable(True) self.toolbar.addAction(self.externMapAction) self.iface.addPluginToMenu("Lat Lon Tools", self.externMapAction) # Add Interface for Zoom to Coordinate icon = QIcon(os.path.dirname(__file__) + "/images/zoomicon.png") self.zoomToAction = QAction(icon, "Zoom To Latitude, Longitude", self.iface.mainWindow()) self.zoomToAction.setObjectName('latLonToolsZoom') self.zoomToAction.triggered.connect(self.showZoomToDialog) self.toolbar.addAction(self.zoomToAction) self.iface.addPluginToMenu('Lat Lon Tools', self.zoomToAction) self.zoomToDialog = ZoomToLatLon(self, self.iface, self.iface.mainWindow()) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.zoomToDialog) self.zoomToDialog.hide() # Add Interface for Multi point zoom icon = QIcon(os.path.dirname(__file__) + '/images/multizoom.png') self.multiZoomToAction = QAction(icon, "Multi-location Zoom", self.iface.mainWindow()) self.multiZoomToAction.setObjectName('latLonToolsMultiZoom') self.multiZoomToAction.triggered.connect(self.multiZoomTo) self.toolbar.addAction(self.multiZoomToAction) self.iface.addPluginToMenu('Lat Lon Tools', self.multiZoomToAction) self.multiZoomDialog = MultiZoomWidget(self, self.settingsDialog, self.iface.mainWindow()) self.multiZoomDialog.hide() self.multiZoomDialog.setFloating(True) # Create the conversions menu menu = QMenu() icon = QIcon(os.path.dirname(__file__) + '/images/field2geom.png') action = menu.addAction(icon, "Fields to point layer", self.field2geom) action.setObjectName('latLonToolsField2Geom') icon = QIcon(os.path.dirname(__file__) + '/images/geom2field.png') action = menu.addAction(icon, "Point layer to fields", self.geom2Field) action.setObjectName('latLonToolsGeom2Field') icon = QIcon(os.path.dirname(__file__) + '/images/pluscodes.png') action = menu.addAction(icon, "Plus Codes to point layer", self.PlusCodestoLayer) action.setObjectName('latLonToolsPlusCodes2Geom') action = menu.addAction(icon, "Point layer to Plus Codes", self.toPlusCodes) action.setObjectName('latLonToolsGeom2PlusCodes') icon = QIcon(os.path.dirname(__file__) + '/images/mgrs2point.png') action = menu.addAction(icon, "MGRS to point layer", self.MGRStoLayer) action.setObjectName('latLonToolsMGRS2Geom') icon = QIcon(os.path.dirname(__file__) + '/images/point2mgrs.png') action = menu.addAction(icon, "Point layer to MGRS", self.toMGRS) action.setObjectName('latLonToolsGeom2MGRS') self.conversionsAction = QAction(icon, "Conversions", self.iface.mainWindow()) self.conversionsAction.setMenu(menu) self.iface.addPluginToMenu('Lat Lon Tools', self.conversionsAction) # Add to Digitize Toolbar icon = QIcon(os.path.dirname(__file__) + '/images/latLonDigitize.png') self.digitizeAction = QAction(icon, "Lat Lon Digitize", self.iface.mainWindow()) self.digitizeAction.setObjectName('latLonToolsDigitize') self.digitizeAction.triggered.connect(self.digitizeClicked) self.digitizeAction.setEnabled(False) self.toolbar.addAction(self.digitizeAction) self.iface.addPluginToMenu('Lat Lon Tools', self.digitizeAction) # Add Interface for copying the canvas extent icon = QIcon(os.path.dirname(__file__) + "/images/copycanvas.png") self.copyCanvasAction = QAction(icon, "Copy Canvas Bounding Box", self.iface.mainWindow()) self.copyCanvasAction.setObjectName('latLonToolsCopyCanvas') self.copyCanvasAction.triggered.connect(self.copyCanvas) self.toolbar.addAction(self.copyCanvasAction) self.iface.addPluginToMenu("Lat Lon Tools", self.copyCanvasAction) # Initialize the Settings Dialog Box settingsicon = QIcon(os.path.dirname(__file__) + '/images/settings.png') self.settingsAction = QAction(settingsicon, "Settings", self.iface.mainWindow()) self.settingsAction.setObjectName('latLonToolsSettings') self.settingsAction.triggered.connect(self.settings) self.iface.addPluginToMenu('Lat Lon Tools', self.settingsAction) # Help icon = QIcon(os.path.dirname(__file__) + '/images/help.png') self.helpAction = QAction(icon, "Help", self.iface.mainWindow()) self.helpAction.setObjectName('latLonToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToMenu('Lat Lon Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.unsetTool) self.enableDigitizeTool() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider) def unsetTool(self, tool): '''Uncheck the Copy Lat Lon tool''' try: if not isinstance(tool, CopyLatLonTool): self.copyAction.setChecked(False) self.multiZoomDialog.stopCapture() self.mapTool.capture4326 = False if not isinstance(tool, ShowOnMapTool): self.externMapAction.setChecked(False) except: pass def unload(self): '''Unload LatLonTools from the QGIS interface''' self.zoomToDialog.removeMarker() self.multiZoomDialog.removeMarkers() self.canvas.unsetMapTool(self.mapTool) self.canvas.unsetMapTool(self.showMapTool) self.iface.removePluginMenu('Lat Lon Tools', self.copyAction) self.iface.removePluginMenu('Lat Lon Tools', self.copyCanvasAction) self.iface.removePluginMenu('Lat Lon Tools', self.externMapAction) self.iface.removePluginMenu('Lat Lon Tools', self.zoomToAction) self.iface.removePluginMenu('Lat Lon Tools', self.multiZoomToAction) self.iface.removePluginMenu('Lat Lon Tools', self.conversionsAction) self.iface.removePluginMenu('Lat Lon Tools', self.settingsAction) self.iface.removePluginMenu('Lat Lon Tools', self.helpAction) self.iface.removePluginMenu('Lat Lon Tools', self.digitizeAction) self.iface.removeDockWidget(self.zoomToDialog) self.iface.removeDockWidget(self.multiZoomDialog) # Remove Toolbar Icons self.iface.removeToolBarIcon(self.copyAction) self.iface.removeToolBarIcon(self.copyCanvasAction) self.iface.removeToolBarIcon(self.zoomToAction) self.iface.removeToolBarIcon(self.externMapAction) self.iface.removeToolBarIcon(self.multiZoomToAction) self.iface.removeToolBarIcon(self.digitizeAction) del self.toolbar self.zoomToDialog = None self.multiZoomDialog = None self.settingsDialog = None self.showMapTool = None self.mapTool = None self.digitizerDialog = None QgsApplication.processingRegistry().removeProvider(self.provider) def startCapture(self): '''Set the focus of the copy coordinate tool and check it''' self.copyAction.setChecked(True) self.canvas.setMapTool(self.mapTool) def copyCanvas(self): extent = self.iface.mapCanvas().extent() canvasCrs = self.canvas.mapSettings().destinationCrs() if settings.bBoxCrs == 0 and canvasCrs != epsg4326: transform = QgsCoordinateTransform(canvasCrs, epsg4326, QgsProject.instance()) p1x, p1y = transform.transform(float(extent.xMinimum()), float(extent.yMinimum())) p2x, p2y = transform.transform(float(extent.xMaximum()), float(extent.yMaximum())) extent.set(p1x, p1y, p2x, p2y) delim = settings.bBoxDelimiter prefix = settings.bBoxPrefix suffix = settings.bBoxSuffix precision = settings.bBoxDigits outStr = '' minX = extent.xMinimum() minY = extent.yMinimum() maxX = extent.xMaximum() maxY = extent.yMaximum() if settings.bBoxFormat == 0: # minX,minY,maxX,maxY - using the delimiter outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format( minX, delim, minY, delim, maxX, delim, maxY, prec=precision) elif settings.bBoxFormat == 1: # minX,maxX,minY,maxY - Using the selected delimiter' outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format( minX, delim, maxX, delim, minY, delim, maxY, prec=precision) elif settings.bBoxFormat == 2: # x1 y1,x2 y2,x3 y3,x4 y4,x1 y1 - Polygon format outStr = '{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f}'.format( minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY, prec=precision) elif settings.bBoxFormat == 3: # x1,y1 x2,y2 x3,y3 x4,y4 x1,y1 - Polygon format outStr = '{:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f}'.format( minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY, prec=precision) elif settings.bBoxFormat == 4: # WKT Polygon outStr = extent.asWktPolygon() elif settings.bBoxFormat == 5: # bbox: [minX, minY, maxX, maxY] - MapProxy outStr = 'bbox: [{}, {}, {}, {}]'.format( minX, minY, maxX, maxY) elif settings.bBoxFormat == 6: # bbox: [minX, minY, maxX, maxY] - MapProxy outStr = 'bbox={},{},{},{}'.format( minX, minY, maxX, maxY) outStr = '{}{}{}'.format(prefix, outStr, suffix) clipboard = QApplication.clipboard() clipboard.setText(outStr) self.iface.messageBar().pushMessage("", "'{}' copied to the clipboard".format(outStr), level=Qgis.Info, duration=4) def setShowMapTool(self): '''Set the focus of the external map tool and check it''' self.externMapAction.setChecked(True) self.canvas.setMapTool(self.showMapTool) def showZoomToDialog(self): '''Show the zoom to docked widget.''' self.zoomToDialog.show() def multiZoomTo(self): '''Display the Multi-zoom to dialog box''' self.multiZoomDialog.show() def field2geom(self): '''Convert layer containing a point x & y coordinate to a new point layer''' results = processing.execAlgorithmDialog('latlontools:field2geom', {}) def geom2Field(self): '''Convert layer geometry to a text string''' results = processing.execAlgorithmDialog('latlontools:geom2field', {}) def toMGRS(self): '''Display the to MGRS dialog box''' results = processing.execAlgorithmDialog('latlontools:point2mgrs', {}) def MGRStoLayer(self): '''Display the to MGRS dialog box''' results = processing.execAlgorithmDialog('latlontools:mgrs2point', {}) def toPlusCodes(self): results = processing.execAlgorithmDialog('latlontools:point2pluscodes', {}) def PlusCodestoLayer(self): results = processing.execAlgorithmDialog('latlontools:pluscodes2point', {}) def settings(self): '''Show the settings dialog box''' self.settingsDialog.show() def help(self): '''Display a help page''' url = QUrl.fromLocalFile(os.path.dirname(__file__) + "/index.html").toString() webbrowser.open(url, new=2) def settingsChanged(self): # Settings may have changed so we need to make sure the zoomToDialog window is configured properly self.zoomToDialog.configure() self.multiZoomDialog.settingsChanged() def zoomTo(self, srcCrs, lat, lon): canvasCrs = self.canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(srcCrs, canvasCrs, QgsProject.instance()) x, y = transform.transform(float(lon), float(lat)) rect = QgsRectangle(x, y, x, y) self.canvas.setExtent(rect) pt = QgsPointXY(x, y) self.highlight(pt) self.canvas.refresh() return pt def highlight(self, point): currExt = self.canvas.extent() leftPt = QgsPoint(currExt.xMinimum(), point.y()) rightPt = QgsPoint(currExt.xMaximum(), point.y()) topPt = QgsPoint(point.x(), currExt.yMaximum()) bottomPt = QgsPoint(point.x(), currExt.yMinimum()) horizLine = QgsGeometry.fromPolyline( [ leftPt , rightPt ] ) vertLine = QgsGeometry.fromPolyline( [ topPt , bottomPt ] ) self.crossRb.reset(QgsWkbTypes.LineGeometry) self.crossRb.addGeometry(horizLine, None) self.crossRb.addGeometry(vertLine, None) QTimer.singleShot(700, self.resetRubberbands) def resetRubberbands(self): self.crossRb.reset() def digitizeClicked(self): if self.digitizerDialog == None: from .digitizer import DigitizerWidget self.digitizerDialog = DigitizerWidget(self, self.iface, self.iface.mainWindow()) self.digitizerDialog.show() def currentLayerChanged(self): layer = self.iface.activeLayer() if layer != None: try: layer.editingStarted.disconnect(self.layerEditingChanged) except: pass try: layer.editingStopped.disconnect(self.layerEditingChanged) except: pass if isinstance(layer, QgsVectorLayer): layer.editingStarted.connect(self.layerEditingChanged) layer.editingStopped.connect(self.layerEditingChanged) self.enableDigitizeTool() def layerEditingChanged(self): self.enableDigitizeTool() def enableDigitizeTool(self): self.digitizeAction.setEnabled(False) layer = self.iface.activeLayer() if layer != None and isinstance(layer, QgsVectorLayer) and (layer.geometryType() == QgsWkbTypes.PointGeometry) and layer.isEditable(): self.digitizeAction.setEnabled(True) else: if self.digitizerDialog != None: self.digitizerDialog.close()
class BoundlessConnectPlugin(object): def __init__(self, iface): self.iface = iface try: from boundlessconnect.tests import testerplugin from qgistester.tests import addTestModule addTestModule(testerplugin, 'Boundless Connect') except Exception as e: pass self.dockWidget = None readSettings() self.iface.initializationCompleted.connect(self.checkFirstRun) def initGui(self): self.dockWidget = getConnectDockWidget() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockWidget) self.dockWidget.hide() utils.setRepositoryUrl() self.actionRunWizard = self.dockWidget.toggleViewAction() self.actionRunWizard.setText('Boundless Connect') self.actionRunWizard.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'connect.svg'))) self.actionRunWizard.setWhatsThis('Boundless Connect') self.actionRunWizard.setObjectName('actionRunWizard') # If Boundless repository is a directory, add menu entry # to start modified Plugin Manager which works with local repositories if utils.isRepositoryInDirectory(): self.actionPluginManager = QAction( 'Manage plugins (local folder)', self.iface.mainWindow()) self.actionPluginManager.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'plugin.svg'))) self.actionPluginManager.setWhatsThis( 'Manage and install plugins from local repository') self.actionPluginManager.setObjectName('actionPluginManager') self.iface.addPluginToMenu( 'Boundless Connect', self.actionPluginManager) self.actionPluginManager.triggered.connect(self.pluginManagerLocal) actions = self.iface.mainWindow().menuBar().actions() for action in actions: if action.menu().objectName() == 'mPluginMenu': menuPlugin = action.menu() separator = menuPlugin.actions()[1] menuPlugin.insertAction(separator, self.actionRunWizard) if utils.isRepositoryInDirectory(): menuPlugin.insertAction(separator, self.actionPluginManager) addSettingsMenu('Boundless Connect') addHelpMenu('Boundless Connect') addAboutMenu('Boundless Connect') # Enable check for updates if it is not enabled utils.addCheckForUpdates() try: from lessons import addLessonsFolder, addGroup folder = os.path.join(os.path.dirname(__file__), "_lessons") addLessonsFolder(folder, "boundlessconnect") group_description = os.path.join(folder, "group.md") addGroup("Boundless Connect plugin", group_description) except: pass def unload(self): actions = self.iface.mainWindow().menuBar().actions() for action in actions: if action.menu().objectName() == 'mPluginMenu': menuPlugin = action.menu() menuPlugin.removeAction(self.actionRunWizard) if utils.isRepositoryInDirectory(): menuPlugin.removeAction(self.actionPluginManager) removeSettingsMenu('Boundless Connect') removeHelpMenu('Boundless Connect') removeAboutMenu('Boundless Connect') self.dockWidget.hide() try: from boundlessconnect.tests import testerplugin from qgistester.tests import removeTestModule removeTestModule(testerplugin, 'Boundless Connect') except Exception as e: pass try: from lessons import removeLessonsFolder folder = os.path.join(pluginPath, '_lessons') removeLessonsFolder(folder) except: pass def checkFirstRun(self): settings = QSettings() firstRun = settings.value('boundlessconnect/firstRun', True, bool) settings.setValue('boundlessconnect/firstRun', False) if self.dockWidget is None: self.dockWidget = getConnectDockWidget() if firstRun: self.dockWidget.show() utils.installFromStandardPath() def installPlugin(self): fileName = askForFiles(self.iface.mainWindow(), 'Open file', exts='zip') if fileName is None: return result = utils.installFromZipFile(fileName) if result is None: self._showMessage('Plugin installed successfully', QgsMessageBar.SUCCESS) else: self._showMessage(result, QgsMessageBar.WARNING) settings.setValue('lastPluginDirectory', QFileInfo(fileName).absoluteDir().absolutePath()) def pluginManagerLocal(self): utils.showPluginManager(False) def _showMessage(self, message, level=QgsMessageBar.INFO): self.iface.messageBar().pushMessage( message, level, self.iface.messageTimeout())
class ProcessingPlugin: def __init__(self, iface): self.iface = iface self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider( self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) # Invalidate the locator filter for in-place when active layer changes iface.currentLayerChanged.connect( lambda _: self.iface.invalidateLocatorResults()) self.edit_features_locator_filter = InPlaceAlgorithmLocatorFilter() iface.registerLocatorFilter(self.edit_features_locator_filter) Processing.initialize() def initGui(self): self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction( self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction( self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', 'Graphical &Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction( self.modelerAction, QKeySequence('Ctrl+Alt+M').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QgsApplication.getThemeIcon("/mIconHistory.svg"), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction( self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction( self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect( self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.toolbox.processingToolbar.addSeparator() self.editInPlaceAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Features In-Place'), self.iface.mainWindow()) self.editInPlaceAction.setObjectName('editInPlaceFeatures') self.editInPlaceAction.setCheckable(True) self.editInPlaceAction.toggled.connect(self.editSelected) self.menu.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addSeparator() self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() # In-place editing button state sync self.iface.currentLayerChanged.connect(self.sync_in_place_button_state) self.iface.mapCanvas().selectionChanged.connect( self.sync_in_place_button_state) self.iface.actionToggleEditing().triggered.connect( partial(self.sync_in_place_button_state, None)) self.sync_in_place_button_state() def sync_in_place_button_state(self, layer=None): """Synchronise the button state with layer state""" if layer is None: layer = self.iface.activeLayer() old_enabled_state = self.editInPlaceAction.isEnabled() new_enabled_state = layer is not None and layer.type( ) == QgsMapLayer.VectorLayer self.editInPlaceAction.setEnabled(new_enabled_state) if new_enabled_state != old_enabled_state: self.toolbox.set_in_place_edit_mode( new_enabled_state and self.editInPlaceAction.isChecked()) def openProcessingOptions(self): self.iface.showOptionsDialog(self.iface.mainWindow(), currentPage='processingOptions') def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.iface.attributesToolBar().removeAction(self.toolboxAction) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.toolbox.deleteLater() self.menu.deleteLater() # delete temporary output files folder = QgsProcessingUtils.tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) # also delete temporary help files folder = tempHelpFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) self.iface.deregisterLocatorFilter(self.locator_filter) self.iface.deregisterLocatorFilter(self.edit_features_locator_filter) self.iface.unregisterCustomDropHandler(self.drop_handler) QgsApplication.dataItemProviderRegistry().removeProvider( self.item_provider) removeMenus() Processing.deinitialize() def openToolbox(self, show): self.toolbox.setUserVisible(show) def toolboxVisibilityChanged(self, visible): self.toolboxAction.setChecked(visible) def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById( 'model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message) def editSelected(self, enabled): self.toolbox.set_in_place_edit_mode(enabled)
def create_action( icon_path, text, callback, enabled_flag=True, status_tip=None, whats_this=None, parent=None, object_name=None): """ # adapted from RedLayers by E. Ferreguti Create an action. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :param object_name: Optional name to identify objects during customization :type object_name: str :returns: The action that was created. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) if callback: action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip: action.setStatusTip(status_tip) if whats_this: action.setWhatsThis(whats_this) if object_name: action.setObjectName(object_name) return action
class ProcessingPlugin(object): def __init__(self, iface): self.iface = iface Processing.initialize() def initGui(self): self.commander = None self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = self.toolbox.toggleViewAction() self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QIcon(os.path.join(cmd_folder, 'images', 'alg.png'))) self.toolboxAction.setText(self.tr('&Toolbox')) self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T') self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'model.png')), self.tr('Graphical &Modeler...'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M') self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'history.gif')), self.tr('&History...'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H') self.menu.addAction(self.historyAction) self.configAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'config.png')), self.tr('&Options...'), self.iface.mainWindow()) self.configAction.setObjectName('configAction') self.configAction.triggered.connect(self.openConfig) self.iface.registerMainWindowAction(self.configAction, 'Ctrl+Alt+C') self.menu.addAction(self.configAction) self.resultsAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'results.png')), self.tr('&Results Viewer...'), self.iface.mainWindow()) self.resultsAction.setObjectName('resultsAction') self.resultsAction.triggered.connect(self.openResults) self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R') self.menu.addAction(self.resultsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) self.commanderAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'commander.png')), self.tr('&Commander'), self.iface.mainWindow()) self.commanderAction.setObjectName('commanderAction') self.commanderAction.triggered.connect(self.openCommander) self.menu.addAction(self.commanderAction) self.iface.registerMainWindowAction(self.commanderAction, self.tr('Ctrl+Alt+D')) initializeMenus() createMenus() def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.menu.deleteLater() # delete temporary output files folder = tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.configAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterMainWindowAction(self.commanderAction) removeMenus() def openCommander(self): if self.commander is None: self.commander = CommanderWindow(self.iface.mainWindow(), self.iface.mapCanvas()) self.commander.prepareGui() self.commander.show() def openToolbox(self): if self.toolbox.isVisible(): self.toolbox.hide() else: self.toolbox.show() def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): algList.reloadProvider('model') def openResults(self): dlg = ResultsDialog() dlg.show() dlg.exec_() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def openConfig(self): dlg = ConfigDialog(self.toolbox) dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class Plugin(): """The QGIS interface implementation for the InaSAFE plugin. This class acts as the 'glue' between QGIS and our custom logic. It creates a toolbar and menu bar entry and launches the InaSAFE user interface if these are activated. """ def __init__(self, iface): """Class constructor. On instantiation, the plugin instance will be assigned a copy of the QGIS iface object which will allow this plugin to access and manipulate the running QGIS instance that spawned it. :param iface:Quantum GIS iface instance. This instance is automatically passed to the plugin by QGIS when it loads the plugin. :type iface: QgisAppInterface """ # Save reference to the QGIS interface self.iface = iface self.dock_widget = None # Actions self.action_add_layers = None self.action_add_osm_layer = None self.action_add_petabencana_layer = None self.action_batch_runner = None self.action_dock = None self.action_extent_selector = None self.action_field_mapping = None self.action_multi_exposure = None self.action_function_centric_wizard = None self.action_import_dialog = None self.action_keywords_wizard = None self.action_minimum_needs = None self.action_minimum_needs_config = None self.action_multi_buffer = None self.action_options = None self.action_run_tests = None self.action_save_scenario = None self.action_shake_converter = None self.action_show_definitions = None self.action_toggle_rubberbands = None self.action_metadata_converter = None self.translator = None self.toolbar = None self.wizard = None self.actions = [] # list of all QActions we create for InaSAFE self.message_bar_item = None # Flag indicating if toolbar should show only common icons or not self.full_toolbar = False # print self.tr('InaSAFE') # For enable/disable the keyword editor icon self.iface.currentLayerChanged.connect(self.layer_changed) developer_mode = setting('developer_mode', False, expected_type=bool) self.hide_developer_buttons = (inasafe_release_status == 'final' and not developer_mode) # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('Plugin', message) def add_action(self, action, add_to_toolbar=True, add_to_legend=False): """Add a toolbar icon to the InaSAFE toolbar. :param action: The action that should be added to the toolbar. :type action: QAction :param add_to_toolbar: Flag indicating whether the action should also be added to the InaSAFE toolbar. Defaults to True. :type add_to_toolbar: bool :param add_to_legend: Flag indicating whether the action should also be added to the layer legend menu. Default to False. :type add_to_legend: bool """ # store in the class list of actions for easy plugin unloading self.actions.append(action) self.iface.addPluginToMenu(self.tr('InaSAFE'), action) if add_to_toolbar: self.toolbar.addAction(action) if add_to_legend: # The id is the action name without spaces, tabs ... self.iface.addCustomActionForLayerType(action, self.tr('InaSAFE'), QgsMapLayer.VectorLayer, True) self.iface.addCustomActionForLayerType(action, self.tr('InaSAFE'), QgsMapLayer.RasterLayer, True) def _create_dock_toggle_action(self): """Create action for plugin dockable window (show/hide).""" # pylint: disable=W0201 icon = resources_path('img', 'icons', 'icon.svg') self.action_dock = QAction(QIcon(icon), self.tr('Toggle InaSAFE Dock'), self.iface.mainWindow()) self.action_dock.setObjectName('InaSAFEDockToggle') self.action_dock.setStatusTip(self.tr('Show/hide InaSAFE dock widget')) self.action_dock.setWhatsThis(self.tr('Show/hide InaSAFE dock widget')) self.action_dock.setCheckable(True) self.action_dock.setChecked(True) self.action_dock.triggered.connect(self.toggle_dock_visibility) self.add_action(self.action_dock) # -------------------------------------- # Create action for keywords creation wizard # ------------------------------------- def _create_keywords_wizard_action(self): """Create action for keywords creation wizard.""" icon = resources_path('img', 'icons', 'show-keyword-wizard.svg') self.action_keywords_wizard = QAction( QIcon(icon), self.tr('Keywords Creation Wizard'), self.iface.mainWindow()) self.action_keywords_wizard.setStatusTip( self.tr('Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setWhatsThis( self.tr('Open InaSAFE keywords creation wizard')) self.action_keywords_wizard.setEnabled(False) self.action_keywords_wizard.triggered.connect( self.show_keywords_wizard) self.add_action(self.action_keywords_wizard, add_to_legend=True) def _create_analysis_wizard_action(self): """Create action for IF-centric wizard.""" icon = resources_path('img', 'icons', 'show-wizard.svg') self.action_function_centric_wizard = QAction( QIcon(icon), self.tr('Impact Function Centric Wizard'), self.iface.mainWindow()) self.action_function_centric_wizard.setStatusTip( self.tr('Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setWhatsThis( self.tr('Open InaSAFE impact function centric wizard')) self.action_function_centric_wizard.setEnabled(True) self.action_function_centric_wizard.triggered.connect( self.show_function_centric_wizard) self.add_action(self.action_function_centric_wizard) def _create_options_dialog_action(self): """Create action for options dialog.""" icon = resources_path('img', 'icons', 'configure-inasafe.svg') self.action_options = QAction(QIcon(icon), self.tr('Options'), self.iface.mainWindow()) self.action_options.setStatusTip( self.tr('Open InaSAFE options dialog')) self.action_options.setWhatsThis( self.tr('Open InaSAFE options dialog')) self.action_options.triggered.connect(self.show_options) self.add_action(self.action_options, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_action(self): """Create action for minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-minimum-needs.svg') self.action_minimum_needs = QAction( QIcon(icon), self.tr('Minimum Needs Calculator'), self.iface.mainWindow()) self.action_minimum_needs.setStatusTip( self.tr('Open InaSAFE minimum needs calculator')) self.action_minimum_needs.setWhatsThis( self.tr('Open InaSAFE minimum needs calculator')) self.action_minimum_needs.triggered.connect(self.show_minimum_needs) self.add_action(self.action_minimum_needs, add_to_toolbar=self.full_toolbar) def _create_multi_buffer_action(self): """Create action for multi buffer dialog.""" icon = resources_path('img', 'icons', 'show-multi-buffer.svg') self.action_multi_buffer = QAction(QIcon(icon), self.tr('Multi Buffer'), self.iface.mainWindow()) self.action_multi_buffer.setStatusTip( self.tr('Open InaSAFE multi buffer')) self.action_multi_buffer.setWhatsThis( self.tr('Open InaSAFE multi buffer')) self.action_multi_buffer.triggered.connect(self.show_multi_buffer) self.add_action(self.action_multi_buffer, add_to_toolbar=self.full_toolbar) def _create_minimum_needs_options_action(self): """Create action for global minimum needs dialog.""" icon = resources_path('img', 'icons', 'show-global-minimum-needs.svg') self.action_minimum_needs_config = QAction( QIcon(icon), self.tr('Minimum Needs Configuration'), self.iface.mainWindow()) self.action_minimum_needs_config.setStatusTip( self.tr('Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.setWhatsThis( self.tr('Open InaSAFE minimum needs configuration')) self.action_minimum_needs_config.triggered.connect( self.show_minimum_needs_configuration) self.add_action(self.action_minimum_needs_config, add_to_toolbar=self.full_toolbar) def _create_shakemap_converter_action(self): """Create action for converter dialog.""" icon = resources_path('img', 'icons', 'show-converter-tool.svg') self.action_shake_converter = QAction(QIcon(icon), self.tr('Shakemap Converter'), self.iface.mainWindow()) self.action_shake_converter.setStatusTip( self.tr('Open InaSAFE Converter')) self.action_shake_converter.setWhatsThis( self.tr('Open InaSAFE Converter')) self.action_shake_converter.triggered.connect( self.show_shakemap_importer) self.add_action(self.action_shake_converter, add_to_toolbar=self.full_toolbar) def _create_batch_runner_action(self): """Create action for batch runner dialog.""" icon = resources_path('img', 'icons', 'show-batch-runner.svg') self.action_batch_runner = QAction(QIcon(icon), self.tr('Batch Runner'), self.iface.mainWindow()) self.action_batch_runner.setStatusTip(self.tr('Open Batch Runner')) self.action_batch_runner.setWhatsThis(self.tr('Open Batch Runner')) self.action_batch_runner.triggered.connect(self.show_batch_runner) self.add_action(self.action_batch_runner, add_to_toolbar=self.full_toolbar) def _create_save_scenario_action(self): """Create action for save scenario dialog.""" icon = resources_path('img', 'icons', 'save-as-scenario.svg') self.action_save_scenario = QAction(QIcon(icon), self.tr('Save Current Scenario'), self.iface.mainWindow()) message = self.tr('Save current scenario to text file') self.action_save_scenario.setStatusTip(message) self.action_save_scenario.setWhatsThis(message) # noinspection PyUnresolvedReferences self.action_save_scenario.triggered.connect(self.save_scenario) self.add_action(self.action_save_scenario, add_to_toolbar=self.full_toolbar) def _create_osm_downloader_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'show-osm-download.svg') self.action_import_dialog = QAction( QIcon(icon), self.tr('OpenStreetMap Downloader'), self.iface.mainWindow()) self.action_import_dialog.setStatusTip( self.tr('OpenStreetMap Downloader')) self.action_import_dialog.setWhatsThis( self.tr('OpenStreetMap Downloader')) self.action_import_dialog.triggered.connect(self.show_osm_downloader) self.add_action(self.action_import_dialog, add_to_toolbar=True) def _create_geonode_uploader_action(self): """Create action for Geonode uploader dialog.""" icon = resources_path('img', 'icons', 'geonode.png') label = tr('Geonode Uploader') self.action_geonode = QAction(QIcon(icon), label, self.iface.mainWindow()) self.action_geonode.setStatusTip(label) self.action_geonode.setWhatsThis(label) self.action_geonode.triggered.connect(self.show_geonode_uploader) self.add_action(self.action_geonode, add_to_toolbar=False) def _create_add_osm_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-osm-tiles-layer.svg') self.action_add_osm_layer = QAction( QIcon(icon), self.tr('Add OpenStreetMap Tile Layer'), self.iface.mainWindow()) self.action_add_osm_layer.setStatusTip( self.tr('Add OpenStreetMap Tile Layer')) self.action_add_osm_layer.setWhatsThis( self.tr('Use this to add an OSM layer to your map. ' 'It needs internet access to function.')) self.action_add_osm_layer.triggered.connect(self.add_osm_layer) self.add_action(self.action_add_osm_layer, add_to_toolbar=True) def _create_show_definitions_action(self): """Create action for showing definitions / help.""" icon = resources_path('img', 'icons', 'show-inasafe-help.svg') self.action_show_definitions = QAction(QIcon(icon), self.tr('InaSAFE Help'), self.iface.mainWindow()) self.action_show_definitions.setStatusTip(self.tr('Show InaSAFE Help')) self.action_show_definitions.setWhatsThis( self. tr('Use this to show a document describing all InaSAFE concepts.')) self.action_show_definitions.triggered.connect(self.show_definitions) self.add_action(self.action_show_definitions, add_to_toolbar=True) def _create_metadata_converter_action(self): """Create action for showing metadata converter dialog.""" icon = resources_path('img', 'icons', 'show-metadata-converter.svg') self.action_metadata_converter = QAction( QIcon(icon), self.tr('InaSAFE Metadata Converter'), self.iface.mainWindow()) self.action_metadata_converter.setStatusTip( self.tr('Convert metadata from version 4.3 to version 3.5.')) self.action_metadata_converter.setWhatsThis( self.tr('Use this tool to convert metadata 4.3 to version 3.5')) self.action_metadata_converter.triggered.connect( self.show_metadata_converter) self.add_action(self.action_metadata_converter, add_to_toolbar=self.full_toolbar) def _create_field_mapping_action(self): """Create action for showing field mapping dialog.""" icon = resources_path('img', 'icons', 'show-mapping-tool.svg') self.action_field_mapping = QAction( QIcon(icon), self.tr('InaSAFE Field Mapping Tool'), self.iface.mainWindow()) self.action_field_mapping.setStatusTip( self.tr('Assign field mapping to layer.')) self.action_field_mapping.setWhatsThis( self.tr('Use this tool to assign field mapping in layer.')) self.action_field_mapping.setEnabled(False) self.action_field_mapping.triggered.connect(self.show_field_mapping) self.add_action(self.action_field_mapping, add_to_toolbar=self.full_toolbar) def _create_multi_exposure_action(self): """Create action for showing the multi exposure tool.""" self.action_multi_exposure = QAction( QIcon(resources_path('img', 'icons', 'show-multi-exposure.svg')), self.tr('InaSAFE Multi Exposure Tool'), self.iface.mainWindow()) self.action_multi_exposure.setStatusTip( self.tr('Open the multi exposure tool.')) self.action_multi_exposure.setWhatsThis( self.tr('Open the multi exposure tool.')) self.action_multi_exposure.setEnabled(True) self.action_multi_exposure.triggered.connect(self.show_multi_exposure) self.add_action(self.action_multi_exposure, add_to_toolbar=self.full_toolbar) def _create_add_petabencana_layer_action(self): """Create action for import OSM Dialog.""" icon = resources_path('img', 'icons', 'add-petabencana-layer.svg') self.action_add_petabencana_layer = QAction( QIcon(icon), self.tr('Add PetaBencana Flood Layer'), self.iface.mainWindow()) self.action_add_petabencana_layer.setStatusTip( self.tr('Add PetaBencana Flood Layer')) self.action_add_petabencana_layer.setWhatsThis( self.tr('Use this to add a PetaBencana layer to your map. ' 'It needs internet access to function.')) self.action_add_petabencana_layer.triggered.connect( self.add_petabencana_layer) self.add_action(self.action_add_petabencana_layer, add_to_toolbar=self.full_toolbar) def _create_rubber_bands_action(self): """Create action for toggling rubber bands.""" icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg') self.action_toggle_rubberbands = QAction( QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow()) message = self.tr('Toggle rubber bands showing scenario extents.') self.action_toggle_rubberbands.setStatusTip(message) self.action_toggle_rubberbands.setWhatsThis(message) # Set initial state self.action_toggle_rubberbands.setCheckable(True) flag = setting('showRubberBands', False, expected_type=bool) self.action_toggle_rubberbands.setChecked(flag) # noinspection PyUnresolvedReferences self.action_toggle_rubberbands.triggered.connect( self.dock_widget.toggle_rubber_bands) self.add_action(self.action_toggle_rubberbands) def _create_analysis_extent_action(self): """Create action for analysis extent dialog.""" icon = resources_path('img', 'icons', 'set-extents-tool.svg') self.action_extent_selector = QAction(QIcon(icon), self.tr('Set Analysis Area'), self.iface.mainWindow()) self.action_extent_selector.setStatusTip( self.tr('Set the analysis area for InaSAFE')) self.action_extent_selector.setWhatsThis( self.tr('Set the analysis area for InaSAFE')) self.action_extent_selector.triggered.connect( self.show_extent_selector) self.add_action(self.action_extent_selector) def _create_test_layers_action(self): """Create action for adding layers (developer mode, non final only).""" if self.hide_developer_buttons: return icon = resources_path('img', 'icons', 'add-test-layers.svg') self.action_add_layers = QAction(QIcon(icon), self.tr('Add Test Layers'), self.iface.mainWindow()) self.action_add_layers.setStatusTip(self.tr('Add test layers')) self.action_add_layers.setWhatsThis(self.tr('Add test layers')) self.action_add_layers.triggered.connect(self.add_test_layers) self.add_action(self.action_add_layers) def _create_run_test_action(self): """Create action for running tests (developer mode, non final only).""" if self.hide_developer_buttons: return default_package = str(setting('testPackage', 'safe', expected_type=str)) msg = self.tr('Run tests in %s' % default_package) self.test_button = QToolButton() self.test_button.setMenu(QMenu()) self.test_button.setPopupMode(QToolButton.MenuButtonPopup) icon = resources_path('img', 'icons', 'run-tests.svg') self.action_run_tests = QAction(QIcon(icon), msg, self.iface.mainWindow()) self.action_run_tests.setStatusTip(msg) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.triggered.connect(self.run_tests) self.test_button.menu().addAction(self.action_run_tests) self.test_button.setDefaultAction(self.action_run_tests) self.action_select_package = QAction(QIcon(icon), self.tr('Select package'), self.iface.mainWindow()) self.action_select_package.setStatusTip(self.tr('Select Test Package')) self.action_select_package.setWhatsThis(self.tr('Select Test Package')) self.action_select_package.triggered.connect(self.select_test_package) self.test_button.menu().addAction(self.action_select_package) self.toolbar.addWidget(self.test_button) self.add_action(self.action_run_tests, add_to_toolbar=False) self.add_action(self.action_select_package, add_to_toolbar=False) def _create_dock(self): """Create dockwidget and tabify it with the legend.""" # Import dock here as it needs to be imported AFTER i18n is set up from safe.gui.widgets.dock import Dock self.dock_widget = Dock(self.iface) self.dock_widget.setObjectName('InaSAFE-Dock') self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget) legend_tab = self.iface.mainWindow().findChild(QApplication, 'Legend') if legend_tab: self.iface.mainWindow().tabifyDockWidget(legend_tab, self.dock_widget) self.dock_widget.raise_() # noinspection PyPep8Naming def initGui(self): """Gui initialisation procedure (for QGIS plugin api). .. note:: Don't change the name of this method from initGui! This method is called by QGIS and should be used to set up any graphical user interface elements that should appear in QGIS by default (i.e. before the user performs any explicit action with the plugin). """ self.toolbar = self.iface.addToolBar('InaSAFE') self.toolbar.setObjectName('InaSAFEToolBar') self.dock_widget = None # Now create the actual dock self._create_dock() # And all the menu actions # Configuration Group self._create_dock_toggle_action() self._create_options_dialog_action() self._create_minimum_needs_options_action() self._create_analysis_extent_action() self._create_rubber_bands_action() self._add_spacer_to_menu() self._create_keywords_wizard_action() self._create_analysis_wizard_action() self._add_spacer_to_menu() self._create_field_mapping_action() self._create_multi_exposure_action() self._create_metadata_converter_action() self._create_osm_downloader_action() self._create_add_osm_layer_action() self._create_add_petabencana_layer_action() self._create_geonode_uploader_action() self._create_shakemap_converter_action() self._create_minimum_needs_action() self._create_multi_buffer_action() self._create_test_layers_action() self._create_run_test_action() self._add_spacer_to_menu() self._create_batch_runner_action() self._create_save_scenario_action() self._add_spacer_to_menu() self._create_show_definitions_action() # Hook up a slot for when the dock is hidden using its close button # or view-panels # self.dock_widget.visibilityChanged.connect(self.toggle_inasafe_action) # Also deal with the fact that on start of QGIS dock may already be # hidden. self.action_dock.setChecked(self.dock_widget.isVisible()) self.iface.initializationCompleted.connect( partial(self.show_welcome_message)) def _add_spacer_to_menu(self): """Create a spacer to the menu to separate action groups.""" separator = QAction(self.iface.mainWindow()) separator.setSeparator(True) self.iface.addPluginToMenu(self.tr('InaSAFE'), separator) @staticmethod def clear_modules(): """Unload inasafe functions and try to return QGIS to before InaSAFE. .. todo:: I think this function can be removed. TS. """ # next lets force remove any inasafe related modules modules = [] for module in sys.modules: if 'inasafe' in module: # Check if it is really one of our modules i.e. exists in the # plugin directory tokens = module.split('.') path = '' for myToken in tokens: path += os.path.sep + myToken parent = os.path.abspath( os.path.join(__file__, os.path.pardir, os.path.pardir)) full_path = os.path.join(parent, path + '.py') if os.path.exists(os.path.abspath(full_path)): LOGGER.debug('Removing: %s' % module) modules.append(module) for module in modules: del (sys.modules[module]) for module in sys.modules: if 'inasafe' in module: print(module) # Lets also clean up all the path additions that were made package_path = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir)) LOGGER.debug('Path to remove: %s' % package_path) # We use a list comprehension to ensure duplicate entries are removed LOGGER.debug(sys.path) sys.path = [y for y in sys.path if package_path not in y] LOGGER.debug(sys.path) def unload(self): """GUI breakdown procedure (for QGIS plugin api). .. note:: Don't change the name of this method from unload! This method is called by QGIS and should be used to *remove* any graphical user interface elements that should appear in QGIS. """ # Remove the plugin menu item and icon if self.wizard: self.wizard.deleteLater() for myAction in self.actions: self.iface.removePluginMenu(self.tr('InaSAFE'), myAction) self.iface.removeToolBarIcon(myAction) self.iface.removeCustomActionForLayerType(myAction) self.iface.mainWindow().removeDockWidget(self.dock_widget) self.iface.mainWindow().removeToolBar(self.toolbar) self.dock_widget.setVisible(False) self.dock_widget.destroy() self.iface.currentLayerChanged.disconnect(self.layer_changed) # Unload QGIS expressions loaded by the plugin. for qgis_expression in list(qgis_expressions().keys()): QgsExpression.unregisterFunction(qgis_expression) def toggle_inasafe_action(self, checked): """Check or un-check the toggle inaSAFE toolbar button. This slot is called when the user hides the inaSAFE panel using its close button or using view->panels. :param checked: True if the dock should be shown, otherwise False. :type checked: bool """ self.action_dock.setChecked(checked) # Run method that performs all the real work def toggle_dock_visibility(self): """Show or hide the dock widget.""" if self.dock_widget.isVisible(): self.dock_widget.setVisible(False) else: self.dock_widget.setVisible(True) self.dock_widget.raise_() def add_test_layers(self): """Add standard test layers.""" from safe.test.utilities import load_standard_layers load_standard_layers() rect = QgsRectangle(106.806, -6.195, 106.837, -6.167) self.iface.mapCanvas().setExtent(rect) def select_test_package(self): """Select the test package.""" default_package = 'safe' user_package = str( setting('testPackage', default_package, expected_type=str)) test_package, _ = QInputDialog.getText( self.iface.mainWindow(), self.tr('Select the python test package'), self.tr('Select the python test package'), QLineEdit.Normal, user_package) if test_package == '': test_package = default_package set_setting('testPackage', test_package) msg = self.tr('Run tests in %s' % test_package) self.action_run_tests.setWhatsThis(msg) self.action_run_tests.setText(msg) def run_tests(self): """Run unit tests in the python console.""" from qgis.PyQt.QtWidgets import QDockWidget main_window = self.iface.mainWindow() action = main_window.findChild(QAction, 'mActionShowPythonDialog') action.trigger() package = str(setting('testPackage', 'safe', expected_type=str)) for child in main_window.findChildren(QDockWidget, 'PythonConsole'): if child.objectName() == 'PythonConsole': child.show() for widget in child.children(): if 'PythonConsoleWidget' in str(widget.__class__): # print "Console widget found" shell = widget.shell shell.runCommand( 'from inasafe.test_suite import test_package') shell.runCommand('test_package(\'%s\')' % package) break def show_extent_selector(self): """Show the extent selector widget for defining analysis extents.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.extent_selector_dialog import ExtentSelectorDialog widget = ExtentSelectorDialog( self.iface, self.iface.mainWindow(), extent=self.dock_widget.extent.user_extent, crs=self.dock_widget.extent.crs) widget.clear_extent.connect( self.dock_widget.extent.clear_user_analysis_extent) widget.extent_defined.connect( self.dock_widget.define_user_analysis_extent) # This ensures that run button state is updated on dialog close widget.extent_selector_closed.connect( self.dock_widget.validate_impact_function) # Needs to be non modal to support hide -> interact with map -> show widget.show() # non modal def show_minimum_needs(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_calculator_dialog import ( NeedsCalculatorDialog) dialog = NeedsCalculatorDialog(self.iface.mainWindow()) dialog.exec_() def show_minimum_needs_configuration(self): """Show the minimum needs dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.minimum_needs.needs_manager_dialog import ( NeedsManagerDialog) dialog = NeedsManagerDialog(parent=self.iface.mainWindow(), dock=self.dock_widget) dialog.exec_() # modal def show_options(self): """Show the options dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog dialog = OptionsDialog(iface=self.iface, parent=self.iface.mainWindow()) dialog.show_option_dialog() if dialog.exec_(): # modal self.dock_widget.read_settings() from safe.gui.widgets.message import getting_started_message send_static_message(self.dock_widget, getting_started_message()) # Issue #4734, make sure to update the combobox after update the # InaSAFE option self.dock_widget.get_layers() def show_welcome_message(self): """Show the welcome message.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.options_dialog import OptionsDialog # Do not show by default show_message = False previous_version = StrictVersion(setting('previous_version')) current_version = StrictVersion(inasafe_version) # Set previous_version to the current inasafe_version set_setting('previous_version', inasafe_version) if setting('always_show_welcome_message', expected_type=bool): # Show if it the setting said so show_message = True elif previous_version < current_version: # Always show if the user installed new version show_message = True # Allow to disable welcome message when running automated tests if os.environ.get('INASAFE_DISABLE_WELCOME_MESSAGE', False): show_message = False if show_message: dialog = OptionsDialog(iface=self.iface, parent=self.iface.mainWindow()) dialog.show_welcome_dialog() if dialog.exec_(): # modal self.dock_widget.read_settings() def show_keywords_wizard(self): """Show the keywords creation wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog if self.iface.activeLayer() is None: return # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since the IFCW is non modal if not self.wizard: self.wizard = WizardDialog(self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_keywords_creation_mode() self.wizard.exec_() # modal def show_function_centric_wizard(self): """Show the function centric wizard.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.wizard.wizard_dialog import WizardDialog # Don't break an existing wizard session if accidentally clicked if self.wizard and self.wizard.isVisible(): return # Prevent spawning multiple copies since it is non modal if not self.wizard: self.wizard = WizardDialog(self.iface.mainWindow(), self.iface, self.dock_widget) self.wizard.set_function_centric_mode() # non-modal in order to hide for selecting user extent self.wizard.show() def show_shakemap_importer(self): """Show the converter dialog.""" # import here only so that it is AFTER i18n set up from safe.gui.tools.shake_grid.shakemap_converter_dialog import ( ShakemapConverterDialog) dialog = ShakemapConverterDialog(self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal def show_multi_buffer(self): """Show the multi buffer tool.""" from safe.gui.tools.multi_buffer_dialog import (MultiBufferDialog) dialog = MultiBufferDialog(self.iface.mainWindow(), self.iface, self.dock_widget) dialog.exec_() # modal def show_osm_downloader(self): """Show the OSM buildings downloader dialog.""" from safe.gui.tools.osm_downloader_dialog import OsmDownloaderDialog dialog = OsmDownloaderDialog(self.iface.mainWindow(), self.iface) # otherwise dialog is never deleted dialog.setAttribute(Qt.WA_DeleteOnClose, True) dialog.show() # non modal def show_geonode_uploader(self): """Show the Geonode uploader dialog.""" from safe.gui.tools.geonode_uploader import GeonodeUploaderDialog dialog = GeonodeUploaderDialog(self.iface.mainWindow()) dialog.show() # non modal def add_osm_layer(self): """Add OSM tile layer to the map. This uses a gdal wrapper around the OSM tile service - see the WorldOSM.gdal file for how it is constructed. """ path = resources_path('osm', 'WorldOSM.gdal') layer = QgsRasterLayer(path, self.tr('OpenStreetMap')) project = QgsProject.instance() # Try to add it as the last layer in the list # False flag prevents layer being added to legend project.addMapLayer(layer, False) root = QgsProject.instance().layerTreeRoot() index = len(root.findLayers()) + 1 # LOGGER.info('Inserting layer %s at position %s' % ( # layer.source(), index)) root.insertLayer(index, layer) project.addMapLayer(layer) def show_definitions(self): """Show InaSAFE Definitions (a report showing all key metadata).""" from safe.utilities.help import show_help from safe.gui.tools.help import definitions_help show_help(definitions_help.definitions_help()) def show_field_mapping(self): """Show InaSAFE Field Mapping.""" from safe.gui.tools.field_mapping_dialog import FieldMappingDialog dialog = FieldMappingDialog( parent=self.iface.mainWindow(), iface=self.iface, ) if dialog.exec_(): # modal LOGGER.debug('Show field mapping accepted') self.dock_widget.layer_changed(self.iface.activeLayer()) else: LOGGER.debug('Show field mapping not accepted') def show_metadata_converter(self): """Show InaSAFE Metadata Converter.""" from safe.gui.tools.metadata_converter_dialog import ( MetadataConverterDialog) dialog = MetadataConverterDialog( parent=self.iface.mainWindow(), iface=self.iface, ) dialog.exec_() def show_multi_exposure(self): """Show InaSAFE Multi Exposure.""" from safe.gui.tools.multi_exposure_dialog import MultiExposureDialog dialog = MultiExposureDialog(self.iface.mainWindow(), self.iface) dialog.exec_() # modal def add_petabencana_layer(self): """Add petabencana layer to the map. This uses the PetaBencana API to fetch the latest floods in JK. See https://data.petabencana.id/floods """ from safe.gui.tools.peta_bencana_dialog import PetaBencanaDialog dialog = PetaBencanaDialog(self.iface.mainWindow(), self.iface) dialog.show() # non modal def show_batch_runner(self): """Show the batch runner dialog.""" from safe.gui.tools.batch.batch_dialog import BatchDialog dialog = BatchDialog(parent=self.iface.mainWindow(), iface=self.iface, dock=self.dock_widget) dialog.exec_() # modal def save_scenario(self): """Save current scenario to text file.""" from safe.gui.tools.save_scenario import SaveScenarioDialog dialog = SaveScenarioDialog(iface=self.iface, dock=self.dock_widget) dialog.save_scenario() def layer_changed(self, layer): """Enable or disable keywords editor icon when active layer changes. :param layer: The layer that is now active. :type layer: QgsMapLayer """ if not layer: enable_keyword_wizard = False elif not hasattr(layer, 'providerType'): enable_keyword_wizard = False elif layer.providerType() == 'wms': enable_keyword_wizard = False else: enable_keyword_wizard = True try: if layer: if is_raster_layer(layer): enable_field_mapping_tool = False else: keywords = KeywordIO().read_keywords(layer) keywords_version = keywords.get('keyword_version') if not keywords_version: supported = False else: supported = ( is_keyword_version_supported(keywords_version)) if not supported: enable_field_mapping_tool = False else: layer_purpose = keywords.get('layer_purpose') if not layer_purpose: enable_field_mapping_tool = False else: if layer_purpose == layer_purpose_exposure['key']: layer_subcategory = keywords.get('exposure') elif layer_purpose == layer_purpose_hazard['key']: layer_subcategory = keywords.get('hazard') else: layer_subcategory = None field_groups = get_field_groups( layer_purpose, layer_subcategory) if len(field_groups) == 0: # No field group, disable field mapping tool. enable_field_mapping_tool = False else: enable_field_mapping_tool = True else: enable_field_mapping_tool = False except (KeywordNotFoundError, NoKeywordsFoundError, MetadataReadError): # No keywords, disable field mapping tool. enable_field_mapping_tool = False self.action_keywords_wizard.setEnabled(enable_keyword_wizard) self.action_field_mapping.setEnabled(enable_field_mapping_tool) def shortcut_f7(self): """Executed when user press F7 - will show the shakemap importer.""" self.show_shakemap_importer()
class GimpSelectionFeaturePlugin(QObject): def __init__(self, iface): super().__init__() self.iface = iface self.name = u"&Gimp Selection Feature" self.dock = self.exitsPluginGimp = None self.translate = Translate( 'gimpselectionfeature' ) def initGui(self): def setExistsPluginGimp(): def getDirPluginGimp(): dirPlugin = None mask = r".*gimp.[0-9]+.[0-9]+/%s" % nameDirPlugin # Linux Format for root, dirs, files in os.walk( dirHome ): if re.match( mask, root.replace('\\', '/'), re.IGNORECASE ): dirPlugin = root break return dirPlugin def copyNewPlugin(): shutil.copy2( gimpPlugin, gimpPluginInstall ) if sys.platform != 'win32': # Add executable st = os.stat( gimpPluginInstall ) os.chmod( gimpPluginInstall, st.st_mode | stat.S_IEXEC ) dirHome = os.path.expanduser('~') nameDirPlugin = "plug-ins" dirPluginGimp = getDirPluginGimp() if dirPluginGimp is None: msg = "Not found diretory 'GIMP' or 'GIMP {}' in '{}'".format( nameDirPlugin, dirHome ) self.exitsPluginGimp = { 'isOk': False, 'msg': msg } return namePlugin = 'socket_server_selection.py' gimpPlugin = os.path.join( os.path.dirname(__file__), namePlugin ) gimpPluginInstall = os.path.join( dirPluginGimp, namePlugin ) if not os.path.exists( gimpPluginInstall ) or not filecmp.cmp( gimpPlugin, gimpPluginInstall ): copyNewPlugin() self.exitsPluginGimp = { 'isOk': True } name = "Gimp Selection Feature" about = QCoreApplication.translate('GimpSelectionFeature', 'Adding selected area in GIMP how a feature in shapefile') icon = QIcon( os.path.join( os.path.dirname(__file__), 'gimpselectionfeature.svg' ) ) self.action = QAction( icon, name, self.iface.mainWindow() ) self.action.setObjectName( name.replace(' ', '') ) self.action.setWhatsThis( about ) self.action.setStatusTip( about ) self.action.setCheckable( True ) self.action.triggered.connect( self.run ) self.iface.addRasterToolBarIcon( self.action ) self.iface.addPluginToRasterMenu( self.name, self.action ) setExistsPluginGimp() if not self.exitsPluginGimp['isOk']: return self.dock = DockWidgetGimpSelectionFeature( self.iface ) self.iface.addDockWidget( Qt.RightDockWidgetArea , self.dock ) self.dock.visibilityChanged.connect( self.dockVisibilityChanged ) def unload(self): self.iface.removeRasterToolBarIcon( self.action ) self.iface.removePluginRasterMenu( self.name, self.action ) if self.exitsPluginGimp['isOk']: self.dock.close() del self.dock self.dock = None del self.action @pyqtSlot() def run(self): if not self.exitsPluginGimp['isOk']: ( t, m ) = ( GimpSelectionFeature.nameModulus, self.exitsPluginGimp['msg'] ) self.iface.messageBar().pushMessage( t, m, Qgis.Critical, 5 ) self.action.setChecked( False ) return if self.dock.isVisible(): self.dock.hide() else: self.dock.show() @pyqtSlot(bool) def dockVisibilityChanged(self, visible): self.action.setChecked( visible )
class LockZoomToTiles: def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.epsg3857 = QgsCoordinateReferenceSystem('EPSG:3857') self.epsg4326 = QgsCoordinateReferenceSystem('EPSG:4326') self.islocking = False def initGui(self): '''Initialize Lock Zoom to Tiles GUI.''' icon = QIcon() icon.addFile(os.path.dirname(__file__) + "/images/zoomUnlocked.png", state=QIcon.Off) icon.addFile(os.path.dirname(__file__) + "/images/zoomLocked.png", state=QIcon.On) self.action = QAction(icon, "Lock zoom scale", self.iface.mainWindow()) self.action.setObjectName('lockZoom') self.action.triggered.connect(self.lockIt) self.action.setCheckable(True) self.iface.addPluginToMenu("Lock zoom to tile scale", self.action) self.iface.addToolBarIcon(self.action) icon = QIcon(os.path.dirname(__file__) + '/images/help.png') self.helpAction = QAction(icon, "Help", self.iface.mainWindow()) self.helpAction.triggered.connect(self.help) self.iface.addPluginToMenu('Lock zoom to tile scale', self.helpAction) self.checkCrs() self.canvas.destinationCrsChanged.connect(self.checkCrs) self.canvas.layersChanged.connect(self.checkCrs) def unload(self): '''Unload from the QGIS interface''' self.iface.removePluginMenu('Lock zoom to tile scale', self.action) self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu("Lock zoom to tile scale", self.helpAction) self.canvas.destinationCrsChanged.disconnect(self.checkCrs) if self.islocking == True: try: self.canvas.scaleChanged.disconnect(self.lockIt) except Exception: pass def help(self): '''Display a help page''' url = QUrl.fromLocalFile(os.path.dirname(__file__) + "/index.html").toString() webbrowser.open(url, new=2) def lockIt(self): '''Set the focus of the copy coordinate tool''' if self.action.isChecked(): self.zoomTo() if self.islocking == False: self.islocking = True self.canvas.scaleChanged.connect(self.zoomTo) self.action.setText("Unlock zoom scale") self.action.setIconText("Unlock zoom scale") else: if self.islocking == True: self.canvas.scaleChanged.disconnect(self.zoomTo) self.islocking = False self.action.setText("Lock zoom scale") self.action.setIconText("Lock zoom scale") def zoomTo(self): crs = self.canvas.mapSettings().destinationCrs() mupp = self.canvas.mapUnitsPerPixel() if crs == self.epsg3857: r = 0 for i in range(0, len(r3857)): r = i if r3857[i] > mupp: if i > 0 and (r3857[i] - mupp > mupp - r3857[i - 1]): r = i - 1 break if not math.isclose(r3857[r], mupp, rel_tol=1e-5): self.canvas.zoomByFactor(r3857[r] / self.canvas.mapUnitsPerPixel()) else: r = 0 for i in range(0, len(r4326)): r = i if r4326[i] > mupp: if i > 0 and (r4326[i] - mupp > mupp - r4326[i - 1]): r = i - 1 break if not math.isclose(r4326[r], mupp, rel_tol=1e-5): self.canvas.zoomByFactor(r4326[r] / self.canvas.mapUnitsPerPixel()) def checkCrs(self): crs = self.canvas.mapSettings().destinationCrs() numlayers = self.canvas.layerCount() if (crs == self.epsg3857 or crs == self.epsg4326) and numlayers > 0: self.action.setEnabled(True) else: self.action.setEnabled(False) self.action.setChecked(False) self.lockIt()
class ProcessingPlugin: def __init__(self, iface): self.iface = iface self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider( self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) Processing.initialize() def initGui(self): self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction( self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction( self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', 'Graphical &Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction( self.modelerAction, QKeySequence('Ctrl+Alt+M').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(pluginPath, 'images', 'history.svg')), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction( self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction( self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect( self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() def openProcessingOptions(self): self.iface.showOptionsDialog(self.iface.mainWindow(), currentPage='processingOptions') def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.iface.attributesToolBar().removeAction(self.toolboxAction) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.toolbox.deleteLater() self.menu.deleteLater() # delete temporary output files folder = QgsProcessingUtils.tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) # also delete temporary help files folder = tempHelpFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) self.iface.deregisterLocatorFilter(self.locator_filter) self.iface.unregisterCustomDropHandler(self.drop_handler) QgsApplication.dataItemProviderRegistry().removeProvider( self.item_provider) removeMenus() Processing.deinitialize() def openToolbox(self, show): self.toolbox.setUserVisible(show) def toolboxVisibilityChanged(self, visible): self.toolboxAction.setChecked(visible) def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById( 'model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class Plugin: def __init__(self, iface: QgisInterface) -> None: print('__init__') self.iface = iface self.first_start = True self.initProcessing() def initProcessing(self) -> None: print('initProvider') self.provider = Provider() QgsApplication.processingRegistry().addProvider(self.provider) def initGui(self) -> None: print('initGui') """self.toolButton = QToolButton() self.toolButton.setMenu(QMenu()) self.toolButton.setPopupMode(QToolButton.MenuButtonPopup) self.toolBtnAction = self.iface.addToolBarWidget(self.toolButton) self.actionRun = QAction( QIcon(os.path.join(os.path.dirname(__file__), "icon.png")), 'Bicycle Planner', self.iface.mainWindow(), ) self.actionRun.setToolTip('Bicycle Planner') self.actionRun.setText('Bicycle Planner') self.iface.addPluginToMenu('&Bicyle Planner', self.actionRun)""" # create action that will start plugin configuration self.action = QAction( icon, "Bicycle Planner", self.iface.mainWindow(), ) self.action.setObjectName("testAction") self.action.setWhatsThis("Configuration for test plugin") self.action.setStatusTip("This is status tip") self.action.triggered.connect(self.run) # add toolbar button and menu item self.iface.addToolBarIcon(self.action) self.iface.addPluginToMenu("&Bicycle Planner", self.action) # connect to signal renderComplete which is emitted when canvas # rendering is done self.iface.mapCanvas().renderComplete.connect(self.renderTest) def unload(self): """for action in [ self.actionRun, ]: self.iface.removePluginMenu('&Bicyle Planner', action) self.iface.removeToolBarIcon(action) self.iface.unregisterMainWindowAction(action) self.iface.removeToolBarIcon(self.toolBtnAction)""" # remove the plugin menu item and icon self.iface.removePluginMenu("&Bicycle Planner", self.action) self.iface.removeToolBarIcon(self.action) # disconnect form signal of the canvas self.iface.mapCanvas().renderComplete.disconnect(self.renderTest) QgsApplication.processingRegistry().removeProvider(self.provider) def run(self): print("BicyclePlanner: run called!") QgsMessageLog.logMessage('Fooooooo') # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start: self.first_start = False self.dlg = Dialog() # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass def renderTest(self, painter): # use painter for drawing to map canvas # print("TestPlugin: renderTest called!") pass
class ProcessingPlugin(object): def __init__(self, iface): self.iface = iface self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider( self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) Processing.initialize() def initGui(self): self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() resultsList.resultAdded.connect(self.resultsDock.fillTree) self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = self.toolbox.toggleViewAction() self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.toolboxAction.setText(self.tr('&Toolbox')) self.iface.registerMainWindowAction(self.toolboxAction, 'Ctrl+Alt+T') self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), self.tr('Graphical &Modeler...'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, 'Ctrl+Alt+M') self.menu.addAction(self.modelerAction) self.historyAction = QAction( QIcon(os.path.join(cmd_folder, 'images', 'history.svg')), self.tr('&History...'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, 'Ctrl+Alt+H') self.menu.addAction(self.historyAction) self.resultsAction = self.resultsDock.toggleViewAction() self.resultsAction.setObjectName('resultsAction') self.resultsAction.setIcon( QgsApplication.getThemeIcon("/processingResult.svg")) self.resultsAction.setText(self.tr('&Results Viewer')) self.iface.registerMainWindowAction(self.resultsAction, 'Ctrl+Alt+R') self.menu.addAction(self.resultsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() def unload(self): self.toolbox.setVisible(False) self.iface.removeDockWidget(self.toolbox) self.resultsDock.setVisible(False) self.iface.removeDockWidget(self.resultsDock) self.menu.deleteLater() # delete temporary output files folder = QgsProcessingUtils.tempFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) # also delete temporary help files folder = tempHelpFolder() if QDir(folder).exists(): shutil.rmtree(folder, True) self.iface.unregisterMainWindowAction(self.toolboxAction) self.iface.unregisterMainWindowAction(self.modelerAction) self.iface.unregisterMainWindowAction(self.historyAction) self.iface.unregisterMainWindowAction(self.resultsAction) self.iface.unregisterOptionsWidgetFactory(self.options_factory) self.iface.deregisterLocatorFilter(self.locator_filter) self.iface.unregisterCustomDropHandler(self.drop_handler) QgsApplication.dataItemProviderRegistry().removeProvider( self.item_provider) removeMenus() Processing.deinitialize() def openToolbox(self): if self.toolbox.isVisible(): self.toolbox.hide() else: self.toolbox.show() def openModeler(self): dlg = ModelerDialog() dlg.update_model.connect(self.updateModel) dlg.show() def updateModel(self): model_provider = QgsApplication.processingRegistry().providerById( 'model') model_provider.refreshAlgorithms() def openResults(self): if self.resultsDock.isVisible(): self.resultsDock.hide() else: self.resultsDock.show() def openHistory(self): dlg = HistoryDialog() dlg.exec_() def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
class ProfilesPlugin(object): def __init__(self, iface): self.iface = iface QSettings().setValue('/UI/Customization/enabled', False) try: from profiles.tests import testerplugin from qgistester.tests import addTestModule addTestModule(testerplugin, 'Profiles plugin') except: pass self.userProfileAction = None self.profilesMenu = None iface.initializationCompleted.connect(self.initProfile) def unload(self): if self.profilesMenu is not None: self.profilesMenu.deleteLater() self.iface.removePluginMenu(self.tr('Profiles'), self.autoloadAction) self.iface.removePluginMenu(self.tr('Profiles'), self.saveProfileAction) try: from profiles.tests import testerplugin from qgistester.tests import removeTestModule removeTestModule(testerplugin, 'Profiles plugin') except: pass saveCurrentPluginState() def initGui(self): self.addMenus() def addMenus(self): if self.profilesMenu is not None: self.profilesMenu.clear() self.actions = defaultdict(list) settings = QSettings() defaultProfile = settings.value('profilesplugin/LastProfile', 'Default', str) autoLoad = settings.value('profilesplugin/AutoLoad', False, bool) for k, v in profiles.items(): action = QAction(k, self.iface.mainWindow()) action.setCheckable(True) if k == defaultProfile and autoLoad: action.setChecked(True) action.triggered.connect(lambda _, menuName=k: self.applyProfile(menuName)) action.setObjectName('mProfilesPlugin_' + k) self.actions[v.group].append(action) actions = self.iface.mainWindow().menuBar().actions() settingsMenu = None self.profilesGroup = QActionGroup(self.iface.mainWindow()) if self.profilesMenu is None: for action in actions: if action.menu().objectName() == 'mSettingsMenu': settingsMenu = action.menu() self.profilesMenu = QMenu(settingsMenu) self.profilesMenu.setObjectName('mProfilesPlugin') self.profilesMenu.setTitle(self.tr('Profiles')) settingsMenu.addMenu(self.profilesMenu) break if self.profilesMenu is not None: for k,v in self.actions.items(): submenu = QMenu(self.profilesMenu) submenu.setObjectName('mProfilesPlugin_submenu_' + k) submenu.setTitle(k) for action in v: self.profilesGroup.addAction(action) submenu.addAction(action) self.profilesMenu.addMenu(submenu) self.profilesMenu.addSeparator() settings = QSettings() def _setAutoLoad(): settings.setValue('profilesplugin/AutoLoad', self.autoloadAction.isChecked()) self.autoloadAction = QAction(self.tr('Auto-load last profile on QGIS start'), iface.mainWindow()) self.autoloadAction.setCheckable(True) autoLoad = settings.value('profilesplugin/AutoLoad', False, bool) self.autoloadAction.setChecked(autoLoad) self.autoloadAction.setObjectName('mProfilesPluginAutoLoad') self.autoloadAction.triggered.connect(_setAutoLoad) self.profilesMenu.addAction(self.autoloadAction) self.saveProfileAction = QAction(self.tr('Profiles manager...'), self.iface.mainWindow()) self.saveProfileAction.setObjectName('mProfilesPluginProfilesManager') self.saveProfileAction.triggered.connect(self.saveProfile) self.profilesMenu.addAction(self.saveProfileAction) self.showHelpAction = QAction(self.tr('Help'), self.iface.mainWindow()) self.showHelpAction.setIcon(QgsApplication.getThemeIcon('/mActionHelpContents.svg')) self.showHelpAction.setObjectName('mProfilesPluginShowHelp') self.showHelpAction.triggered.connect(self.showHelp) self.profilesMenu.addAction(self.showHelpAction) def applyProfile(self, name): profile = profiles.get(name) applyProfile(profile) def initProfile(self): settings = QSettings() autoLoad = settings.value('profilesplugin/AutoLoad', False, bool) if autoLoad: profileName = settings.value('profilesplugin/LastProfile', '', str) if profileName in profiles: profile = profiles[profileName] if not profile.hasToInstallPlugins(): applyProfile(profile, False) def saveProfile(self): dlg = ProfileManager(iface.mainWindow()) dlg.exec_() def showHelp(self): if not QDesktopServices.openUrl( QUrl('file://{}'.format(os.path.join(pluginPath, 'docs', 'html', 'index.html')))): QMessageBox.warning(None, self.tr('Error'), self.tr('Can not open help URL in browser')) def tr(self, text): return QCoreApplication.translate('Profiles', text)
class GwParentMapTool(QgsMapTool): def __init__(self, icon_path, text, toolbar, action_group, iface, settings, controller, plugin_dir): self.iface = iface self.settings = settings self.controller = controller self.plugin_dir = plugin_dir self.show_help = bool(int(self.settings.value('status/show_help', 1))) self.layer_arc = None self.layer_connec = None self.layer_gully = None self.layer_node = None self.snapper_manager = SnappingConfigManager(self.iface) self.snapper_manager.controller = controller self.canvas = iface.mapCanvas() super().__init__(self.canvas) icon = None if os.path.exists(icon_path): icon = QIcon(icon_path) self.action = None if icon is None: self.action = QAction(text, action_group) else: self.action = QAction(icon, text, action_group) self.action.setObjectName(text) self.action.setCheckable(True) self.action.triggered.connect(self.clicked_event) # Change map tool cursor self.cursor = QCursor() self.cursor.setShape(Qt.CrossCursor) # Get default cursor # noinspection PyCallingNonCallable self.std_cursor = self.parent().cursor() # Set default vertex marker color = QColor(255, 100, 255) self.vertex_marker = QgsVertexMarker(self.canvas) self.vertex_marker.setIconType(QgsVertexMarker.ICON_CIRCLE) self.vertex_marker.setColor(color) self.vertex_marker.setIconSize(15) self.vertex_marker.setPenWidth(3) # Set default rubber band color_selection = QColor(254, 178, 76, 63) self.rubber_band = QgsRubberBand(self.canvas, 2) self.rubber_band.setColor(color) self.rubber_band.setFillColor(color_selection) self.rubber_band.setWidth(1) self.reset() self.force_active_layer = True toolbar.addAction(self.action) self.setAction(self.action) def clicked_event(self): self.controller.prev_maptool = self.iface.mapCanvas().mapTool() if not (self == self.iface.mapCanvas().mapTool()): self.iface.mapCanvas().setMapTool(self) else: self.iface.mapCanvas().unsetMapTool(self) def deactivate(self): # Uncheck button self.action.setChecked(False) # Restore previous snapping self.snapper_manager.recover_snapping_options() # Enable snapping self.snapper_manager.enable_snapping(True) # Recover cursor self.canvas.setCursor(self.std_cursor) # Remove highlight self.vertex_marker.hide() def canvasMoveEvent(self, event): # Make sure active layer is always 'v_edit_node' cur_layer = self.iface.activeLayer() if cur_layer != self.layer_node and self.force_active_layer: self.iface.setActiveLayer(self.layer_node) # Hide highlight and get coordinates self.vertex_marker.hide() event_point = self.snapper_manager.get_event_point(event) # Snapping result = self.snapper_manager.snap_to_current_layer(event_point) if self.snapper_manager.result_is_valid(): self.snapper_manager.add_marker(result, self.vertex_marker) def recover_previus_maptool(self): if self.controller.prev_maptool: self.iface.mapCanvas().setMapTool(self.controller.prev_maptool) self.controller.prev_maptool = None def remove_vertex(self): """ Remove vertex_marker from canvas""" vertex_items = [i for i in self.iface.mapCanvas().scene().items() if issubclass(type(i), QgsVertexMarker)] for ver in vertex_items: if ver in self.iface.mapCanvas().scene().items(): if self.vertex_marker == ver: self.iface.mapCanvas().scene().removeItem(ver) def set_action_pan(self): """ Set action 'Pan' """ try: self.iface.actionPan().trigger() except Exception: pass def reset_rubber_band(self, geom_type="polygon"): try: if geom_type == "polygon": geom_type = QgsWkbTypes.PolygonGeometry elif geom_type == "line": geom_type = QgsWkbTypes.LineString self.rubber_band.reset(geom_type) except: pass def reset(self): self.reset_rubber_band() self.snapped_feat = None def cancel_map_tool(self): """ Executed if user press right button or escape key """ # Reset rubber band self.reset() # Deactivate map tool self.deactivate() self.set_action_pan() def remove_markers(self): """ Remove previous markers """ vertex_items = [i for i in list(self.canvas.scene().items()) if issubclass(type(i), QgsVertexMarker)] for ver in vertex_items: if ver in list(self.canvas.scene().items()): self.canvas.scene().removeItem(ver) def refresh_map_canvas(self): """ Refresh all layers present in map canvas """ self.canvas.refreshAllLayers() for layer_refresh in self.canvas.layers(): layer_refresh.triggerRepaint()
class DBManagerPlugin: def __init__(self, iface): self.iface = iface self.dlg = None def initGui(self): self.action = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "DB Manager"), self.iface.mainWindow()) self.action.setObjectName("dbManager") self.action.triggered.connect(self.run) # Add toolbar button and menu item if hasattr(self.iface, 'addDatabaseToolBarIcon'): self.iface.addDatabaseToolBarIcon(self.action) else: self.iface.addToolBarIcon(self.action) if hasattr(self.iface, 'addPluginToDatabaseMenu'): self.iface.addPluginToDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.addPluginToMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) self.layerAction = QAction(QIcon(":/db_manager/icon"), QApplication.translate("DBManagerPlugin", "Update Sql Layer"), self.iface.mainWindow()) self.layerAction.setObjectName("dbManagerUpdateSqlLayer") QObject.connect(self.layerAction, SIGNAL("triggered()"), self.onUpdateSqlLayer) self.iface.legendInterface().addLegendLayerAction(self.layerAction, "", "dbManagerUpdateSqlLayer", QgsMapLayer.VectorLayer, False) for l in QgsMapLayerRegistry.instance().mapLayers().values(): self.onLayerWasAdded(l) QgsMapLayerRegistry.instance().layerWasAdded.connect(self.onLayerWasAdded) def unload(self): # Remove the plugin menu item and icon if hasattr(self.iface, 'removePluginDatabaseMenu'): self.iface.removePluginDatabaseMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) else: self.iface.removePluginMenu(QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) if hasattr(self.iface, 'removeDatabaseToolBarIcon'): self.iface.removeDatabaseToolBarIcon(self.action) else: self.iface.removeToolBarIcon(self.action) self.iface.legendInterface().removeLegendLayerAction(self.layerAction) QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.onLayerWasAdded) if self.dlg is not None: self.dlg.close() def onLayerWasAdded(self, aMapLayer): if aMapLayer.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: uri = QgsDataSourceURI(aMapLayer.source()) if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S): self.iface.legendInterface().addLegendLayerActionForLayer(self.layerAction, aMapLayer) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') # url.queryItemValue('uid') # url.queryItemValue('geometry') def onUpdateSqlLayer(self): l = self.iface.legendInterface().currentLayer() if l.dataProvider().name() in ['postgres', 'spatialite', 'oracle']: uri = QgsDataSourceURI(l.source()) if re.search('^\(SELECT .+ FROM .+\)$', uri.table(), re.S): self.run() self.dlg.runSqlLayerWindow(l) # virtual has QUrl source # url = QUrl(QUrl.fromPercentEncoding(l.source())) # url.queryItemValue('query') # url.queryItemValue('uid') # url.queryItemValue('geometry') def run(self): # keep opened only one instance if self.dlg is None: from .db_manager import DBManager self.dlg = DBManager(self.iface) self.dlg.destroyed.connect(self.onDestroyed) self.dlg.show() self.dlg.raise_() self.dlg.setWindowState(self.dlg.windowState() & ~Qt.WindowMinimized) self.dlg.activateWindow() def onDestroyed(self, obj): self.dlg = None