def initGui(self): """startup""" # run run_icon = QIcon('%s/%s' % (self.context.ppath, 'images/MetaSearch.png')) self.action_run = QAction(run_icon, 'MetaSearch', self.iface.mainWindow()) self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin')) self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch', 'Search Metadata Catalogs')) self.action_run.triggered.connect(self.run) self.iface.addWebToolBarIcon(self.action_run) self.iface.addPluginToWebMenu(self.web_menu, self.action_run) # help help_icon = QgsApplication.getThemeIcon('/mActionHelpContents.svg') self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow()) self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch', 'MetaSearch plugin help')) self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch', 'Get Help on MetaSearch')) self.action_help.triggered.connect(self.help) self.iface.addPluginToWebMenu(self.web_menu, self.action_help) # prefab the dialog but not open it yet self.dialog = MetaSearchDialog(self.iface)
class D3DataVis: heatmapDialog = None def __init__(self, iface): self.iface = iface def initGui(self): """ Initialize the menu and dialog boxes for the D3 heatmap chart """ icon = QIcon(os.path.dirname(__file__) + "/icon.png") self.heatmapAction = QAction(icon, "Circular Date/Time Heatmap", self.iface.mainWindow()) self.heatmapAction.triggered.connect(self.showHeatmapDialog) self.heatmapAction.setCheckable(False) self.iface.addWebToolBarIcon(self.heatmapAction) # Add a D3 Data Visualization menu item to the Web menu self.iface.addPluginToWebMenu("D3 Data Visualization", self.heatmapAction) def unload(self): self.iface.removePluginWebMenu("D3 Data Visualization", self.heatmapAction) self.iface.removeWebToolBarIcon(self.heatmapAction) def showHeatmapDialog(self): """Display the circular date/time heatmap dialog box""" if not self.heatmapDialog: from .heatmapDialog import HeatmapDialog self.heatmapDialog = HeatmapDialog(self.iface, self.iface.mainWindow()) self.heatmapDialog.show()
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.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 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)
def testSettingsPath(self): """ test that settings path is respected """ QSettings().clear() s1 = QgsShortcutsManager(None, '/path1/') s2 = QgsShortcutsManager(None, '/path2/') action1 = QAction('action', None) s1.registerAction(action1) s1.setKeySequence(action1, 'B') action2 = QAction('action', None) s2.registerAction(action2) s2.setKeySequence(action2, 'C') # test retrieving r1 = QgsShortcutsManager(None, '/path1/') r2 = QgsShortcutsManager(None, '/path2/') raction1 = QAction('action', None) r1.registerAction(raction1) raction2 = QAction('action', None) r2.registerAction(raction2) self.assertEqual(raction1.shortcut().toString(), 'B') self.assertEqual(raction2.shortcut().toString(), 'C')
def build_menu_tree(self): # Main Menu self.menu.clear() self.groups_list = GroupsList() self.ds_list = DataSourcesList() data_sources = self.ds_list.data_sources.values() data_sources = sorted(data_sources, key=lambda x: x.alias or x.id) ds_hide_list = PluginSettings.get_hide_ds_id_list() for ds in data_sources: if ds.id in ds_hide_list: continue ds.action.triggered.connect(self.insert_layer) gr_menu = self.groups_list.get_group_menu(ds.group) gr_menu.addAction(ds.action) if gr_menu not in self.menu.children(): self.menu.addMenu(gr_menu) # QMS web service self.menu.addSeparator() self.service_actions.append(self.qms_search_action) self.menu.addAction(self.qms_search_action) icon_create_service_path = self.plugin_dir + '/icons/mActionCreate.svg' qms_create_service_action = QAction(self.tr('Add to Search'), self.iface.mainWindow()) qms_create_service_action.setIcon(QIcon(icon_create_service_path)) qms_create_service_action.triggered.connect(self.openURL) self.menu.addAction(qms_create_service_action) # Scales, Settings and About actions self.menu.addSeparator() icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.svg' # TODO change icon set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path), self.tr('Set proper scale'), self.iface.mainWindow()) set_nearest_scale_act.triggered.connect(self.set_nearest_scale) self.menu.addAction(set_nearest_scale_act) # TODO: uncomment after fix self.service_actions.append(set_nearest_scale_act) icon_scales_path = self.plugin_dir + '/icons/mActionSettings.svg' # TODO change icon scales_act = QAction(QIcon(icon_scales_path), self.tr('Set SlippyMap scales'), self.iface.mainWindow()) scales_act.triggered.connect(self.set_tms_scales) #self.menu.addAction(scales_act) # TODO: uncomment after fix self.service_actions.append(scales_act) icon_settings_path = self.plugin_dir + '/icons/mActionSettings.svg' settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'), self.iface.mainWindow()) self.service_actions.append(settings_act) settings_act.triggered.connect(self.show_settings_dialog) self.menu.addAction(settings_act) icon_about_path = self.plugin_dir + '/icons/mActionAbout.svg' info_act = QAction(QIcon(icon_about_path), self.tr('About'), self.iface.mainWindow()) self.service_actions.append(info_act) info_act.triggered.connect(self.info_dlg.show) self.menu.addAction(info_act)
def registerDatabaseActions(self, mainWindow): Database.registerDatabaseActions(self, mainWindow) # add a separator separator = QAction(self) separator.setSeparator(True) mainWindow.registerAction(separator, self.tr("&Table")) action = QAction(self.tr("Run &Vacuum Analyze"), self) mainWindow.registerAction(action, self.tr("&Table"), self.runVacuumAnalyzeActionSlot)
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()
class QMatplotlibWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.canvas = QMatplotlibCanvas() self.ax = self.canvas.ax self.figure = self.canvas.figure self.toolBar = NavigationToolbar2QT(self.canvas, self) bgColor = self.palette().color(QPalette.Background).name() self.figure.set_facecolor(bgColor) self.layout = QVBoxLayout() self.layout.setSpacing(2) self.layout.setMargin(0) self.layout.addWidget(self.toolBar) self.layout.addWidget(self.canvas) self.setLayout(self.layout) self._setupToolbar() def _setupToolbar(self): self.actionToggleGrid = QAction(self.tr('Toggle grid'), self.toolBar) self.actionToggleGrid.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'toggleGrid.svg'))) self.actionToggleGrid.setCheckable(True) self.actionToggleGrid.triggered.connect(self.toggleGrid) self.toolBar.insertAction(self.toolBar.actions()[7], self.actionToggleGrid) self.toolBar.insertSeparator(self.toolBar.actions()[8]) def toggleGrid(self): self.ax.grid() self.canvas.draw() def alignLabels(self): self.figure.autofmt_xdate() def clear(self): self.ax.clear() self.canvas.draw() def setTitle(self, text): self.ax.set_title(text) def setXAxisCaption(self, text): self.ax.set_xlabel(text) def setYAxisCaption(self, text): self.ax.set_ylabel(text)
def setAsNonRepoLayer(layer): removeLayerActions(layer) action = QAction("Import to GeoGig...", config.iface.legendInterface()) action.triggered.connect(partial(addLayer, layer)) if layer.type() == QgsMapLayer.RasterLayer or layer.storageType() != 'GPKG': action.setEnabled(False) config.iface.legendInterface().addLegendLayerAction(action, u"GeoGig", u"id2", QgsMapLayer.VectorLayer, False) config.iface.legendInterface().addLegendLayerActionForLayer(action, layer) _actions[layer.id()] = [action] try: repoWatcher.layerUpdated.disconnect(updateInfoActions) except: pass #In case it is a layer that was never a repo layer
def menu(self): menu = QMenu() refreshAction = QAction(icon("refresh.svg"), "Refresh", menu) refreshAction.triggered.connect(self.refreshContent) menu.addAction(refreshAction) createBranchAction = QAction(icon("create_branch.png"), "Create branch", menu) createBranchAction.triggered.connect(self.createBranch) menu.addAction(createBranchAction) deleteAction = QAction(QgsApplication.getThemeIcon('/mActionDeleteSelected.svg'), "Delete", menu) deleteAction.triggered.connect(self.delete) menu.addAction(deleteAction) deleteAction.setEnabled(self.parent().childCount() > 1 and self.branch != "master") return menu
def selectOutput(self): if isinstance(self.parameter, QgsProcessingParameterFolderDestination): self.selectDirectory() else: popupMenu = QMenu() if not self.default_selection: if self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional: actionSkipOutput = QAction( self.tr('Skip Output'), self.btnSelect) actionSkipOutput.triggered.connect(self.skipOutput) popupMenu.addAction(actionSkipOutput) if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \ and self.parameter.supportsNonFileBasedOutput(): # use memory layers for temporary layers if supported actionSaveToTemp = QAction( self.tr('Create Temporary Layer'), self.btnSelect) else: actionSaveToTemp = QAction( self.tr('Save to a Temporary File'), self.btnSelect) actionSaveToTemp.triggered.connect(self.saveToTemporary) popupMenu.addAction(actionSaveToTemp) actionSaveToFile = QAction( QCoreApplication.translate('DestinationSelectionPanel', 'Save to File…'), self.btnSelect) actionSaveToFile.triggered.connect(self.selectFile) popupMenu.addAction(actionSaveToFile) if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \ and self.parameter.supportsNonFileBasedOutput(): actionSaveToGpkg = QAction( QCoreApplication.translate('DestinationSelectionPanel', 'Save to GeoPackage…'), self.btnSelect) actionSaveToGpkg.triggered.connect(self.saveToGeopackage) popupMenu.addAction(actionSaveToGpkg) actionSaveToPostGIS = QAction( QCoreApplication.translate('DestinationSelectionPanel', 'Save to PostGIS Table…'), self.btnSelect) actionSaveToPostGIS.triggered.connect(self.saveToPostGIS) settings = QgsSettings() settings.beginGroup('/PostgreSQL/connections/') names = settings.childGroups() settings.endGroup() actionSaveToPostGIS.setEnabled(bool(names)) popupMenu.addAction(actionSaveToPostGIS) actionSetEncoding = QAction( QCoreApplication.translate('DestinationSelectionPanel', 'Change File Encoding ({})…').format(self.encoding), self.btnSelect) actionSetEncoding.triggered.connect(self.selectEncoding) popupMenu.addAction(actionSetEncoding) popupMenu.exec_(QCursor.pos())
def selectOutput(self): if isinstance(self.parameter, QgsProcessingParameterFolderDestination): self.selectDirectory() else: popupMenu = QMenu() if self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional: actionSkipOutput = QAction( self.tr('Skip output'), self.btnSelect) actionSkipOutput.triggered.connect(self.skipOutput) popupMenu.addAction(actionSkipOutput) if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \ and self.alg.provider().supportsNonFileBasedOutput(): # use memory layers for temporary layers if supported actionSaveToTemp = QAction( self.tr('Create temporary layer'), self.btnSelect) else: actionSaveToTemp = QAction( self.tr('Save to a temporary file'), self.btnSelect) actionSaveToTemp.triggered.connect(self.saveToTemporary) popupMenu.addAction(actionSaveToTemp) actionSaveToFile = QAction( self.tr('Save to file...'), self.btnSelect) actionSaveToFile.triggered.connect(self.selectFile) popupMenu.addAction(actionSaveToFile) actionShowExpressionsBuilder = QAction( self.tr('Use expression...'), self.btnSelect) actionShowExpressionsBuilder.triggered.connect(self.showExpressionsBuilder) popupMenu.addAction(actionShowExpressionsBuilder) if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \ and self.alg.provider().supportsNonFileBasedOutput(): actionSaveToSpatialite = QAction( self.tr('Save to SpatiaLite table...'), self.btnSelect) actionSaveToSpatialite.triggered.connect(self.saveToSpatialite) popupMenu.addAction(actionSaveToSpatialite) actionSaveToPostGIS = QAction( self.tr('Save to PostGIS table...'), self.btnSelect) actionSaveToPostGIS.triggered.connect(self.saveToPostGIS) settings = QgsSettings() settings.beginGroup('/PostgreSQL/connections/') names = settings.childGroups() settings.endGroup() actionSaveToPostGIS.setEnabled(bool(names)) popupMenu.addAction(actionSaveToPostGIS) popupMenu.exec_(QCursor.pos())
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 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 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)
def __init__(self, parent=None): QTableView.__init__(self, parent) self.setSelectionBehavior(QAbstractItemView.SelectRows) self.setSelectionMode(QAbstractItemView.ExtendedSelection) self.item = None self.dirty = False # allow copying results copyAction = QAction(QApplication.translate("DBManagerPlugin", "Copy"), self) self.addAction(copyAction) copyAction.setShortcuts(QKeySequence.Copy) copyAction.triggered.connect(self.copySelectedResults) self._clear()
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)
class Send2GE: def __init__(self, iface): """Initialize class""" # save reference to QGIS interface self.iface = iface self.plugin_dir = get_file_dir(__file__) def initGui(self): """Initialize graphic user interface""" #create action that will be run by the plugin self.action = QAction( QIcon("%s/icons/cursor2.png" % self.plugin_dir), "Send to Google Earth", self.iface.mainWindow() ) self.action.setWhatsThis("Send to Google Earth") self.action.setStatusTip("Send coordinates of a mouse click to Google Earth") # add plugin menu to Vector toolbar self.iface.addPluginToMenu("Send2GoogleEarth",self.action) # add icon to new menu item in Vector toolbar self.iface.addToolBarIcon(self.action) # connect action to the run method self.action.triggered.connect(self.run) # prepare map tool self.mapTool = Send2GEtool(self.iface) #self.iface.mapCanvas().mapToolSet.connect(self.mapToolChanged) def unload(self): """Actions to run when the plugin is unloaded""" # remove menu and icon from the menu self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu("Send2GoogleEarth",self.action) if self.iface.mapCanvas().mapTool() == self.mapTool: self.iface.mapCanvas().unsetMapTool(self.mapTool) del self.mapTool def run(self): """Action to run""" # create a string and show it self.iface.mapCanvas().setMapTool(self.mapTool)
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)
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 add_action( self, icon_path, text, callback, enabled_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.""" icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_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.append(action) return action
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 initGui(self): """ Initialize the menu and dialog boxes for the D3 heatmap chart """ icon = QIcon(os.path.dirname(__file__) + "/icon.png") self.heatmapAction = QAction(icon, "Circular Date/Time Heatmap", self.iface.mainWindow()) self.heatmapAction.triggered.connect(self.showHeatmapDialog) self.heatmapAction.setCheckable(False) self.iface.addWebToolBarIcon(self.heatmapAction) # Add a D3 Data Visualization menu item to the Web menu self.iface.addPluginToWebMenu("D3 Data Visualization", self.heatmapAction)
class NavToolbar(NavigationToolbar): updateRequested = pyqtSignal() def __init__(self, canvas, parent=None): NavigationToolbar.__init__(self, canvas, parent) # add toolbutton to change fonts/colors self.fontColorAction = QAction( QIcon(":/pstimeseries_plugin/icons/settings"), "Change fonts and colors", self ) self.fontColorAction.setToolTip( "Change fonts and colors" ) self.insertAction(self.homeAction, self.fontColorAction) self.fontColorAction.triggered.connect(self.openFontColorSettings) self.insertSeparator(self.homeAction) def openFontColorSettings(self): dlg = GraphSettings_Dlg(self) if dlg.exec_(): self.updateRequested.emit()
def selectOutput(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() else: popupMenu = QMenu() if isinstance(self.output, OutputVector) \ and self.alg.provider.supportsNonFileBasedOutput(): # use memory layers for temporary layers if supported actionSaveToTemp = QAction( self.tr('Create temporary layer'), self.btnSelect) else: actionSaveToTemp = QAction( self.tr('Save to a temporary file'), self.btnSelect) actionSaveToTemp.triggered.connect(self.saveToTemporary) popupMenu.addAction(actionSaveToTemp) actionSaveToFile = QAction( self.tr('Save to file...'), self.btnSelect) actionSaveToFile.triggered.connect(self.selectFile) popupMenu.addAction(actionSaveToFile) actionShowExpressionsBuilder = QAction( self.tr('Use expression...'), self.btnSelect) actionShowExpressionsBuilder.triggered.connect(self.showExpressionsBuilder) popupMenu.addAction(actionShowExpressionsBuilder) if isinstance(self.output, OutputVector) \ and self.alg.provider.supportsNonFileBasedOutput(): actionSaveToSpatialite = QAction( self.tr('Save to Spatialite table...'), self.btnSelect) actionSaveToSpatialite.triggered.connect(self.saveToSpatialite) popupMenu.addAction(actionSaveToSpatialite) actionSaveToPostGIS = QAction( self.tr('Save to PostGIS table...'), self.btnSelect) actionSaveToPostGIS.triggered.connect(self.saveToPostGIS) settings = QSettings() settings.beginGroup('/PostgreSQL/connections/') names = settings.childGroups() settings.endGroup() actionSaveToPostGIS.setEnabled(bool(names)) popupMenu.addAction(actionSaveToPostGIS) popupMenu.exec_(QCursor.pos())
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 __init__(self, canvas, parent=None): NavigationToolbar.__init__(self, canvas, parent) # add toolbutton to change fonts/colors self.fontColorAction = QAction( QIcon(":/pstimeseries_plugin/icons/settings"), "Change fonts and colors", self ) self.fontColorAction.setToolTip( "Change fonts and colors" ) self.insertAction(self.homeAction, self.fontColorAction) self.fontColorAction.triggered.connect(self.openFontColorSettings) self.insertSeparator(self.homeAction)
def _setupToolbar(self): self.actionToggleGrid = QAction(self.tr('Toggle grid'), self.toolBar) self.actionToggleGrid.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'toggleGrid.svg'))) self.actionToggleGrid.setCheckable(True) self.actionToggleGrid.triggered.connect(self.toggleGrid) self.toolBar.insertAction(self.toolBar.actions()[7], self.actionToggleGrid) self.toolBar.insertSeparator(self.toolBar.actions()[8])
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
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) 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.editSelectedAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Selected Features'), self.iface.mainWindow()) self.editSelectedAction.setObjectName('editSelectedFeatures') self.editSelectedAction.setCheckable(True) self.editSelectedAction.toggled.connect(self.editSelected) self.toolbox.processingToolbar.addAction(self.editSelectedAction) 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 and selection""" if layer is None: layer = self.iface.activeLayer() old_enabled_state = self.editSelectedAction.isEnabled() new_enabled_state = layer is not None and layer.type() == QgsMapLayer.VectorLayer and layer.isEditable() and layer.selectedFeatureCount() self.editSelectedAction.setEnabled(new_enabled_state) if new_enabled_state != old_enabled_state: self.toolbox.set_in_place_edit_mode(new_enabled_state and self.editSelectedAction.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 __init__(self, model=None): super().__init__(None) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi(self) self._variables_scope = None # LOTS of bug reports when we include the dock creation in the UI file # see e.g. #16428, #19068 # So just roll it all by hand......! self.propertiesDock = QgsDockWidget(self) self.propertiesDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.propertiesDock.setObjectName("propertiesDock") propertiesDockContents = QWidget() self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents) self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0) self.verticalDockLayout_1.setSpacing(0) self.scrollArea_1 = QgsScrollArea(propertiesDockContents) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.scrollArea_1.sizePolicy().hasHeightForWidth()) self.scrollArea_1.setSizePolicy(sizePolicy) self.scrollArea_1.setFocusPolicy(Qt.WheelFocus) self.scrollArea_1.setFrameShape(QFrame.NoFrame) self.scrollArea_1.setFrameShadow(QFrame.Plain) self.scrollArea_1.setWidgetResizable(True) self.scrollAreaWidgetContents_1 = QWidget() self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1) self.gridLayout.setContentsMargins(6, 6, 6, 6) self.gridLayout.setSpacing(4) self.label_1 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1) self.textName = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textName, 0, 1, 1, 1) self.label_2 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1) self.label_1.setText(self.tr("Name")) self.textName.setToolTip(self.tr("Enter model name here")) self.label_2.setText(self.tr("Group")) self.textGroup.setToolTip(self.tr("Enter group name here")) self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1) self.verticalDockLayout_1.addWidget(self.scrollArea_1) self.propertiesDock.setWidget(propertiesDockContents) self.propertiesDock.setWindowTitle(self.tr("Model Properties")) self.inputsDock = QgsDockWidget(self) self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.inputsDock.setObjectName("inputsDock") self.inputsDockContents = QWidget() self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.scrollArea_2 = QgsScrollArea(self.inputsDockContents) sizePolicy.setHeightForWidth( self.scrollArea_2.sizePolicy().hasHeightForWidth()) self.scrollArea_2.setSizePolicy(sizePolicy) self.scrollArea_2.setFocusPolicy(Qt.WheelFocus) self.scrollArea_2.setFrameShape(QFrame.NoFrame) self.scrollArea_2.setFrameShadow(QFrame.Plain) self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2) self.inputsTree.setAlternatingRowColors(True) self.inputsTree.header().setVisible(False) self.verticalLayout.addWidget(self.inputsTree) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_3.addWidget(self.scrollArea_2) self.inputsDock.setWidget(self.inputsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock) self.inputsDock.setWindowTitle(self.tr("Inputs")) self.algorithmsDock = QgsDockWidget(self) self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.algorithmsDock.setObjectName("algorithmsDock") self.algorithmsDockContents = QWidget() self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents) sizePolicy.setHeightForWidth( self.scrollArea_3.sizePolicy().hasHeightForWidth()) self.scrollArea_3.setSizePolicy(sizePolicy) self.scrollArea_3.setFocusPolicy(Qt.WheelFocus) self.scrollArea_3.setFrameShape(QFrame.NoFrame) self.scrollArea_3.setFrameShadow(QFrame.Plain) self.scrollArea_3.setWidgetResizable(True) self.scrollAreaWidgetContents_3 = QWidget() self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setSpacing(4) self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3) self.verticalLayout_2.addWidget(self.searchBox) self.algorithmTree = QgsProcessingToolboxTreeView( None, QgsApplication.processingRegistry()) self.algorithmTree.setAlternatingRowColors(True) self.algorithmTree.header().setVisible(False) self.verticalLayout_2.addWidget(self.algorithmTree) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.verticalLayout_4.addWidget(self.scrollArea_3) self.algorithmsDock.setWidget(self.algorithmsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock) self.algorithmsDock.setWindowTitle(self.tr("Algorithms")) self.searchBox.setToolTip( self.tr("Enter algorithm name to filter list")) self.searchBox.setShowSearchIcon(True) self.variables_dock = QgsDockWidget(self) self.variables_dock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.variables_dock.setObjectName("variablesDock") self.variables_dock_contents = QWidget() vl_v = QVBoxLayout() vl_v.setContentsMargins(0, 0, 0, 0) self.variables_editor = QgsVariableEditorWidget() vl_v.addWidget(self.variables_editor) self.variables_dock_contents.setLayout(vl_v) self.variables_dock.setWidget(self.variables_dock_contents) self.addDockWidget(Qt.DockWidgetArea(1), self.variables_dock) self.variables_dock.setWindowTitle(self.tr("Variables")) self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock) self.tabifyDockWidget(self.propertiesDock, self.variables_dock) self.variables_editor.scopeChanged.connect(self.variables_changed) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.centralWidget().layout().insertWidget(0, self.bar) try: self.setDockOptions(self.dockOptions() | QMainWindow.GroupedDragging) except: pass if iface is not None: self.mToolbar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.toolbutton_export_to_script = QToolButton() self.toolbutton_export_to_script.setPopupMode(QToolButton.InstantPopup) self.export_to_script_algorithm_action = QAction( QCoreApplication.translate('ModelerDialog', 'Export as Script Algorithm…')) self.toolbutton_export_to_script.addActions( [self.export_to_script_algorithm_action]) self.mToolbar.insertWidget(self.mActionExportImage, self.toolbutton_export_to_script) self.export_to_script_algorithm_action.triggered.connect( self.export_as_script_algorithm) self.mActionOpen.setIcon( QgsApplication.getThemeIcon('/mActionFileOpen.svg')) self.mActionSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.mActionSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.mActionSaveInProject.setIcon( QgsApplication.getThemeIcon('/mAddToProject.svg')) self.mActionZoomActual.setIcon( QgsApplication.getThemeIcon('/mActionZoomActual.svg')) self.mActionZoomIn.setIcon( QgsApplication.getThemeIcon('/mActionZoomIn.svg')) self.mActionZoomOut.setIcon( QgsApplication.getThemeIcon('/mActionZoomOut.svg')) self.mActionExportImage.setIcon( QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) self.mActionZoomToItems.setIcon( QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg')) self.mActionExportPdf.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg')) self.mActionExportSvg.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg')) self.toolbutton_export_to_script.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPython.svg')) self.mActionEditHelp.setIcon( QgsApplication.getThemeIcon('/mActionEditHelpContent.svg')) self.mActionRun.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock) self.tabifyDockWidget(self.inputsDock, self.algorithmsDock) self.inputsDock.raise_() self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) settings = QgsSettings() self.restoreState( settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry( settings.value("/Processing/geometryModeler", QByteArray())) self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect( QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.view.setScene(self.scene) self.view.setAcceptDrops(True) self.view.ensureVisible(0, 0, 10, 10) self.view.scale(QgsApplication.desktop().logicalDpiX() / 96, QgsApplication.desktop().logicalDpiX() / 96) def _dragEnterEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): event.acceptProposedAction() else: event.ignore() def _dropEvent(event): def alg_dropped(algorithm_id, pos): alg = QgsApplication.processingRegistry().createAlgorithmById( algorithm_id) if alg is not None: self._addAlgorithm(alg, pos) else: assert False, algorithm_id def input_dropped(id, pos): if id in [ param.id() for param in QgsApplication.instance(). processingRegistry().parameterTypes() ]: self.addInputOfType(itemId, pos) if event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): data = event.mimeData().data( 'application/x-vnd.qgis.qgis.algorithmid') stream = QDataStream(data, QIODevice.ReadOnly) algorithm_id = stream.readQString() QTimer.singleShot( 0, lambda id=algorithm_id, pos=self.view.mapToScene(event.pos( )): alg_dropped(id, pos)) event.accept() elif event.mimeData().hasText(): itemId = event.mimeData().text() QTimer.singleShot(0, lambda id=itemId, pos=self.view.mapToScene( event.pos()): input_dropped(id, pos)) event.accept() else: event.ignore() def _dragMoveEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): event.accept() else: event.ignore() def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) # "Normal" mouse has an angle delta of 120, precision mouses provide data # faster, in smaller steps factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y()) if (event.modifiers() == Qt.ControlModifier): factor = 1.0 + (factor - 1.0) / 20.0 if event.angleDelta().y() < 0: factor = 1 / factor self.view.scale(factor, factor) def _enterEvent(e): QGraphicsView.enterEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mousePressEvent(e): if e.button() == Qt.MidButton: self.previousMousePos = e.pos() else: QGraphicsView.mousePressEvent(self.view, e) def _mouseMoveEvent(e): if e.buttons() == Qt.MidButton: offset = self.previousMousePos - e.pos() self.previousMousePos = e.pos() self.view.verticalScrollBar().setValue( self.view.verticalScrollBar().value() + offset.y()) self.view.horizontalScrollBar().setValue( self.view.horizontalScrollBar().value() + offset.x()) else: QGraphicsView.mouseMoveEvent(self.view, e) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent self.view.dragMoveEvent = _dragMoveEvent self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() text = items[0].data(0, Qt.UserRole) mimeData.setText(text) return mimeData self.inputsTree.mimeData = _mimeDataInput self.inputsTree.setDragDropMode(QTreeWidget.DragOnly) self.inputsTree.setDropIndicatorShown(True) self.algorithms_model = ModelerToolboxModel( self, QgsApplication.processingRegistry()) self.algorithmTree.setToolboxProxyModel(self.algorithms_model) self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) filters = QgsProcessingToolboxProxyModel.Filters( QgsProcessingToolboxProxyModel.FilterModeler) if ProcessingConfig.getSetting( ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES): filters |= QgsProcessingToolboxProxyModel.FilterShowKnownIssues self.algorithmTree.setFilters(filters) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText( QCoreApplication.translate('ModelerDialog', 'Search…')) if hasattr(self.textName, 'setPlaceholderText'): self.textName.setPlaceholderText(self.tr('Enter model name here')) if hasattr(self.textGroup, 'setPlaceholderText'): self.textGroup.setPlaceholderText(self.tr('Enter group name here')) # Connect signals and slots self.inputsTree.doubleClicked.connect(self.addInput) self.searchBox.textChanged.connect(self.algorithmTree.setFilterString) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) # Ctrl+= should also trigger a zoom in action ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self) ctrlEquals.activated.connect(self.zoomIn) self.mActionOpen.triggered.connect(self.openModel) self.mActionSave.triggered.connect(self.save) self.mActionSaveAs.triggered.connect(self.saveAs) self.mActionSaveInProject.triggered.connect(self.saveInProject) self.mActionZoomIn.triggered.connect(self.zoomIn) self.mActionZoomOut.triggered.connect(self.zoomOut) self.mActionZoomActual.triggered.connect(self.zoomActual) self.mActionZoomToItems.triggered.connect(self.zoomToItems) self.mActionExportImage.triggered.connect(self.exportAsImage) self.mActionExportPdf.triggered.connect(self.exportAsPdf) self.mActionExportSvg.triggered.connect(self.exportAsSvg) #self.mActionExportPython.triggered.connect(self.exportAsPython) self.mActionEditHelp.triggered.connect(self.editHelp) self.mActionRun.triggered.connect(self.runModel) if model is not None: self.model = model.create() self.model.setSourceFilePath(model.sourceFilePath()) self.textGroup.setText(self.model.group()) self.textName.setText(self.model.displayName()) self.repaintModel() else: self.model = QgsProcessingModelAlgorithm() self.model.setProvider( QgsApplication.processingRegistry().providerById('model')) self.update_variables_gui() self.fillInputsTree() self.view.centerOn(0, 0) self.help = None self.hasChanged = False
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+G').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.setObjectName('resultsViewer') 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() createButtons() # 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 initGui(self): self.toolbar = self.iface.addToolBar(name) self.toolbar.setObjectName(name) icon = QIcon(":/plugins/SplitPolygonShowingAreas/icon.png") self.action = QAction(icon, name, self.iface.mainWindow()) self.action.setCheckable(True) self.action.triggered.connect(self.onClick) self.toolbar.addAction(self.action) self.actionMoveVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveVertices.png"), moveVerticesName, self.iface.mainWindow()) self.actionMoveVertices.setCheckable(True) self.actionMoveVertices.triggered.connect(self.onClickMoveVertices) self.toolbar.addAction(self.actionMoveVertices) self.actionAddVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/addVertices.png"), addVerticesName, self.iface.mainWindow()) self.actionAddVertices.setCheckable(True) self.actionAddVertices.triggered.connect(self.onClickAddVertices) self.toolbar.addAction(self.actionAddVertices) self.actionRemoveVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/removeVertices.png"), removeVerticesName, self.iface.mainWindow()) self.actionRemoveVertices.setCheckable(True) self.actionRemoveVertices.triggered.connect(self.onClickRemoveVertices) self.toolbar.addAction(self.actionRemoveVertices) self.actionMoveSegment = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveSegment.png"), moveSegmentName, self.iface.mainWindow()) self.actionMoveSegment.setCheckable(True) self.actionMoveSegment.triggered.connect(self.onClickMoveSegment) self.toolbar.addAction(self.actionMoveSegment) self.actionLineClose = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/lineClose.png"), closeLineName, self.iface.mainWindow()) self.actionLineClose.setCheckable(False) self.actionLineClose.triggered.connect(self.onClickLineClose) self.toolbar.addAction(self.actionLineClose) self.actionLineOpen = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/lineOpen.png"), openLineName, self.iface.mainWindow()) self.actionLineOpen.setCheckable(False) self.actionLineOpen.triggered.connect(self.onClickLineOpen) self.toolbar.addAction(self.actionLineOpen) self.actionMoveLine = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveLine.png"), moveLineName, self.iface.mainWindow()) self.actionMoveLine.setCheckable(True) self.actionMoveLine.triggered.connect(self.onClickMoveLine) self.toolbar.addAction(self.actionMoveLine) self.iface.addPluginToMenu(name, self.action) self.iface.addPluginToMenu(name, self.actionMoveVertices) self.iface.addPluginToMenu(name, self.actionAddVertices) self.iface.addPluginToMenu(name, self.actionRemoveVertices) self.iface.addPluginToMenu(name, self.actionMoveSegment) self.iface.addPluginToMenu(name, self.actionLineClose) self.iface.addPluginToMenu(name, self.actionLineOpen) self.iface.addPluginToMenu(name, self.actionMoveLine) self.help_action = QAction("Help", self.iface.mainWindow()) self.help_action.triggered.connect(self.onHelp) self.iface.addPluginToMenu(name, self.help_action) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.enableTool()
def testRegisterAction(self): """ test registering actions """ QgsSettings().clear() s = QgsShortcutsManager(None) action1 = QAction('action1', None) action1.setShortcut('x') self.assertTrue(s.registerAction(action1, 'A')) action2 = QAction('action2', None) action2.setShortcut('y') self.assertTrue(s.registerAction(action2, 'B')) self.assertCountEqual(s.listActions(), [action1, action2]) # try re-registering an existing action - should fail, but leave action registered self.assertFalse(s.registerAction(action2, 'B')) self.assertCountEqual(s.listActions(), [action1, action2]) # actions should have been set to default sequences self.assertEqual(action1.shortcut().toString(), 'A') self.assertEqual(action2.shortcut().toString(), 'B') # test that adding an action should set its shortcut automatically s.setKeySequence('action1', 'C') s.setKeySequence('action2', 'D') s = QgsShortcutsManager(None) self.assertTrue(s.registerAction(action1, 'A')) self.assertTrue(s.registerAction(action2, 'B')) # actions should have been set to previous shortcuts self.assertEqual(action1.shortcut().toString(), 'C') self.assertEqual(action2.shortcut().toString(), 'D') # test registering an action containing '&' in name s = QgsShortcutsManager(None) action = QAction('&action1', None) self.assertTrue(s.registerAction(action)) self.assertEqual(action1.shortcut().toString(), 'C')
class XYZHubConnector(object): """base plugin""" def __init__(self, iface): """init""" import sys print(sys.version) self.iface = iface self.web_menu = "&XYZ Hub Connector" self.init_modules() self.obj = self def initGui(self): """startup""" parent = self.iface.mainWindow() ######## action, button icon = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/xyz.png")) icon_bbox = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/bbox.svg")) self.action_connect = QAction(icon, "New XYZ Hub Connection", parent) self.action_connect.setWhatsThis( QCoreApplication.translate(PLUGIN_NAME, "WhatsThis message")) self.action_connect.setStatusTip( QCoreApplication.translate(PLUGIN_NAME, "status tip message")) self.action_clear_cache = QAction("Clear cache", parent) self.action_upload = QAction("Upload to New XYZ Geospace", parent) self.action_basemap = QAction("Add HERE Map Tile", parent) self.action_magic_sync = QAction("Magic Sync (EXPERIMENTAL)", parent) self.action_manage = QAction("Manage XYZ Geospace (EXPERIMENTAL)", parent) self.action_edit = QAction("Edit/Delete XYZ Geospace (EXPERIMENTAL)", parent) if self.iface.activeLayer() is None: # self.action_upload.setEnabled(False) self.action_edit.setEnabled(False) self.action_magic_sync.setEnabled(False) # self.action_magic_sync.setVisible(False) # disable magic sync ######## CONNECT action, button self.action_connect.triggered.connect(self.open_connection_dialog) self.action_manage.triggered.connect(self.open_manage_dialog) self.action_edit.triggered.connect(self.open_edit_dialog) self.action_upload.triggered.connect(self.open_upload_dialog) self.action_magic_sync.triggered.connect(self.open_magic_sync_dialog) self.action_clear_cache.triggered.connect(self.open_clear_cache_dialog) self.action_basemap.triggered.connect(self.open_basemap_dialog) ######## Add the toolbar + button self.toolbar = self.iface.addToolBar(PLUGIN_NAME) self.toolbar.setObjectName("XYZ Hub Connector") tool_btn = QToolButton(self.toolbar) self.actions = [ self.action_connect, self.action_upload, self.action_basemap, self.action_clear_cache ] # , self.action_magic_sync, self.action_manage, self.action_edit for a in self.actions: tool_btn.addAction(a) self.iface.addPluginToWebMenu(self.web_menu, a) tool_btn.setDefaultAction(self.action_connect) tool_btn.setPopupMode(tool_btn.MenuButtonPopup) self.xyz_widget_action = self.toolbar.addWidget(tool_btn) self.action_help = None self.action_reload = QAction(icon_bbox, "Reload BBox", parent) self.action_reload.triggered.connect(self.layer_reload_bbox) self.action_reload.setVisible(False) # disable self.toolbar.addAction(self.action_reload) progress = QProgressBar() progress.setMinimum(0) progress.setMaximum(0) progress.reset() progress.hide() # progress = self.iface.statusBarIface().children()[2] # will be hidden by qgis self.iface.statusBarIface().addPermanentWidget(progress) self.pb = progress def init_modules(self): # util.init_module() # parent = self.iface.mainWindow() parent = QgsProject.instance() ######## Init xyz modules self.map_basemap_meta = basemap.load_default_xml() self.auth_manager = AuthManager(config.USER_PLUGIN_DIR + "/auth.ini") self.token_model = GroupTokenModel(parent) # self.layer = LayerManager(parent, self.iface) self.network = NetManager(parent) self.con_man = ControllerManager() self.layer_man = LayerManager() ######## data flow self.conn_info = SpaceConnectionInfo() ######## token self.token_model.load_ini(config.USER_PLUGIN_DIR + "/token.ini") ######## CALLBACK self.con_man.ld_pool.signal.progress.connect( self.cb_progress_busy) #, Qt.QueuedConnection self.con_man.ld_pool.signal.finished.connect(self.cb_progress_done) QgsProject.instance().layersWillBeRemoved["QStringList"].connect( self.layer_man.remove) QgsProject.instance().layersWillBeRemoved["QStringList"].connect( self.con_man.remove) # self.iface.currentLayerChanged.connect( self.cb_layer_selected) # UNCOMMENT if DEBUG: QgsApplication.messageLog().messageReceived.connect(print_qgis) def unload_modules(self): # self.con_man.disconnect_ux( self.iface) QgsProject.instance().layersWillBeRemoved["QStringList"].disconnect( self.layer_man.remove) QgsProject.instance().layersWillBeRemoved["QStringList"].disconnect( self.con_man.remove) # utils.disconnect_silent(self.iface.currentLayerChanged) # self.iface.mapCanvas().extentsChanged.disconnect( self.debug_reload) close_print_qgis() pass def unload(self): """teardown""" self.unload_modules() # remove the plugin menu item and icon self.iface.removePluginWebMenu(self.web_menu, self.action_help) self.toolbar.clear( ) # remove action from custom toolbar (toolbar still exist) self.toolbar.deleteLater() for a in self.actions: self.iface.removePluginWebMenu(self.web_menu, a) ############### # Callback ############### def cb_layer_selected(self, qlayer): flag_xyz = True if qlayer is not None and self.layer.is_xyz_supported_layer( qlayer) else False # disable magic sync # self.action_magic_sync.setEnabled(flag_xyz) flag_layer = True self.action_upload.setEnabled(flag_layer) self.action_edit.setEnabled(flag_layer) ############### # Callback of action (main function) ############### def cb_success_msg(self, msg, info=""): self.iface.messageBar().pushMessage(msg, info, Qgis.Success, 1) def make_cb_success(self, msg, info=""): def _cb_success_msg(): txt = info self.cb_success_msg(msg, txt) return _cb_success_msg def cb_handle_error_msg(self, e): err = parse_exception_obj(e) if isinstance(err, ChainInterrupt): e0, idx = err.args[0:2] if isinstance(e0, net_handler.NetworkError): ok = self.show_net_err_dialog(e0) if ok: return elif isinstance(e0, loader.EmptyXYZSpaceError): ret = exec_warning_dialog( "Warning", "Requested query returns no features") self.show_err_msgbar(err) def show_net_err_dialog(self, err): assert isinstance(err, net_handler.NetworkError) reply_tag, status, reason, body = err.args[:4] if reply_tag in ["count"]: # too many error return 0 msg = ("%s: %s\n" % (status, reason) + "There was a problem connecting to the server") if status == 403: msg += "\n\n" + "Please make sure that the token has WRITE permission" ret = exec_warning_dialog("Network Error", msg, body) return 1 def show_err_msgbar(self, err): self.iface.messageBar().pushMessage(TAG_PLUGIN, repr(err), Qgis.Warning, 5) msg = format_traceback(err) QgsMessageLog.logMessage(msg, TAG_PLUGIN, Qgis.Warning) def cb_progress_busy(self, n_active): if n_active > 1: return self.flag_pb_show = True self.cb_progress_refresh() def cb_progress_done(self): self.flag_pb_show = False self.cb_progress_refresh() def cb_progress_refresh(self): if not hasattr(self, "flag_pb_show"): return pb = self.pb if self.flag_pb_show: pb.show() print_qgis("show", pb) else: pb.hide() print_qgis("hide") ############### # Action (main function) ############### def load_bbox(self, con, args): bbox = bbox_utils.extend_to_bbox( bbox_utils.get_bounding_box(self.iface)) a, kw = parse_qt_args(args) kw["bbox"] = bbox kw["limit"] = 1000 con.start(*a, **kw) def layer_reload_bbox(self): con_bbox_reload = ReloadLayerController_bbox(self.network) self.con_man.add(con_bbox_reload) # con_bbox_reload.signal.finished.connect( self.refresh_canvas, Qt.QueuedConnection) con_bbox_reload.signal.finished.connect( self.make_cb_success("Bounding box loading finish")) con_bbox_reload.signal.error.connect(self.cb_handle_error_msg) # TODO: set/get params from vlayer layer_id = self.iface.activeLayer().id() layer = self.layer_man.get(layer_id) self.load_bbox(con_bbox_reload, make_qt_args(layer)) # UNUSED def refresh_canvas(self): # self.iface.activeLayer().triggerRepaint() self.iface.mapCanvas().refresh() def previous_canvas_extent(self): self.iface.mapCanvas().zoomToPreviousExtent() # def open_clear_cache_dialog(self): parent = self.iface.mainWindow() dialog = ConfirmDialog( parent, "Delete cache will make loaded layer unusable !!") ret = dialog.exec_() if ret != dialog.Ok: return utils.clear_cache() def open_connection_dialog(self): parent = self.iface.mainWindow() dialog = ConnectManageSpaceDialog(parent) dialog.config(self.token_model, self.conn_info) ############ edit btn con = EditSpaceController(self.network) self.con_man.add_background(con) con.signal.finished.connect(dialog.btn_use.clicked.emit) con.signal.error.connect(self.cb_handle_error_msg) dialog.signal_edit_space.connect(con.start_args) ############ delete btn con = DeleteSpaceController(self.network) self.con_man.add_background(con) con.signal.results.connect(dialog.btn_use.clicked.emit) con.signal.error.connect(self.cb_handle_error_msg) dialog.signal_del_space.connect(con.start_args) ############ Use Token btn con = LoadSpaceController(self.network) self.con_man.add(con) con.signal.results.connect(make_fun_args(dialog.cb_display_spaces)) con.signal.error.connect(self.cb_handle_error_msg) con.signal.error.connect(lambda e: dialog.cb_enable_token_ui()) con.signal.finished.connect(dialog.cb_enable_token_ui) dialog.signal_use_token.connect(con.start_args) ############ get statisitics con = StatSpaceController(self.network) self.con_man.add(con) con.signal.results.connect(make_fun_args( dialog.cb_display_space_count)) con.signal.error.connect(self.cb_handle_error_msg) dialog.signal_space_count.connect(con.start_args) ############ TODO: bbox btn ############ connect btn con_load = loader.ReloadLayerController(self.network, n_parallel=2) self.con_man.add_background(con_load) con_load.signal.finished.connect( self.make_cb_success("Loading finish")) # con_load.signal.finished.connect( self.refresh_canvas, Qt.QueuedConnection) con_load.signal.error.connect(self.cb_handle_error_msg) dialog.signal_space_connect.connect(con_load.start_args) # con.signal.results.connect( self.layer_man.add_args) # IMPORTANT dialog.exec_() self.con_man.finish_fast() # self.startTime = time.time() def open_manage_dialog(self): pass def open_edit_dialog(self): pass def open_upload_dialog(self): vlayer = self.iface.activeLayer() parent = self.iface.mainWindow() dialog = UploadNewSpaceDialog(parent) dialog.config(self.token_model, self.network, vlayer) ############ Use Token btn con = LoadSpaceController(self.network) self.con_man.add(con) con.signal.results.connect(make_fun_args( dialog.cb_set_valid_token)) # finished signal !? con.signal.error.connect(self.cb_handle_error_msg) con.signal.finished.connect(dialog.cb_enable_token_ui) dialog.signal_use_token.connect(con.start_args) con_upload = UploadLayerController(self.network, n_parallel=2) self.con_man.add_background(con_upload) con_upload.signal.finished.connect( self.make_cb_success("Uploading finish")) con_upload.signal.error.connect(self.cb_handle_error_msg) con = InitUploadLayerController(self.network) self.con_man.add_background(con) dialog.signal_upload_new_space.connect(con.start_args) con.signal.results.connect(con_upload.start_args) con.signal.error.connect(self.cb_handle_error_msg) dialog.exec_() self.con_man.finish_fast() def open_magic_sync_dialog(self): pass def open_basemap_dialog(self): parent = self.iface.mainWindow() auth = self.auth_manager.get_auth() dialog = BaseMapDialog(parent) dialog.config(self.map_basemap_meta, auth) dialog.signal_add_basemap.connect(self.add_basemap_layer) dialog.exec_() def add_basemap_layer(self, args): a, kw = parse_qt_args(args) meta, app_id, app_code = a self.auth_manager.save(app_id, app_code) basemap.add_basemap_layer(meta, app_id, app_code)
def registerDatabaseActions(self, mainWindow): action = QAction(QApplication.translate( "DBManagerPlugin", "&Re-connect"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Database"), self.reconnectActionSlot) if self.schemas(): action = QAction(QApplication.translate( "DBManagerPlugin", "&Create Schema…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Schema"), self.createSchemaActionSlot) action = QAction(QApplication.translate( "DBManagerPlugin", "&Delete (Empty) Schema…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot) action = QAction(QApplication.translate( "DBManagerPlugin", "Delete Selected Item"), self) mainWindow.registerAction(action, None, self.deleteActionSlot) action.setShortcuts(QKeySequence.Delete) action = QAction(QgsApplication.getThemeIcon("/mActionCreateTable.svg"), QApplication.translate( "DBManagerPlugin", "&Create Table…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Table"), self.createTableActionSlot) action = QAction(QgsApplication.getThemeIcon("/mActionEditTable.svg"), QApplication.translate( "DBManagerPlugin", "&Edit Table…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Table"), self.editTableActionSlot) action = QAction(QgsApplication.getThemeIcon("/mActionDeleteTable.svg"), QApplication.translate( "DBManagerPlugin", "&Delete Table/View…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Table"), self.deleteTableActionSlot) action = QAction(QApplication.translate( "DBManagerPlugin", "&Empty Table…"), self) mainWindow.registerAction(action, QApplication.translate( "DBManagerPlugin", "&Table"), self.emptyTableActionSlot)
def initGui(self): """startup""" parent = self.iface.mainWindow() ######## action, button icon = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/xyz.png")) icon_bbox = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/bbox.svg")) self.action_connect = QAction(icon, "New XYZ Hub Connection", parent) self.action_connect.setWhatsThis( QCoreApplication.translate(PLUGIN_NAME, "WhatsThis message")) self.action_connect.setStatusTip( QCoreApplication.translate(PLUGIN_NAME, "status tip message")) self.action_clear_cache = QAction("Clear cache", parent) self.action_upload = QAction("Upload to New XYZ Geospace", parent) self.action_basemap = QAction("Add HERE Map Tile", parent) self.action_magic_sync = QAction("Magic Sync (EXPERIMENTAL)", parent) self.action_manage = QAction("Manage XYZ Geospace (EXPERIMENTAL)", parent) self.action_edit = QAction("Edit/Delete XYZ Geospace (EXPERIMENTAL)", parent) if self.iface.activeLayer() is None: # self.action_upload.setEnabled(False) self.action_edit.setEnabled(False) self.action_magic_sync.setEnabled(False) # self.action_magic_sync.setVisible(False) # disable magic sync ######## CONNECT action, button self.action_connect.triggered.connect(self.open_connection_dialog) self.action_manage.triggered.connect(self.open_manage_dialog) self.action_edit.triggered.connect(self.open_edit_dialog) self.action_upload.triggered.connect(self.open_upload_dialog) self.action_magic_sync.triggered.connect(self.open_magic_sync_dialog) self.action_clear_cache.triggered.connect(self.open_clear_cache_dialog) self.action_basemap.triggered.connect(self.open_basemap_dialog) ######## Add the toolbar + button self.toolbar = self.iface.addToolBar(PLUGIN_NAME) self.toolbar.setObjectName("XYZ Hub Connector") tool_btn = QToolButton(self.toolbar) self.actions = [ self.action_connect, self.action_upload, self.action_basemap, self.action_clear_cache ] # , self.action_magic_sync, self.action_manage, self.action_edit for a in self.actions: tool_btn.addAction(a) self.iface.addPluginToWebMenu(self.web_menu, a) tool_btn.setDefaultAction(self.action_connect) tool_btn.setPopupMode(tool_btn.MenuButtonPopup) self.xyz_widget_action = self.toolbar.addWidget(tool_btn) self.action_help = None self.action_reload = QAction(icon_bbox, "Reload BBox", parent) self.action_reload.triggered.connect(self.layer_reload_bbox) self.action_reload.setVisible(False) # disable self.toolbar.addAction(self.action_reload) progress = QProgressBar() progress.setMinimum(0) progress.setMaximum(0) progress.reset() progress.hide() # progress = self.iface.statusBarIface().children()[2] # will be hidden by qgis self.iface.statusBarIface().addPermanentWidget(progress) self.pb = progress
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", "DB Manager"), self.action) else: self.iface.addPluginToMenu( QApplication.translate("DBManagerPlugin", "DB Manager"), self.action) self.layerAction = QAction( QgsApplication.getThemeIcon('dbmanager.svg'), 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.iface.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
def testSetSequence(self): """ test setting key sequences """ QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') shortcut2 = QShortcut(None) shortcut2.setObjectName('shortcut2') action1 = QAction('action1', None) action2 = QAction('action2', None) s.registerShortcut(shortcut1, 'A') s.registerShortcut(shortcut2, 'B') s.registerAction(action1, 'C') s.registerAction(action2, 'D') # test setting by action/shortcut self.assertTrue(s.setKeySequence(shortcut1, 'E')) self.assertTrue(s.setKeySequence(shortcut2, 'F')) self.assertTrue(s.setKeySequence(action1, 'G')) self.assertTrue(s.setKeySequence(action2, 'H')) # test that action/shortcuts have been updated self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(shortcut2.key().toString(), 'F') self.assertEqual(action1.shortcut().toString(), 'G') self.assertEqual(action2.shortcut().toString(), 'H') # new manager s = QgsShortcutsManager(None) # new shortcuts shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') shortcut2 = QShortcut(None) shortcut2.setObjectName('shortcut2') action1 = QAction('action1', None) action2 = QAction('action2', None) # register them s.registerShortcut(shortcut1, 'A') s.registerShortcut(shortcut2, 'B') s.registerAction(action1, 'C') s.registerAction(action2, 'D') # check that previously set sequence has been restored self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(shortcut2.key().toString(), 'F') self.assertEqual(action1.shortcut().toString(), 'G') self.assertEqual(action2.shortcut().toString(), 'H') # same test, using setObjectKeySequence QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertTrue(s.setObjectKeySequence(shortcut1, 'E')) self.assertTrue(s.setObjectKeySequence(action1, 'G')) self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') # same test, using setKeySequence by name QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertFalse(s.setKeySequence('invalid_name', 'E')) self.assertTrue(s.setKeySequence('shortcut1', 'E')) self.assertTrue(s.setKeySequence('action1', 'G')) self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G')
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.editSelectedAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Selected Features'), self.iface.mainWindow()) self.editSelectedAction.setObjectName('editSelectedFeatures') self.editSelectedAction.setCheckable(True) self.editSelectedAction.toggled.connect(self.editSelected) self.toolbox.processingToolbar.addAction(self.editSelectedAction) 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 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()
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 AttributesTable(QWidget): def __init__(self, iface): QWidget.__init__(self) self.setWindowTitle(self.tr('Search results')) self.resize(480,320) self.setMinimumSize(320,240) self.center() # Results export button self.btn_saveTab = QAction(QIcon(':/plugins/qgeric/resources/icon_save.png'), self.tr('Save this tab\'s results'), self) self.btn_saveTab.triggered.connect(lambda : self.saveAttributes(True)) self.btn_saveAllTabs = QAction(QIcon(':/plugins/qgeric/resources/icon_saveAll.png'), self.tr('Save all results'), self) self.btn_saveAllTabs.triggered.connect(lambda : self.saveAttributes(False)) self.btn_export = QAction(QIcon(':/plugins/qgeric/resources/icon_export.png'), self.tr('Export the selection as a memory layer'), self) self.btn_export.triggered.connect(self.exportLayer) self.btn_zoom = QAction(QIcon(':/plugins/qgeric/resources/icon_Zoom.png'), self.tr('Zoom to selected attributes'), self) self.btn_zoom.triggered.connect(self.zoomToFeature) self.btn_selectGeom = QAction(QIcon(':/plugins/qgeric/resources/icon_HlG.png'), self.tr('Highlight feature\'s geometry'), self) self.btn_selectGeom.triggered.connect(self.selectGeomChanged) self.btn_rename = QAction(QIcon(':/plugins/qgeric/resources/icon_Settings.png'), self.tr('Settings'), self) self.btn_rename.triggered.connect(self.renameWindow) self.tabWidget = QTabWidget() # Tab container self.tabWidget.setTabsClosable(True) self.tabWidget.currentChanged.connect(self.highlight_features) self.tabWidget.tabCloseRequested.connect(self.closeTab) self.loadingWindow = QProgressDialog() self.loadingWindow.setWindowTitle(self.tr('Loading...')) self.loadingWindow.setRange(0,100) self.loadingWindow.setAutoClose(False) self.loadingWindow.setCancelButton(None) self.canvas = iface.mapCanvas() self.canvas.extentsChanged.connect(self.highlight_features) self.highlight = [] self.highlight_rows = [] toolbar = QToolBar() toolbar.addAction(self.btn_saveTab) toolbar.addAction(self.btn_saveAllTabs) toolbar.addAction(self.btn_export) toolbar.addSeparator() toolbar.addAction(self.btn_zoom) toolbar.addSeparator() toolbar.addAction(self.btn_selectGeom) toolbar.addAction(self.btn_rename) vbox = QVBoxLayout() vbox.setContentsMargins(0,0,0,0) vbox.addWidget(toolbar) vbox.addWidget(self.tabWidget) self.setLayout(vbox) self.mb = iface.messageBar() self.selectGeom = False # False for point, True for geometry def renameWindow(self): title, ok = QInputDialog.getText(self, self.tr('Rename window'), self.tr('Enter a new title:')) if ok: self.setWindowTitle(title) def closeTab(self, index): self.tabWidget.widget(index).deleteLater() self.tabWidget.removeTab(index) def selectGeomChanged(self): if self.selectGeom: self.selectGeom = False self.btn_selectGeom.setText(self.tr('Highlight feature\'s geometry')) self.btn_selectGeom.setIcon(QIcon(':/plugins/qgeric/resources/icon_HlG.png')) else: self.selectGeom = True self.btn_selectGeom.setText(self.tr('Highlight feature\'s centroid')) self.btn_selectGeom.setIcon(QIcon(':/plugins/qgeric/resources/icon_HlC.png')) self.highlight_features() def exportLayer(self): if self.tabWidget.count() != 0: index = self.tabWidget.currentIndex() table = self.tabWidget.widget(index).findChildren(QTableWidget)[0] items = table.selectedItems() if len(items) > 0: type = '' if items[0].feature.geometry().type() == QgsWkbTypes.PointGeometry: type = 'Point' elif items[0].feature.geometry().type() == QgsWkbTypes.LineGeometry: type = 'LineString' else: type = 'Polygon' features = [] for item in items: if item.feature not in features: features.append(item.feature) name = '' ok = True while not name.strip() and ok == True: name, ok = QInputDialog.getText(self, self.tr('Layer name'), self.tr('Give a name to the layer:')) if ok: layer = QgsVectorLayer(type+"?crs="+table.crs.authid(),name,"memory") layer.startEditing() layer.dataProvider().addAttributes(features[0].fields().toList()) layer.dataProvider().addFeatures(features) layer.commitChanges() QgsProject.instance().addMapLayer(layer) else: self.mb.pushWarning(self.tr('Warning'), self.tr('There is no selected feature !')) def highlight_features(self): for item in self.highlight: self.canvas.scene().removeItem(item) del self.highlight[:] del self.highlight_rows[:] index = self.tabWidget.currentIndex() tab = self.tabWidget.widget(index) if self.tabWidget.count() != 0: table = self.tabWidget.widget(index).findChildren(QTableWidget)[0] nb = 0 area = 0 length = 0 items = table.selectedItems() for item in items: if item.row() not in self.highlight_rows: if self.selectGeom: highlight = QgsHighlight(self.canvas, item.feature.geometry(), self.tabWidget.widget(index).layer) else: highlight = QgsHighlight(self.canvas, item.feature.geometry().centroid(), self.tabWidget.widget(index).layer) highlight.setColor(QColor(255,0,0)) self.highlight.append(highlight) self.highlight_rows.append(item.row()) g = QgsGeometry(item.feature.geometry()) g.transform(QgsCoordinateTransform(tab.layer.crs(), QgsCoordinateReferenceSystem(2154), QgsProject.instance())) # geometry reprojection to get meters nb += 1 area += g.area() length += g.length() if tab.layer.geometryType()==QgsWkbTypes.PolygonGeometry: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb)+' '+self.tr('Area')+': '+"%.2f"%area+' m'+u'²') elif tab.layer.geometryType()==QgsWkbTypes.LineGeometry: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb)+' '+self.tr('Length')+': '+"%.2f"%length+' m') else: tab.sb.showMessage(self.tr('Selected features')+': '+str(nb)) def tr(self, message): return QCoreApplication.translate('Qgeric', message) def zoomToFeature(self): index = self.tabWidget.currentIndex() table = self.tabWidget.widget(index).findChildren(QTableWidget)[0] items = table.selectedItems() feat_id = [] for item in items: feat_id.append(item.feature.id()) if len(feat_id) >= 1: if len(feat_id) == 1: self.canvas.setExtent(items[0].feature.geometry().buffer(5, 0).boundingBox()) # in case of a single point, it will still zoom to it else: self.canvas.zoomToFeatureIds(self.tabWidget.widget(self.tabWidget.currentIndex()).layer, feat_id) self.canvas.refresh() # Add a new tab def addLayer(self, layer, headers, types, features): tab = QWidget() tab.layer = layer p1_vertical = QVBoxLayout(tab) p1_vertical.setContentsMargins(0,0,0,0) table = QTableWidget() table.itemSelectionChanged.connect(self.highlight_features) table.title = layer.name() table.crs = layer.crs() table.setColumnCount(len(headers)) if len(features) > 0: table.setRowCount(len(features)) nbrow = len(features) self.loadingWindow.show() self.loadingWindow.setLabelText(table.title) self.loadingWindow.activateWindow() self.loadingWindow.showNormal() # Table population m = 0 for feature in features: n = 0 for cell in feature.attributes(): item = QTableWidgetItem() item.setData(Qt.DisplayRole, cell) item.setFlags(item.flags() ^ Qt.ItemIsEditable) item.feature = feature table.setItem(m, n, item) n += 1 m += 1 self.loadingWindow.setValue(int((float(m)/nbrow)*100)) QApplication.processEvents() else: table.setRowCount(0) table.setHorizontalHeaderLabels(headers) table.horizontalHeader().setSectionsMovable(True) table.types = types table.filter_op = [] table.filters = [] for i in range(0, len(headers)): table.filters.append('') table.filter_op.append(0) header = table.horizontalHeader() header.setContextMenuPolicy(Qt.CustomContextMenu) header.customContextMenuRequested.connect(partial(self.filterMenu, table)) table.setSortingEnabled(True) p1_vertical.addWidget(table) # Status bar to display informations (ie: area) tab.sb = QStatusBar() p1_vertical.addWidget(tab.sb) title = table.title # We reduce the title's length to 20 characters if len(title)>20: title = title[:20]+'...' # We add the number of elements to the tab's title. title += ' ('+str(len(features))+')' self.tabWidget.addTab(tab, title) # Add the tab to the conatiner self.tabWidget.setTabToolTip(self.tabWidget.indexOf(tab), table.title) # Display a tooltip with the layer's full name def filterMenu(self, table, pos): index = table.columnAt(pos.x()) menu = QMenu() filter_operation = QComboBox() if table.types[index] in [10]: filter_operation.addItems([self.tr('Contains'),self.tr('Equals')]) else: filter_operation.addItems(['=','>','<']) filter_operation.setCurrentIndex(table.filter_op[index]) action_filter_operation = QWidgetAction(self) action_filter_operation.setDefaultWidget(filter_operation) if table.types[index] in [14]: if not isinstance(table.filters[index], QDate): filter_value = QDateEdit() else: filter_value = QDateEdit(table.filters[index]) elif table.types[index] in [15]: if not isinstance(table.filters[index], QTime): filter_value = QTimeEdit() else: filter_value = QTimeEdit(table.filters[index]) elif table.types[index] in [16]: if not isinstance(table.filters[index], QDateTime): filter_value = QDateTimeEdit() else: filter_value = QDateTimeEdit(table.filters[index]) else: filter_value = QLineEdit(table.filters[index]) action_filter_value = QWidgetAction(self) action_filter_value.setDefaultWidget(filter_value) menu.addAction(action_filter_operation) menu.addAction(action_filter_value) action_filter_apply = QAction(self.tr('Apply'), self) action_filter_apply.triggered.connect(partial(self.applyFilter, table, index, filter_value, filter_operation)) action_filter_cancel = QAction(self.tr('Cancel'), self) action_filter_cancel.triggered.connect(partial(self.applyFilter, table, index, None, filter_operation)) menu.addAction(action_filter_apply) menu.addAction(action_filter_cancel) menu.exec_(QtGui.QCursor.pos()) def applyFilter(self, table, index, filter_value, filter_operation): if filter_value == None: table.filters[index] = None else: if isinstance(filter_value, QDateEdit): table.filters[index] = filter_value.date() elif isinstance(filter_value, QTimeEdit): table.filters[index] = filter_value.time() elif isinstance(filter_value, QDateTimeEdit): table.filters[index] = filter_value.dateTime() else: table.filters[index] = filter_value.text() table.filter_op[index] = filter_operation.currentIndex() nb_elts = 0 for i in range(0, table.rowCount()): table.setRowHidden(i, False) nb_elts += 1 hidden_rows = [] for nb_col in range(0, table.columnCount()): filtered = False header = table.horizontalHeaderItem(nb_col).text() valid = False if table.filters[nb_col] is not None: if type(table.filters[nb_col]) in [QDate, QTime, QDateTime]: valid = True else: if table.filters[nb_col].strip(): valid = True if valid: filtered = True items = None if table.types[nb_col] in [10]:# If it's a string filter_type = None if table.filter_op[nb_col] == 0: # Contain filter_type = Qt.MatchContains if table.filter_op[nb_col] == 1: # Equal filter_type = Qt.MatchFixedString items = table.findItems(table.filters[nb_col], filter_type) elif table.types[nb_col] in [14, 15, 16]: # If it's a date/time items = [] for nb_row in range(0, table.rowCount()): item = table.item(nb_row, nb_col) if table.filter_op[nb_col] == 0: # = if item.data(QTableWidgetItem.Type) == table.filters[nb_col]: items.append(item) if table.filter_op[nb_col] == 1: # > if item.data(QTableWidgetItem.Type) > table.filters[nb_col]: items.append(item) if table.filter_op[nb_col] == 2: # < if item.data(QTableWidgetItem.Type) < table.filters[nb_col]: items.append(item) else: # If it's a number items = [] for nb_row in range(0, table.rowCount()): item = table.item(nb_row, nb_col) if item.text().strip(): if table.filter_op[nb_col] == 0: # = if float(item.text()) == float(table.filters[nb_col]): items.append(item) if table.filter_op[nb_col] == 1: # > if float(item.text()) > float(table.filters[nb_col]): items.append(item) if table.filter_op[nb_col] == 2: # < if float(item.text()) < float(table.filters[nb_col]): items.append(item) rows = [] for item in items: if item.column() == nb_col: rows.append(item.row()) for i in range(0, table.rowCount()): if i not in rows: if i not in hidden_rows: nb_elts -= 1 table.setRowHidden(i, True) hidden_rows.append(i) if filtered: if header[len(header)-1] != '*': table.setHorizontalHeaderItem(nb_col, QTableWidgetItem(header+'*')) else: if header[len(header)-1] == '*': header = header[:-1] table.setHorizontalHeaderItem(nb_col, QTableWidgetItem(header)) title = self.tabWidget.tabText(self.tabWidget.currentIndex()) for i in reversed(range(len(title))): if title[i] == ' ': break title = title[:-1] title += '('+str(nb_elts)+')' self.tabWidget.setTabText(self.tabWidget.currentIndex(), title) # Save tables in OpenDocument format # Use odswriter library def saveAttributes(self, active): file = QFileDialog.getSaveFileName(self, self.tr('Save in...'),'', self.tr('OpenDocument Spreadsheet (*.ods)')) if file[0]: try: with ods.writer(open(file[0],"wb")) as odsfile: tabs = None if active: tabs = self.tabWidget.currentWidget().findChildren(QTableWidget) else: tabs = self.tabWidget.findChildren(QTableWidget) for table in reversed(tabs): sheet = odsfile.new_sheet(table.title[:20]+'...') # For each tab in the container, a new sheet is created sheet.writerow([table.title]) # As the tab's title's lenght is limited, the full name of the layer is written in the first row nb_row = table.rowCount() nb_col = table.columnCount() # Fetching and writing of the table's header header = [] for i in range(0,nb_col): header.append(table.horizontalHeaderItem(i).text()) sheet.writerow(header) # Fetching and writing of the table's items for i in range(0,nb_row): row = [] for j in range(0,nb_col): row.append(table.item(i,j).text()) if not table.isRowHidden(i): sheet.writerow(row) return True except IOError: QMessageBox.critical(self, self.tr('Error'), self.tr('The file can\'t be written.')+'\n'+self.tr('Maybe you don\'t have the rights or are trying to overwrite an opened file.')) return False def center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width()-size.width())/2, (screen.height()-size.height())/2) def clear(self): self.tabWidget.clear() for table in self.tabWidget.findChildren(QTableWidget): table.setParent(None) def closeEvent(self, e): result = QMessageBox.question(self, self.tr("Saving ?"), self.tr("Would you like to save results before exit ?"), buttons = QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if result == QMessageBox.Yes: if self.saveAttributes(False): self.clear() e.accept() else: e.ignore() elif result == QMessageBox.No: self.clear() e.accept() else: e.ignore()
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() 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): 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 add_action(self, icon_path, text, callback, enabled_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 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 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.triggered.connect(callback) action.setEnabled(enabled_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: # Adds plugin icon to Plugins toolbar self.iface.addToolBarIcon(action) if add_to_menu: self.iface.addPluginToVectorMenu(self.menu, action) self.actions.append(action) return action
class CreatePoint: """QGIS Plugin Implementation.""" 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 # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir, 'i18n', 'CreatePoint_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Obtaining the map canvas self.canvas = iface.mapCanvas() def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/Create_Point/icon.png' #create action that will be run by the plugin self.action = QAction("Create Point", self.iface.mainWindow()) self.action.setIcon(QIcon(icon_path)) self.action.setWhatsThis("Create Point") self.action.setStatusTip("Click On Map And Draw Point") # add plugin menu to Vector toolbar self.iface.addPluginToMenu("Create_Point", self.action) # add icon to new menu item in Vector toolbar self.iface.addToolBarIcon(self.action) # connect action to the run method self.action.triggered.connect(self.run) # prepare map tool self.mapTool = Map_Tool(self.iface) #self.iface.mapCanvas().mapToolSet.connect(self.mapToolChanged) def unload(self): """Actions to run when the plugin is unloaded""" # remove menu and icon from the menu self.iface.removeToolBarIcon(self.action) self.iface.removePluginMenu("Create_Point", self.action) if self.iface.mapCanvas().mapTool() == self.mapTool: self.iface.mapCanvas().unsetMapTool(self.mapTool) del self.mapTool def run(self): #Check Active Layer Present Or Not self.active_point_layer = self.iface.mapCanvas().currentLayer() if not self.active_point_layer: self.iface.messageBar().pushMessage( "Active Layer", "No Active Layer Found Please Select Point Layer", level=Qgis.Warning) else: self.layer_type = self.active_point_layer.geometryType() if self.layer_type == QgsWkbTypes.PointGeometry: self.iface.mapCanvas().setMapTool(self.mapTool) else: self.iface.messageBar().pushMessage( "Active Layer", "Active Layer Is Not Point Type Layer Please Select Point Layer", level=Qgis.Warning)
def _setup_tool_buttons(self): extent_menu = QMenu(self) canvas_act = QAction('Current visible extent', extent_menu) # noinspection PyUnresolvedReferences canvas_act.triggered[bool].connect(self.aoi_from_current_extent) extent_menu.addAction(canvas_act) active_act = QAction('Active map layer extent', extent_menu) # noinspection PyUnresolvedReferences active_act.triggered[bool].connect(self.aoi_from_active_layer_extent) extent_menu.addAction(active_act) full_act = QAction('All map layers extent', extent_menu) # noinspection PyUnresolvedReferences full_act.triggered[bool].connect(self.aoi_from_full_extent) extent_menu.addAction(full_act) self.btnExtent.setMenu(extent_menu) # Also show menu on click, to keep disclosure triangle visible self.btnExtent.clicked.connect(self.btnExtent.showMenu) draw_menu = QMenu(self) box_act = QAction('Rectangle', draw_menu) # noinspection PyUnresolvedReferences box_act.triggered[bool].connect(self.aoi_from_box) draw_menu.addAction(box_act) circle_act = QAction('Circle', draw_menu) # noinspection PyUnresolvedReferences circle_act.triggered[bool].connect(self.aoi_from_circle) draw_menu.addAction(circle_act) polygon_act = QAction('Polygon', draw_menu) # noinspection PyUnresolvedReferences polygon_act.triggered[bool].connect(self.aoi_from_polygon) draw_menu.addAction(polygon_act) self.btnDraw.setMenu(draw_menu) # Also show menu on click, to keep disclosure triangle visible self.btnDraw.clicked.connect(self.btnDraw.showMenu) selection_menu = QMenu(self) self.single_select_act = QAction('Single feature', selection_menu) # noinspection PyUnresolvedReferences self.single_select_act.triggered[bool].connect(self.aoi_from_feature) selection_menu.addAction(self.single_select_act) self.bound_select_act = QAction('Multiple features (bounding box)', selection_menu) # noinspection PyUnresolvedReferences self.bound_select_act.triggered[bool].connect(self.aoi_from_bound) selection_menu.addAction(self.bound_select_act) self.btnSelection.setMenu(selection_menu) # Also show menu on click, to keep disclosure triangle visible self.btnSelection.clicked.connect(self._toggle_selection_tools) self.btnSelection.clicked.connect(self.btnSelection.showMenu)
def registerDatabaseActions(self, mainWindow): action = QAction( QApplication.translate("DBManagerPlugin", "&Re-connect"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Database"), self.reconnectActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Create schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.createSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Delete (empty) schema"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Schema"), self.deleteSchemaActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "Delete selected item"), self) mainWindow.registerAction(action, None, self.deleteActionSlot) action.setShortcuts(QKeySequence.Delete) action = QAction( QIcon(":/db_manager/actions/create_table"), QApplication.translate("DBManagerPlugin", "&Create table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.createTableActionSlot) action = QAction( QIcon(":/db_manager/actions/edit_table"), QApplication.translate("DBManagerPlugin", "&Edit table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.editTableActionSlot) action = QAction( QIcon(":/db_manager/actions/del_table"), QApplication.translate("DBManagerPlugin", "&Delete table/view"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.deleteTableActionSlot) action = QAction( QApplication.translate("DBManagerPlugin", "&Empty table"), self) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"), self.emptyTableActionSlot) if self.schemas() is not None: action = QAction( QApplication.translate("DBManagerPlugin", "&Move to schema"), self) action.setMenu(QMenu(mainWindow)) def invoke_callback(): return mainWindow.invokeCallback( self.prepareMenuMoveTableToSchemaActionSlot) action.menu().aboutToShow.connect(invoke_callback) mainWindow.registerAction( action, QApplication.translate("DBManagerPlugin", "&Table"))
def initGui(self): self.azDigitizerTool = AzDigitizerTool(self.iface) self.lineDigitizerTool = LineDigitizerTool(self.iface) # Initialize the create shape menu items menu = QMenu() # Initialize Create Arc Wedge tool icon = QIcon(self.plugin_dir + '/images/arc.png') self.createArcAction = menu.addAction(icon, tr('Create arc wedge'), self.createArc) self.createArcAction.setObjectName('stCreateArcWedge') icon = QIcon(self.plugin_dir + '/images/donut.png') self.createDonutAction = menu.addAction(icon, tr('Create donut'), self.createDonut) self.createDonutAction.setObjectName('stCreateDonut') icon = QIcon(self.plugin_dir + '/images/ellipse.png') self.createEllipseAction = menu.addAction(icon, tr('Create ellipse'), self.createEllipse) self.createEllipseAction.setObjectName('stCreateEllipse') icon = QIcon(self.plugin_dir + '/images/rose.png') self.createEllipseRoseAction = menu.addAction( icon, tr('Create ellipse rose'), self.createEllipseRose) self.createEllipseRoseAction.setObjectName('stCreateEllipseRose') icon = QIcon(self.plugin_dir + '/images/epicycloid.png') self.createEpicycloidAction = menu.addAction(icon, tr('Create epicycloid'), self.createEpicycloid) self.createEpicycloidAction.setObjectName('stCreateEpicycloid') icon = QIcon(self.plugin_dir + '/images/heart.png') self.createHeartAction = menu.addAction(icon, tr('Create heart'), self.createHeart) self.createHeartAction.setObjectName('stCreateHeart') icon = QIcon(self.plugin_dir + '/images/hypocycloid.png') self.createHypocycloidAction = menu.addAction(icon, tr('Create hypocycloid'), self.createHypocycloid) self.createHypocycloidAction.setObjectName('stCreateHypocycloid') icon = QIcon(self.plugin_dir + '/images/line.png') self.createLOBAction = menu.addAction(icon, tr('Create line of bearing'), self.createLOB) self.createLOBAction.setObjectName('stCreateLineOfBearing') icon = QIcon(self.plugin_dir + '/images/pie.png') self.createPieAction = menu.addAction(icon, tr('Create pie wedge'), self.createPie) self.createPieAction.setObjectName('stCreatePie') icon = QIcon(self.plugin_dir + '/images/polyfoil.png') self.createPolyfoilAction = menu.addAction(icon, tr('Create polyfoil'), self.createPolyfoil) self.createPolyfoilAction.setObjectName('stCreatePolyfoil') icon = QIcon(self.plugin_dir + '/images/polygon.png') self.createPolygonAction = menu.addAction(icon, tr('Create polygon'), self.createPolygon) self.createPolygonAction.setObjectName('stCreatePolygon') icon = QIcon(self.plugin_dir + '/images/radialLines.png') self.createPolygonAction = menu.addAction(icon, tr('Create radial lines'), self.createRadialLines) self.createPolygonAction.setObjectName('stCreateRadialLines') icon = QIcon(self.plugin_dir + '/images/star.png') self.createStarAction = menu.addAction(icon, tr('Create star'), self.createStar) self.createStarAction.setObjectName('stCreateStar') # Add the shape creation tools to the menu icon = QIcon(self.plugin_dir + '/images/shapes.png') self.createShapesAction = QAction(icon, tr('Create shapes'), self.iface.mainWindow()) self.createShapesAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.createShapesAction) # Add the shape creation tools to the toolbar self.createShapeButton = QToolButton() self.createShapeButton.setMenu(menu) self.createShapeButton.setDefaultAction(self.createDonutAction) self.createShapeButton.setPopupMode(QToolButton.MenuButtonPopup) self.createShapeButton.triggered.connect(self.createShapeTriggered) self.createShapeToolbar = self.toolbar.addWidget( self.createShapeButton) # Initialize the XY to Line menu item icon = QIcon(self.plugin_dir + '/images/xyline.png') self.xyLineAction = QAction(icon, tr('XY to line'), self.iface.mainWindow()) self.xyLineAction.setObjectName('stXYtoLine') self.xyLineAction.triggered.connect(self.xyLineTool) self.iface.addPluginToVectorMenu('Shape Tools', self.xyLineAction) self.toolbar.addAction(self.xyLineAction) # Initialize the Geodesic Densifier menu item icon = QIcon(self.plugin_dir + '/images/geodesicDensifier.png') self.geodesicDensifyAction = QAction(icon, tr('Geodesic shape densifier'), self.iface.mainWindow()) self.geodesicDensifyAction.setObjectName('stGeodesicDensifier') self.geodesicDensifyAction.triggered.connect(self.geodesicDensifyTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicDensifyAction) self.toolbar.addAction(self.geodesicDensifyAction) # Initialize the Geodesic decimation menu items menu = QMenu() icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.png') self.lineDecimateAction = menu.addAction(icon, tr('Geodesic line decimate'), self.lineDecimateTool) self.lineDecimateAction.setObjectName('stGeodesicLineDecimate') icon = QIcon(self.plugin_dir + '/images/geodesicPointDecimate.png') self.pointDecimateAction = menu.addAction( icon, tr('Geodesic point decimate'), self.pointDecimateTool) self.pointDecimateAction.setObjectName('stGeodesicPointDecimate') # Add the decimation tools to the menu icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.png') self.simplifyGeomAction = QAction( icon, tr('Geodesic geometry simplification'), self.iface.mainWindow()) self.simplifyGeomAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.simplifyGeomAction) # Add the shape creation tools to the toolbar self.simplifyButton = QToolButton() self.simplifyButton.setMenu(menu) self.simplifyButton.setDefaultAction(self.lineDecimateAction) self.simplifyButton.setPopupMode(QToolButton.MenuButtonPopup) self.simplifyButton.triggered.connect(self.simplifyTriggered) self.simplifyToolbar = self.toolbar.addWidget(self.simplifyButton) # Initialize the Geodesic line break menu item icon = QIcon(self.plugin_dir + '/images/idlbreak.png') self.geodesicLineBreakAction = QAction( icon, tr('Geodesic line break at -180,180'), self.iface.mainWindow()) self.geodesicLineBreakAction.setObjectName('stGeodesicLineBreak') self.geodesicLineBreakAction.triggered.connect( self.geodesicLineBreakTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicLineBreakAction) self.toolbar.addAction(self.geodesicLineBreakAction) # Initialize Geodesic Measure Tool self.geodesicMeasureTool = GeodesicMeasureTool(self.iface, self.iface.mainWindow()) icon = QIcon(self.plugin_dir + '/images/measure.png') self.measureAction = QAction(icon, tr('Geodesic measure tool'), self.iface.mainWindow()) self.measureAction.setObjectName('stGeodesicMeasureTool') self.measureAction.triggered.connect(self.measureTool) self.measureAction.setCheckable(True) self.iface.addPluginToVectorMenu('Shape Tools', self.measureAction) self.toolbar.addAction(self.measureAction) # Initialize Geodesic Measurement layer icon = QIcon(self.plugin_dir + '/images/measureLine.png') self.measureLayerAction = QAction(icon, tr('Geodesic measurement layer'), self.iface.mainWindow()) self.measureLayerAction.setObjectName('stGeodesicLineBreak') self.measureLayerAction.triggered.connect(self.measureLayerTool) self.iface.addPluginToVectorMenu('Shape Tools', self.measureLayerAction) self.toolbar.addAction(self.measureLayerAction) menu = QMenu() # Initialize Geodesic transformation tool icon = QIcon(self.plugin_dir + '/images/transformShape.png') self.transformationsAction = menu.addAction( icon, tr('Geodesic transformations'), self.transformTool) self.transformationsAction.setObjectName('stGeodesicTransformations') icon = QIcon(self.plugin_dir + '/images/flip.png') self.flipRotateAction = menu.addAction(icon, tr('Geodesic flip and rotate'), self.flipRotateTool) self.flipRotateAction.setObjectName('stGeodesicFlipRotate') icon = QIcon(self.plugin_dir + '/images/flipHorizontal.png') self.flipHorizontalAction = menu.addAction(icon, tr('Flip horizontal'), self.flipHorizontalTool) self.flipHorizontalAction.setObjectName('stGeodesicFlipHorizontal') self.flipHorizontalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/flipVertical.png') self.flipVerticalAction = menu.addAction(icon, tr('Flip vertical'), self.flipVerticalTool) self.flipVerticalAction.setObjectName('stGeodesicFlipVertical') self.flipVerticalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotate180.png') self.rotate180Action = menu.addAction(icon, tr('Rotate 180\xb0'), self.rotate180Tool) self.rotate180Action.setObjectName('stGeodesicRotate180') self.rotate180Action.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotatecw.png') self.rotate90CWAction = menu.addAction(icon, tr('Rotate 90\xb0 CW'), self.rotate90CWTool) self.rotate90CWAction.setObjectName('stGeodesicRotate90CW') self.rotate90CWAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotateccw.png') self.rotate90CCWAction = menu.addAction(icon, tr('Rotate 90\xb0 CCW'), self.rotate90CCWTool) self.rotate90CCWAction.setObjectName('stGeodesicRotate90CCW') self.rotate90CCWAction.setEnabled(False) self.transformsAction = QAction(icon, tr('Geodesic transforms'), self.iface.mainWindow()) self.transformsAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.transformsAction) self.transformationButton = QToolButton() self.transformationButton.setMenu(menu) self.transformationButton.setDefaultAction(self.transformationsAction) self.transformationButton.setPopupMode(QToolButton.MenuButtonPopup) self.transformationButton.triggered.connect(self.toolButtonTriggered) self.tranformToolbar = self.toolbar.addWidget( self.transformationButton) # Initialize the Azimuth Distance Digitize function icon = QIcon(self.plugin_dir + '/images/dazdigitize.png') self.digitizeAction = QAction(icon, tr('Azimuth distance digitizer'), self.iface.mainWindow()) self.digitizeAction.setObjectName('stAzDistanceDigitizer') self.digitizeAction.triggered.connect(self.setShowAzDigitizerTool) self.digitizeAction.setCheckable(True) self.digitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.digitizeAction) self.toolbar.addAction(self.digitizeAction) # Initialize the multi point azimuth Digitize function icon = QIcon(self.plugin_dir + '/images/linedigitize.png') self.lineDigitizeAction = QAction( icon, tr('Azimuth distance sequence digitizer'), self.iface.mainWindow()) self.lineDigitizeAction.setObjectName('stLineDigitizer') self.lineDigitizeAction.triggered.connect(self.setShowLineDigitizeTool) self.lineDigitizeAction.setCheckable(True) self.lineDigitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.lineDigitizeAction) self.toolbar.addAction(self.lineDigitizeAction) # Settings icon = QIcon(self.plugin_dir + '/images/settings.png') self.settingsAction = QAction(icon, tr('Settings'), self.iface.mainWindow()) self.settingsAction.setObjectName('shapeToolsSettings') self.settingsAction.triggered.connect(self.settings) self.iface.addPluginToVectorMenu('Shape Tools', self.settingsAction) # Help icon = QIcon(self.plugin_dir + '/images/help.png') self.helpAction = QAction(icon, tr('Shape Tools help'), self.iface.mainWindow()) self.helpAction.setObjectName('shapeToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToVectorMenu('Shape Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.unsetTool) self.enableTools() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider)
def add_action(self, icon_name, callback=None, text="", enabled_flag=True, add_to_menu=False, add_to_toolbar=None, status_tip=None, whats_this=None, checkable=False, checked=False, always_on=False): icon = QIcon(icon_path(icon_name)) action = QAction(icon, text, self.iface.mainWindow()) action.triggered.connect(callback) action.setEnabled(enabled_flag) action.setCheckable(checkable) action.setChecked(checked) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar is not None: add_to_toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu(self.menu, action) self.actions.append(action) if always_on: self.actions_always_on.append(action) return action
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open Script...") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate( "PythonConsole", "Open in External Editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCut.svg")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCopy.svg")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditPaste.svg")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector...") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show Editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear Console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Options...") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run Command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help...") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(16, 16)) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(16, 16)) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) ## Menu Import Class default_command = { (QCoreApplication.translate("PythonConsole", "Import Processing Class"), QgsApplication.getThemeIcon("console/iconProcessingConsole.png")): ["import processing"], (QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore Class"), QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")): ["from qgis.PyQt.QtCore import *"], (QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui Class"), QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")): [ "from qgis.PyQt.QtGui import *", "from qgis.PyQt.QtWidgets import *" ] } self.classMenu = QMenu() for (title, icon), commands in default_command.items(): action = self.classMenu.addAction(icon, title) action.triggered.connect( partial(self.shell.commandConsole, commands)) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") self.lineEditFind.setPlaceholderText(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.triggered.connect(self._toggleFind) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.listClassMethod.itemClicked.connect(self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findNext) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) self.findScut = QShortcut(QKeySequence.Find, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._openFind) self.findNextScut = QShortcut(QKeySequence.FindNext, self.widgetEditor) self.findNextScut.setContext(Qt.WidgetWithChildrenShortcut) self.findNextScut.activated.connect(self._findNext) self.findPreviousScut = QShortcut(QKeySequence.FindPrevious, self.widgetEditor) self.findPreviousScut.setContext(Qt.WidgetWithChildrenShortcut) self.findPreviousScut.activated.connect(self._findPrev) # Escape on editor hides the find bar self.findScut = QShortcut(Qt.Key_Escape, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._closeFind)
def __init__(self, parent=None): """ QueryWidget constructor """ QuickOSMWidget.__init__(self, parent) self.setupUi(self) self.init() # Highlight XML self.highlighter = XMLHighlighter(self.textEdit_query.document()) # QGIS 3 self.pushButton_saveQuery.setVisible(False) # Setup UI self.cb_query_type.addItem(tr('Canvas Extent'), 'canvas') self.cb_query_type.addItem(tr('Layer Extent'), 'layer') self.cb_query_type.currentIndexChanged.connect(self.query_type_updated) self.label_progress.setText("") self.lineEdit_filePrefix.setDisabled(True) self.bbox = None # self.activate_extent_layer() self.pushButton_overpassTurbo.setIcon(QIcon(resources_path('turbo.png'))) # Disable buttons self.pushButton_generateQuery.setDisabled(True) self.pushButton_saveQuery.setDisabled(True) self.pushButton_runQuery.setDisabled(True) # Setup menu for saving popup_menu = QMenu() save_final_query_action = QAction( tr('Save as final query'), self.pushButton_saveQuery) save_final_query_action.triggered.connect(self.save_final_query) popup_menu.addAction(save_final_query_action) save_template_query_action = QAction( tr('Save as template'), self.pushButton_saveQuery) save_template_query_action.triggered.connect(self.save_template_query) popup_menu.addAction(save_template_query_action) self.pushButton_saveQuery.setMenu(popup_menu) # Setup menu for documentation popup_menu = QMenu() map_features_action = QAction( 'Map Features', self.pushButton_documentation) map_features_action.triggered.connect(self.open_map_features) popup_menu.addAction(map_features_action) overpass_action = QAction('Overpass', self.pushButton_documentation) overpass_action.triggered.connect(self.open_doc_overpass) popup_menu.addAction(overpass_action) self.pushButton_documentation.setMenu(popup_menu) # Enable autofill on nominatim self.init_nominatim_autofill() # connect self.pushButton_runQuery.clicked.connect(self.run_query) self.pushButton_generateQuery.clicked.connect(self.generate_query) self.textEdit_query.cursorPositionChanged.connect( self.highlighter.rehighlight) self.textEdit_query.cursorPositionChanged.connect( self.allow_nominatim_or_extent) self.pushButton_overpassTurbo.clicked.connect(self.open_overpass_turbo) self.buttonBox.button(QDialogButtonBox.Reset).clicked.connect( self.reset_form) self.query_type_updated()
def actions(self, parent): run_model_action = QAction(QCoreApplication.translate('ProcessingPlugin', '&Run Model…'), parent) run_model_action.triggered.connect(self.runModel) edit_model_action = QAction(QCoreApplication.translate('ProcessingPlugin', '&Edit Model…'), parent) edit_model_action.triggered.connect(self.editModel) return [run_model_action, edit_model_action]
class PlanetMainFilters(MAIN_FILTERS_BASE, MAIN_FILTERS_WIDGET, PlanetFilterMixin): leAOI: QLineEdit filtersChanged = pyqtSignal() savedSearchSelected = pyqtSignal(object) zoomToAOIRequested = pyqtSignal() def __init__(self, iface, parent=None, plugin=None, no_saved_search=False, color=MAIN_AOI_COLOR): super().__init__(parent=parent) self._iface: QgisInterface = iface self._plugin = plugin self.setupUi(self) self.emitFiltersChanged = False self.color = color self._aoi_box = QgsRubberBand(self._iface.mapCanvas(), QgsWkbTypes.PolygonGeometry) self._aoi_box.setFillColor(QColor(0, 0, 0, 0)) self._aoi_box.setStrokeColor(color) self._aoi_box.setWidth(3) self._aoi_box.setLineStyle(Qt.DashLine) self._canvas: QgsMapCanvas = self._iface.mapCanvas() # This may later be a nullptr, if no active tool when queried self._cur_maptool = None # noinspection PyUnresolvedReferences self.leAOI.textChanged['QString'].connect(self.filters_changed) # noinspection PyUnresolvedReferences self.leAOI.textEdited['QString'].connect(self.validate_edited_aoi) self._setup_tool_buttons() # Extent line edit tools self.btnZoomToAOI.clicked.connect(self.zoom_to_aoi) self.btnCopyAOI.clicked.connect(self.copy_aoi_to_clipboard) self.p_client = PlanetClient.getInstance() self.p_client.loginChanged.connect(self.populate_saved_searches) self.comboSavedSearch.currentIndexChanged.connect(self.saved_search_selected) if no_saved_search: self.comboSavedSearch.setVisible(False) def populate_saved_searches(self, is_logged): if is_logged: self.comboSavedSearch.blockSignals(True) self.comboSavedSearch.addItem("[Select a Saved Search]") res = self.p_client.get_searches().get() for search in res["searches"]: self.comboSavedSearch.addItem(search["name"], search) self.comboSavedSearch.blockSignals(False) def add_saved_search(self, request): self.comboSavedSearch.blockSignals(True) self.comboSavedSearch.addItem(request["name"], request) self.comboSavedSearch.setCurrentIndex(self.comboSavedSearch.count() - 1) self.comboSavedSearch.blockSignals(False) def saved_search_selected(self, idx): if idx == 0: return request = self.comboSavedSearch.currentData() self.savedSearchSelected.emit(request) def null_out_saved_search(self): self.comboSavedSearch.blockSignals(True) self.comboSavedSearch.setCurrentIndex(0) self.comboSavedSearch.blockSignals(False) def reset_aoi_box(self): self.leAOI.setText("") if self._aoi_box: self._aoi_box.reset(QgsWkbTypes.PolygonGeometry) def filters(self): filters = [] if self.leAOI.text(): # TODO: Validate GeoJSON; try planet.api.utils.probably_geojson() # noinspection PyBroadException try: if qgsgeometry_from_geojson(self.leAOI.text()): aoi = json.loads(self.leAOI.text()) filters.append(geom_filter(aoi)) else: self._show_message("AOI not valid GeoJSON polygon", level=Qgis.Warning, duration=10) except Exception: self._show_message("AOI not valid JSON", level=Qgis.Warning, duration=10) finally: return filters def filters_as_json(self): filters = [] if self.leAOI.text(): filters.append(self.leAOI.text()) return filters def set_from_request(self, request): self.emitFiltersChanged = False filters = filters_from_request(request, "geometry") if filters: geom = filters[0]["config"] txt = json.dumps(geom) self.leAOI.setText(txt) else: self.leAOI.setText("") self.emitFiltersChanged = True @pyqtSlot('QString') def filters_changed(self, value): if self.emitFiltersChanged:# noinspection PyUnresolvedReferences self.filtersChanged.emit() @pyqtSlot() def clean_up(self): self.reset_aoi_box() def _setup_tool_buttons(self): extent_menu = QMenu(self) canvas_act = QAction('Current visible extent', extent_menu) # noinspection PyUnresolvedReferences canvas_act.triggered[bool].connect(self.aoi_from_current_extent) extent_menu.addAction(canvas_act) active_act = QAction('Active map layer extent', extent_menu) # noinspection PyUnresolvedReferences active_act.triggered[bool].connect(self.aoi_from_active_layer_extent) extent_menu.addAction(active_act) full_act = QAction('All map layers extent', extent_menu) # noinspection PyUnresolvedReferences full_act.triggered[bool].connect(self.aoi_from_full_extent) extent_menu.addAction(full_act) self.btnExtent.setMenu(extent_menu) # Also show menu on click, to keep disclosure triangle visible self.btnExtent.clicked.connect(self.btnExtent.showMenu) draw_menu = QMenu(self) box_act = QAction('Rectangle', draw_menu) # noinspection PyUnresolvedReferences box_act.triggered[bool].connect(self.aoi_from_box) draw_menu.addAction(box_act) circle_act = QAction('Circle', draw_menu) # noinspection PyUnresolvedReferences circle_act.triggered[bool].connect(self.aoi_from_circle) draw_menu.addAction(circle_act) polygon_act = QAction('Polygon', draw_menu) # noinspection PyUnresolvedReferences polygon_act.triggered[bool].connect(self.aoi_from_polygon) draw_menu.addAction(polygon_act) self.btnDraw.setMenu(draw_menu) # Also show menu on click, to keep disclosure triangle visible self.btnDraw.clicked.connect(self.btnDraw.showMenu) selection_menu = QMenu(self) self.single_select_act = QAction('Single feature', selection_menu) # noinspection PyUnresolvedReferences self.single_select_act.triggered[bool].connect(self.aoi_from_feature) selection_menu.addAction(self.single_select_act) self.bound_select_act = QAction('Multiple features (bounding box)', selection_menu) # noinspection PyUnresolvedReferences self.bound_select_act.triggered[bool].connect(self.aoi_from_bound) selection_menu.addAction(self.bound_select_act) self.btnSelection.setMenu(selection_menu) # Also show menu on click, to keep disclosure triangle visible self.btnSelection.clicked.connect(self._toggle_selection_tools) self.btnSelection.clicked.connect(self.btnSelection.showMenu) def _toggle_selection_tools(self): active_layer = self._iface.activeLayer() is_vector = isinstance(active_layer, QgsVectorLayer) if is_vector and active_layer.selectedFeatureCount(): if active_layer.selectedFeatureCount() > 1: self.single_select_act.setEnabled(False) self.bound_select_act.setEnabled(True) elif active_layer.selectedFeatureCount(): self.single_select_act.setEnabled(True) self.bound_select_act.setEnabled(False) else: self.single_select_act.setEnabled(False) self.bound_select_act.setEnabled(False) else: self.single_select_act.setEnabled(False) self.bound_select_act.setEnabled(False) @pyqtSlot() # noinspection PyArgumentList def aoi_from_current_extent(self): """Return current map extent as geojson transformed to EPSG:4326 """ if not self._iface: log.debug('No iface object, skipping AOI extent') return canvas = self._iface.mapCanvas() # noinspection PyArgumentList transform = QgsCoordinateTransform( QgsProject.instance().crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance() ) canvas_extent: QgsRectangle = canvas.extent() transform_extent = transform.transformBoundingBox(canvas_extent) # noinspection PyArgumentList geom_extent = QgsGeometry.fromRect(transform_extent) extent_json = geom_extent.asJson(precision=6) # noinspection PyArgumentList self._aoi_box.setToGeometry(QgsGeometry.fromRect(canvas.extent())) self.leAOI.setText(extent_json) log.debug('AOI set to canvas extent') self.zoom_to_aoi() @pyqtSlot() # noinspection PyArgumentList def aoi_from_active_layer_extent(self): """Return active map layer extent as geojson transformed to EPSG:4326 """ if not self._iface: log.debug('No iface object, skipping AOI extent') return map_layer: QgsMapLayer = self._iface.activeLayer() if map_layer is None: log.debug('No active layer selected, skipping AOI extent') return if not map_layer.isValid(): log.debug('Active map layer invalid, skipping AOI extent') return # noinspection PyArgumentList transform = QgsCoordinateTransform( map_layer.crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance()) ml_extent: QgsRectangle = map_layer.extent() transform_extent = transform.transformBoundingBox(ml_extent) # noinspection PyArgumentList geom_extent = QgsGeometry.fromRect(transform_extent) extent_json = geom_extent.asJson(precision=6) # noinspection PyArgumentList,PyCallByClass self._aoi_box.setToGeometry(QgsGeometry.fromRect(ml_extent)) self.leAOI.setText(extent_json) log.debug('AOI set to active layer extent') self.zoom_to_aoi() @pyqtSlot() # noinspection PyArgumentList def aoi_from_full_extent(self): """Return full data map extent as geojson transformed to EPSG:4326 """ if not self._iface: log.debug('No iface object, skipping AOI extent') return canvas = self._iface.mapCanvas() # noinspection PyArgumentList transform = QgsCoordinateTransform( QgsProject.instance().crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance()) canvas_extent: QgsRectangle = canvas.fullExtent() transform_extent = transform.transformBoundingBox(canvas_extent) # noinspection PyArgumentList geom_extent = QgsGeometry.fromRect(transform_extent) extent_json = geom_extent.asJson(precision=6) # noinspection PyArgumentList,PyCallByClass self._aoi_box.setToGeometry(QgsGeometry.fromRect(canvas_extent)) self.leAOI.setText(extent_json) log.debug('AOI set to full data extent') self.zoom_to_aoi() @pyqtSlot() def aoi_from_box(self): self._cur_maptool: QgsMapTool = self._canvas.mapTool() self._aoi_box.reset(QgsWkbTypes.PolygonGeometry) aoi_draw = PlanetExtentMapTool(self._iface.mapCanvas()) self._iface.mapCanvas().setMapTool(aoi_draw) aoi_draw.extentSelected.connect(self.set_draw_aoi) @pyqtSlot() def aoi_from_circle(self): self._cur_maptool: QgsMapTool = self._canvas.mapTool() self._aoi_box.reset(QgsWkbTypes.PolygonGeometry) aoi_draw = PlanetCircleMapTool(self._iface.mapCanvas()) self._iface.mapCanvas().setMapTool(aoi_draw) aoi_draw.circleSelected.connect(self.set_draw_aoi) @pyqtSlot() def aoi_from_polygon(self): self._cur_maptool: QgsMapTool = self._canvas.mapTool() self._aoi_box.reset(QgsWkbTypes.PolygonGeometry) aoi_draw = PlanetPolyMapTool(self._iface.mapCanvas()) self._iface.mapCanvas().setMapTool(aoi_draw) aoi_draw.polygonSelected.connect(self.set_draw_aoi) @pyqtSlot(object) def set_draw_aoi(self, aoi): # noinspection PyArgumentList transform = QgsCoordinateTransform( QgsProject.instance().crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance()) aoi_json = None if isinstance(aoi, QgsRectangle): aoi_geom = QgsGeometry().fromRect(aoi) self._aoi_box.setToGeometry(aoi_geom) aoi_geom.transform(transform) aoi_json = aoi_geom.asJson(precision=6) if isinstance(aoi, QgsGeometry): if aoi.isMultipart(): aoi = QgsGeometry.fromPolygonXY(aoi.asMultiPolygon()[0]) self._aoi_box.setToGeometry(aoi) # TODO: validate geom is less than 500 vertices aoi.transform(transform) aoi_json = aoi.asJson(precision=6) if aoi_json: self.leAOI.setText(aoi_json) # noinspection PyUnresolvedReferences self._show_message('AOI set to drawn figure') self.zoom_to_aoi() if self._cur_maptool is not None: # Restore previously used maptool self._canvas.setMapTool(self._cur_maptool) self._cur_maptool = None else: # Fallback to activating pan tool self._iface.actionPan().trigger() else: # noinspection PyUnresolvedReferences self._show_message('AOI unable to be set', level=Qgis.Warning, duration=10) @pyqtSlot() def aoi_from_feature(self): layer: QgsVectorLayer = self._iface.activeLayer() if layer.selectedFeatureCount() > 1: self._show_message('More than 1 feature. Searching by bbox.', level=Qgis.Warning, duration=10) self.aoi_from_bound() return elif layer.selectedFeatureCount() < 1: self._show_message('No features selected.', level=Qgis.Warning, duration=10) return selected: QgsFeature = layer.selectedFeatures()[0] if selected.geometry().isMultipart(): multi_geom = selected.geometry().asGeometryCollection() if len(multi_geom) > 1: self._show_message( 'More than 1 geometry. Searching by bbox.', level=Qgis.Warning, duration=10 ) self.aoi_from_bound() return elif len(multi_geom) < 1: self._show_message('No geometry selected.', level=Qgis.Warning, duration=10) return else: geom: QgsGeometry = multi_geom[0] else: geom: QgsGeometry = selected.geometry() if geom.constGet().vertexCount() > 500: self._show_message( 'More than 500 vertices. Searching by bbox.', level=Qgis.Warning, duration=10 ) self.aoi_from_bound() return # noinspection PyArgumentList trans_layer = QgsCoordinateTransform( layer.sourceCrs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance() ) # noinspection PyArgumentList trans_canvas = QgsCoordinateTransform( QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance().crs(), QgsProject.instance() ) # geom.transform(transform) geom.transform(trans_layer) geom_json = geom.asJson(precision=6) self.leAOI.setText(geom_json) geom.transform(trans_canvas) self._aoi_box.setToGeometry( geom, QgsCoordinateReferenceSystem("EPSG:4326") ) self.zoom_to_aoi() @pyqtSlot() def aoi_from_bound(self): layer: QgsVectorLayer = self._iface.activeLayer() if layer.selectedFeatureCount() < 1: self._show_message('No features selected.', level=Qgis.Warning, duration=10) return bbox = layer.boundingBoxOfSelected() # noinspection PyArgumentList trans_layer = QgsCoordinateTransform( layer.sourceCrs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance() ) # noinspection PyArgumentList trans_canvas = QgsCoordinateTransform( QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance().crs(), QgsProject.instance() ) transform_bbox = trans_layer.transformBoundingBox(bbox) # noinspection PyArgumentList geom_bbox = QgsGeometry.fromRect(transform_bbox) bbox_json = geom_bbox.asJson(precision=6) self.leAOI.setText(bbox_json) bbox_canvas = trans_canvas.transformBoundingBox(transform_bbox) # noinspection PyArgumentList self._aoi_box.setToGeometry(QgsGeometry.fromRect(bbox_canvas)) self.zoom_to_aoi() def hide_aoi_if_matches_geom(self, geom): color = (QColor(0, 0, 0, 0) if self._aoi_box.asGeometry().equals(geom) else self.color) self._aoi_box.setStrokeColor(color) def show_aoi(self): if self._aoi_box is not None: self._aoi_box.setStrokeColor(self.color) def aoi_geom(self): if self._aoi_box is not None: return self._aoi_box.asGeometry() def aoi_as_4326_geom(self): transform = QgsCoordinateTransform( QgsProject.instance().crs(), QgsCoordinateReferenceSystem("EPSG:4326"), QgsProject.instance() ) geom = self.aoi_geom() if geom is not None: geom.transform(transform) return geom @pyqtSlot() def zoom_to_aoi(self): if not self._iface: log.debug('No iface object, skipping AOI extent') return if not self.leAOI.text(): log.debug('No AOI defined, skipping zoom to AOI') return geom: QgsGeometry = qgsgeometry_from_geojson(self.leAOI.text()) self._aoi_box.setToGeometry( geom, QgsCoordinateReferenceSystem("EPSG:4326") ) self.show_aoi() zoom_canvas_to_aoi(self.leAOI.text()) self.zoomToAOIRequested.emit() @pyqtSlot() def copy_aoi_to_clipboard(self): if not self.leAOI.text(): log.debug('No AOI defined, skipping zoom to AOI') return json_geom_txt = json.dumps(json.loads(self.leAOI.text()), indent=2) cb = QgsApplication.clipboard() cb.setText(json_geom_txt) # noinspection PyUnresolvedReferences self._show_message('AOI copied to clipboard') @pyqtSlot() def validate_aoi(self): # TODO:gather existing validation logic here # TODO: Check for valid json.loads # TODO: Check API verticie limit of 500 pass @pyqtSlot() def validate_edited_aoi(self): json_txt = self.leAOI.text() if not json_txt: self.reset_aoi_box() log.debug('No AOI defined, skipping validation') return try: json_obj = json.loads(json_txt) except ValueError: # noinspection PyUnresolvedReferences self._show_message('AOI GeoJSON is invalid', level=Qgis.Warning, duration=10) return json_geom = geometry_from_json(json_obj) if not json_geom: # noinspection PyUnresolvedReferences self._show_message('AOI GeoJSON geometry invalid', level=Qgis.Warning, duration=10) return geom: QgsGeometry = qgsgeometry_from_geojson(json_geom) self._aoi_box.setToGeometry( geom, QgsCoordinateReferenceSystem("EPSG:4326") ) self.leAOI.blockSignals(True) self.leAOI.setText(json.dumps(json_geom)) self.leAOI.blockSignals(False) self.zoom_to_aoi()
class SplitFeaturesOnSteroidsPlugin(object): mapTool = None def __init__(self, iface): self.iface = iface def initGui(self): self.toolbar = self.iface.addToolBar(name) self.toolbar.setObjectName(name) icon = QIcon(":/plugins/SplitPolygonShowingAreas/icon.png") self.action = QAction(icon, name, self.iface.mainWindow()) self.action.setCheckable(True) self.action.triggered.connect(self.onClick) self.toolbar.addAction(self.action) self.actionMoveVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveVertices.png"), moveVerticesName, self.iface.mainWindow()) self.actionMoveVertices.setCheckable(True) self.actionMoveVertices.triggered.connect(self.onClickMoveVertices) self.toolbar.addAction(self.actionMoveVertices) self.actionAddVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/addVertices.png"), addVerticesName, self.iface.mainWindow()) self.actionAddVertices.setCheckable(True) self.actionAddVertices.triggered.connect(self.onClickAddVertices) self.toolbar.addAction(self.actionAddVertices) self.actionRemoveVertices = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/removeVertices.png"), removeVerticesName, self.iface.mainWindow()) self.actionRemoveVertices.setCheckable(True) self.actionRemoveVertices.triggered.connect(self.onClickRemoveVertices) self.toolbar.addAction(self.actionRemoveVertices) self.actionMoveSegment = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveSegment.png"), moveSegmentName, self.iface.mainWindow()) self.actionMoveSegment.setCheckable(True) self.actionMoveSegment.triggered.connect(self.onClickMoveSegment) self.toolbar.addAction(self.actionMoveSegment) self.actionLineClose = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/lineClose.png"), closeLineName, self.iface.mainWindow()) self.actionLineClose.setCheckable(False) self.actionLineClose.triggered.connect(self.onClickLineClose) self.toolbar.addAction(self.actionLineClose) self.actionLineOpen = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/lineOpen.png"), openLineName, self.iface.mainWindow()) self.actionLineOpen.setCheckable(False) self.actionLineOpen.triggered.connect(self.onClickLineOpen) self.toolbar.addAction(self.actionLineOpen) self.actionMoveLine = QAction( QIcon(":/plugins/SplitPolygonShowingAreas/moveLine.png"), moveLineName, self.iface.mainWindow()) self.actionMoveLine.setCheckable(True) self.actionMoveLine.triggered.connect(self.onClickMoveLine) self.toolbar.addAction(self.actionMoveLine) self.iface.addPluginToMenu(name, self.action) self.iface.addPluginToMenu(name, self.actionMoveVertices) self.iface.addPluginToMenu(name, self.actionAddVertices) self.iface.addPluginToMenu(name, self.actionRemoveVertices) self.iface.addPluginToMenu(name, self.actionMoveSegment) self.iface.addPluginToMenu(name, self.actionLineClose) self.iface.addPluginToMenu(name, self.actionLineOpen) self.iface.addPluginToMenu(name, self.actionMoveLine) self.help_action = QAction("Help", self.iface.mainWindow()) self.help_action.triggered.connect(self.onHelp) self.iface.addPluginToMenu(name, self.help_action) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.enableTool() def disableAll(self): self.actionMoveVertices.setChecked(False) self.actionMoveVertices.setEnabled(False) self.actionAddVertices.setChecked(False) self.actionAddVertices.setEnabled(False) self.actionRemoveVertices.setChecked(False) self.actionRemoveVertices.setEnabled(False) self.actionMoveSegment.setChecked(False) self.actionMoveSegment.setEnabled(False) self.actionLineClose.setEnabled(False) self.actionLineOpen.setEnabled(False) self.actionMoveLine.setChecked(False) self.actionMoveLine.setEnabled(False) def unload(self): self.iface.removePluginMenu(name, self.action) self.iface.removePluginMenu(name, self.actionMoveVertices) self.iface.removePluginMenu(name, self.actionAddVertices) self.iface.removePluginMenu(name, self.actionRemoveVertices) self.iface.removePluginMenu(name, self.actionMoveSegment) self.iface.removePluginMenu(name, self.actionLineClose) self.iface.removePluginMenu(name, self.actionLineOpen) self.iface.removePluginMenu(name, self.actionMoveLine) self.iface.removePluginMenu(name, self.help_action) self.iface.removeToolBarIcon(self.action) self.iface.removeToolBarIcon(self.actionMoveVertices) self.iface.removeToolBarIcon(self.actionAddVertices) self.iface.removeToolBarIcon(self.actionRemoveVertices) self.iface.removeToolBarIcon(self.actionMoveSegment) self.iface.removeToolBarIcon(self.actionLineClose) self.iface.removeToolBarIcon(self.actionLineOpen) self.iface.removeToolBarIcon(self.actionMoveLine) def onHelp(self): qgis.utils.showPluginHelp(filename="index") def onClick(self): self.disableAll() if not self.action.isChecked(): if self.mapTool != None and len(self.mapTool.capturedPoints) >= 2: reply = QMessageBox.question( self.iface.mapCanvas(), "Cancel splitting line?", "Your splitting line has " + str(len(self.mapTool.capturedPoints)) + " points. Do you want to remove it?", QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.No: self.action.setChecked(True) self.mapTool.restoreAction() return if self.mapTool != None: self.mapTool.stopCapturing() self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None return layer = self.iface.activeLayer() if layer == None or not isinstance(layer, QgsVectorLayer) or ( layer.wkbType() != QgsWkbTypes.Polygon and layer.wkbType() != QgsWkbTypes.MultiPolygon and layer.wkbType() != QgsWkbTypes.Polygon25D and layer.wkbType() != QgsWkbTypes.MultiPoint25D): self.iface.messageBar().pushMessage( "No Polygon Vectorial Layer Selected", "Select a Polygon Vectorial Layer first", level=QgsMessageBar.WARNING) self.action.setChecked(False) return selectedFeatures = layer.selectedFeatures() if selectedFeatures == None or len(selectedFeatures) == 0: self.iface.messageBar().pushMessage("No Features Selected", "Select some features first", level=QgsMessageBar.WARNING) self.action.setChecked(False) return self.action.setChecked(True) self.mapTool = SplitMapTool( self.iface.mapCanvas(), layer, self.actionMoveVertices, self.actionAddVertices, self.actionRemoveVertices, self.actionMoveSegment, self.actionLineClose, self.actionLineOpen, self.actionMoveLine) self.mapTool.setAction(self.action) self.iface.mapCanvas().setMapTool(self.mapTool) self.mapTool.redrawActions() def onClickMoveVertices(self): if not self.actionMoveVertices.isChecked(): if self.mapTool != None: self.mapTool.stopMovingVertices() return self.mapTool.startMovingVertices() def onClickAddVertices(self): if not self.actionAddVertices.isChecked(): if self.mapTool != None: self.mapTool.stopAddingVertices() return self.actionAddVertices.setChecked(True) self.mapTool.startAddingVertices() def onClickRemoveVertices(self): if not self.actionRemoveVertices.isChecked(): if self.mapTool != None: self.mapTool.stopRemovingVertices() return self.actionRemoveVertices.setChecked(True) self.mapTool.startRemovingVertices() def onClickMoveSegment(self): if not self.actionMoveSegment.isChecked(): if self.mapTool != None: self.mapTool.stopMovingSegment() return self.actionMoveSegment.setChecked(True) self.mapTool.startMovingSegment() def onClickLineClose(self): self.mapTool.lineClose() def onClickLineOpen(self): self.mapTool.lineOpen() def onClickMoveLine(self): if not self.actionMoveLine.isChecked(): if self.mapTool != None: self.mapTool.stopMovingLine() return self.actionMoveLine.setChecked(True) self.mapTool.startMovingLine() def currentLayerChanged(self): if self.mapTool != None: self.mapTool.stopCapturing() layer = self.iface.activeLayer() if layer != None: try: layer.editingStarted.disconnect(self.layerEditingChanged) except: pass try: layer.editingStopped.disconnect(self.layerEditingChanged) except: pass try: layer.selectionChanged.disconnect(self.layerEditingChanged) except: pass if isinstance(layer, QgsVectorLayer): layer.editingStarted.connect(self.layerEditingChanged) layer.editingStopped.connect(self.layerEditingChanged) layer.selectionChanged.connect(self.layerSelectionChanged) self.enableTool() def layerEditingChanged(self): if self.mapTool != None: self.mapTool.stopCapturing() self.enableTool() def layerSelectionChanged(self): if self.mapTool != None: self.mapTool.stopCapturing() self.enableTool() def enableTool(self): self.disableAll() self.action.setEnabled(False) layer = self.iface.activeLayer() if layer != None and isinstance(layer, QgsVectorLayer): selectedFeatures = layer.selectedFeatures() if isinstance(layer, QgsVectorLayer) and ( layer.wkbType() == QgsWkbTypes.Polygon or layer.wkbType() == QgsWkbTypes.MultiPolygon or layer.wkbType() == QgsWkbTypes.Polygon25D or layer.wkbType() == QgsWkbTypes.MultiPoint25D ) and selectedFeatures != None and len( selectedFeatures) > 0 and layer.isEditable(): self.action.setEnabled(True)
class ShapeTools(object): def __init__(self, iface): self.iface = iface self.canvas = iface.mapCanvas() self.settingsDialog = None self.xyLineDialog = None self.geodesicDensifyDialog = None self.azDigitizerTool = None self.lineDigitizerTool = None self.previousLayer = None self.toolbar = self.iface.addToolBar('Shape Tools Toolbar') self.toolbar.setObjectName('ShapeToolsToolbar') self.provider = ShapeToolsProvider() # Initialize the plugin path directory self.plugin_dir = os.path.dirname(__file__) # initialize locale try: locale = QSettings().value("locale/userLocale", "en", type=str)[0:2] except Exception: locale = "en" locale_path = os.path.join(self.plugin_dir, 'i18n', 'shapeTools_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) def initGui(self): self.azDigitizerTool = AzDigitizerTool(self.iface) self.lineDigitizerTool = LineDigitizerTool(self.iface) # Initialize the create shape menu items menu = QMenu() # Initialize Create Arc Wedge tool icon = QIcon(self.plugin_dir + '/images/arc.png') self.createArcAction = menu.addAction(icon, tr('Create arc wedge'), self.createArc) self.createArcAction.setObjectName('stCreateArcWedge') icon = QIcon(self.plugin_dir + '/images/donut.png') self.createDonutAction = menu.addAction(icon, tr('Create donut'), self.createDonut) self.createDonutAction.setObjectName('stCreateDonut') icon = QIcon(self.plugin_dir + '/images/ellipse.png') self.createEllipseAction = menu.addAction(icon, tr('Create ellipse'), self.createEllipse) self.createEllipseAction.setObjectName('stCreateEllipse') icon = QIcon(self.plugin_dir + '/images/rose.png') self.createEllipseRoseAction = menu.addAction( icon, tr('Create ellipse rose'), self.createEllipseRose) self.createEllipseRoseAction.setObjectName('stCreateEllipseRose') icon = QIcon(self.plugin_dir + '/images/epicycloid.png') self.createEpicycloidAction = menu.addAction(icon, tr('Create epicycloid'), self.createEpicycloid) self.createEpicycloidAction.setObjectName('stCreateEpicycloid') icon = QIcon(self.plugin_dir + '/images/heart.png') self.createHeartAction = menu.addAction(icon, tr('Create heart'), self.createHeart) self.createHeartAction.setObjectName('stCreateHeart') icon = QIcon(self.plugin_dir + '/images/hypocycloid.png') self.createHypocycloidAction = menu.addAction(icon, tr('Create hypocycloid'), self.createHypocycloid) self.createHypocycloidAction.setObjectName('stCreateHypocycloid') icon = QIcon(self.plugin_dir + '/images/line.png') self.createLOBAction = menu.addAction(icon, tr('Create line of bearing'), self.createLOB) self.createLOBAction.setObjectName('stCreateLineOfBearing') icon = QIcon(self.plugin_dir + '/images/pie.png') self.createPieAction = menu.addAction(icon, tr('Create pie wedge'), self.createPie) self.createPieAction.setObjectName('stCreatePie') icon = QIcon(self.plugin_dir + '/images/polyfoil.png') self.createPolyfoilAction = menu.addAction(icon, tr('Create polyfoil'), self.createPolyfoil) self.createPolyfoilAction.setObjectName('stCreatePolyfoil') icon = QIcon(self.plugin_dir + '/images/polygon.png') self.createPolygonAction = menu.addAction(icon, tr('Create polygon'), self.createPolygon) self.createPolygonAction.setObjectName('stCreatePolygon') icon = QIcon(self.plugin_dir + '/images/radialLines.png') self.createPolygonAction = menu.addAction(icon, tr('Create radial lines'), self.createRadialLines) self.createPolygonAction.setObjectName('stCreateRadialLines') icon = QIcon(self.plugin_dir + '/images/star.png') self.createStarAction = menu.addAction(icon, tr('Create star'), self.createStar) self.createStarAction.setObjectName('stCreateStar') # Add the shape creation tools to the menu icon = QIcon(self.plugin_dir + '/images/shapes.png') self.createShapesAction = QAction(icon, tr('Create shapes'), self.iface.mainWindow()) self.createShapesAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.createShapesAction) # Add the shape creation tools to the toolbar self.createShapeButton = QToolButton() self.createShapeButton.setMenu(menu) self.createShapeButton.setDefaultAction(self.createDonutAction) self.createShapeButton.setPopupMode(QToolButton.MenuButtonPopup) self.createShapeButton.triggered.connect(self.createShapeTriggered) self.createShapeToolbar = self.toolbar.addWidget( self.createShapeButton) # Initialize the XY to Line menu item icon = QIcon(self.plugin_dir + '/images/xyline.png') self.xyLineAction = QAction(icon, tr('XY to line'), self.iface.mainWindow()) self.xyLineAction.setObjectName('stXYtoLine') self.xyLineAction.triggered.connect(self.xyLineTool) self.iface.addPluginToVectorMenu('Shape Tools', self.xyLineAction) self.toolbar.addAction(self.xyLineAction) # Initialize the Geodesic Densifier menu item icon = QIcon(self.plugin_dir + '/images/geodesicDensifier.png') self.geodesicDensifyAction = QAction(icon, tr('Geodesic shape densifier'), self.iface.mainWindow()) self.geodesicDensifyAction.setObjectName('stGeodesicDensifier') self.geodesicDensifyAction.triggered.connect(self.geodesicDensifyTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicDensifyAction) self.toolbar.addAction(self.geodesicDensifyAction) # Initialize the Geodesic decimation menu items menu = QMenu() icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.png') self.lineDecimateAction = menu.addAction(icon, tr('Geodesic line decimate'), self.lineDecimateTool) self.lineDecimateAction.setObjectName('stGeodesicLineDecimate') icon = QIcon(self.plugin_dir + '/images/geodesicPointDecimate.png') self.pointDecimateAction = menu.addAction( icon, tr('Geodesic point decimate'), self.pointDecimateTool) self.pointDecimateAction.setObjectName('stGeodesicPointDecimate') # Add the decimation tools to the menu icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.png') self.simplifyGeomAction = QAction( icon, tr('Geodesic geometry simplification'), self.iface.mainWindow()) self.simplifyGeomAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.simplifyGeomAction) # Add the shape creation tools to the toolbar self.simplifyButton = QToolButton() self.simplifyButton.setMenu(menu) self.simplifyButton.setDefaultAction(self.lineDecimateAction) self.simplifyButton.setPopupMode(QToolButton.MenuButtonPopup) self.simplifyButton.triggered.connect(self.simplifyTriggered) self.simplifyToolbar = self.toolbar.addWidget(self.simplifyButton) # Initialize the Geodesic line break menu item icon = QIcon(self.plugin_dir + '/images/idlbreak.png') self.geodesicLineBreakAction = QAction( icon, tr('Geodesic line break at -180,180'), self.iface.mainWindow()) self.geodesicLineBreakAction.setObjectName('stGeodesicLineBreak') self.geodesicLineBreakAction.triggered.connect( self.geodesicLineBreakTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicLineBreakAction) self.toolbar.addAction(self.geodesicLineBreakAction) # Initialize Geodesic Measure Tool self.geodesicMeasureTool = GeodesicMeasureTool(self.iface, self.iface.mainWindow()) icon = QIcon(self.plugin_dir + '/images/measure.png') self.measureAction = QAction(icon, tr('Geodesic measure tool'), self.iface.mainWindow()) self.measureAction.setObjectName('stGeodesicMeasureTool') self.measureAction.triggered.connect(self.measureTool) self.measureAction.setCheckable(True) self.iface.addPluginToVectorMenu('Shape Tools', self.measureAction) self.toolbar.addAction(self.measureAction) # Initialize Geodesic Measurement layer icon = QIcon(self.plugin_dir + '/images/measureLine.png') self.measureLayerAction = QAction(icon, tr('Geodesic measurement layer'), self.iface.mainWindow()) self.measureLayerAction.setObjectName('stGeodesicLineBreak') self.measureLayerAction.triggered.connect(self.measureLayerTool) self.iface.addPluginToVectorMenu('Shape Tools', self.measureLayerAction) self.toolbar.addAction(self.measureLayerAction) menu = QMenu() # Initialize Geodesic transformation tool icon = QIcon(self.plugin_dir + '/images/transformShape.png') self.transformationsAction = menu.addAction( icon, tr('Geodesic transformations'), self.transformTool) self.transformationsAction.setObjectName('stGeodesicTransformations') icon = QIcon(self.plugin_dir + '/images/flip.png') self.flipRotateAction = menu.addAction(icon, tr('Geodesic flip and rotate'), self.flipRotateTool) self.flipRotateAction.setObjectName('stGeodesicFlipRotate') icon = QIcon(self.plugin_dir + '/images/flipHorizontal.png') self.flipHorizontalAction = menu.addAction(icon, tr('Flip horizontal'), self.flipHorizontalTool) self.flipHorizontalAction.setObjectName('stGeodesicFlipHorizontal') self.flipHorizontalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/flipVertical.png') self.flipVerticalAction = menu.addAction(icon, tr('Flip vertical'), self.flipVerticalTool) self.flipVerticalAction.setObjectName('stGeodesicFlipVertical') self.flipVerticalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotate180.png') self.rotate180Action = menu.addAction(icon, tr('Rotate 180\xb0'), self.rotate180Tool) self.rotate180Action.setObjectName('stGeodesicRotate180') self.rotate180Action.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotatecw.png') self.rotate90CWAction = menu.addAction(icon, tr('Rotate 90\xb0 CW'), self.rotate90CWTool) self.rotate90CWAction.setObjectName('stGeodesicRotate90CW') self.rotate90CWAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotateccw.png') self.rotate90CCWAction = menu.addAction(icon, tr('Rotate 90\xb0 CCW'), self.rotate90CCWTool) self.rotate90CCWAction.setObjectName('stGeodesicRotate90CCW') self.rotate90CCWAction.setEnabled(False) self.transformsAction = QAction(icon, tr('Geodesic transforms'), self.iface.mainWindow()) self.transformsAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.transformsAction) self.transformationButton = QToolButton() self.transformationButton.setMenu(menu) self.transformationButton.setDefaultAction(self.transformationsAction) self.transformationButton.setPopupMode(QToolButton.MenuButtonPopup) self.transformationButton.triggered.connect(self.toolButtonTriggered) self.tranformToolbar = self.toolbar.addWidget( self.transformationButton) # Initialize the Azimuth Distance Digitize function icon = QIcon(self.plugin_dir + '/images/dazdigitize.png') self.digitizeAction = QAction(icon, tr('Azimuth distance digitizer'), self.iface.mainWindow()) self.digitizeAction.setObjectName('stAzDistanceDigitizer') self.digitizeAction.triggered.connect(self.setShowAzDigitizerTool) self.digitizeAction.setCheckable(True) self.digitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.digitizeAction) self.toolbar.addAction(self.digitizeAction) # Initialize the multi point azimuth Digitize function icon = QIcon(self.plugin_dir + '/images/linedigitize.png') self.lineDigitizeAction = QAction( icon, tr('Azimuth distance sequence digitizer'), self.iface.mainWindow()) self.lineDigitizeAction.setObjectName('stLineDigitizer') self.lineDigitizeAction.triggered.connect(self.setShowLineDigitizeTool) self.lineDigitizeAction.setCheckable(True) self.lineDigitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.lineDigitizeAction) self.toolbar.addAction(self.lineDigitizeAction) # Settings icon = QIcon(self.plugin_dir + '/images/settings.png') self.settingsAction = QAction(icon, tr('Settings'), self.iface.mainWindow()) self.settingsAction.setObjectName('shapeToolsSettings') self.settingsAction.triggered.connect(self.settings) self.iface.addPluginToVectorMenu('Shape Tools', self.settingsAction) # Help icon = QIcon(self.plugin_dir + '/images/help.png') self.helpAction = QAction(icon, tr('Shape Tools help'), self.iface.mainWindow()) self.helpAction.setObjectName('shapeToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToVectorMenu('Shape Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.unsetTool) self.enableTools() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider) def unsetTool(self, tool): try: if not isinstance(tool, GeodesicMeasureTool): self.measureAction.setChecked(False) self.geodesicMeasureTool.endInteractiveLine() if not isinstance(tool, AzDigitizerTool): self.digitizeAction.setChecked(False) if not isinstance(tool, LineDigitizerTool): self.lineDigitizeAction.setChecked(False) except Exception: pass def unload(self): self.canvas.unsetMapTool(self.azDigitizerTool) self.canvas.unsetMapTool(self.lineDigitizerTool) # remove from menu self.iface.removePluginVectorMenu('Shape Tools', self.createShapesAction) self.iface.removePluginVectorMenu('Shape Tools', self.xyLineAction) self.iface.removePluginVectorMenu('Shape Tools', self.geodesicDensifyAction) self.iface.removePluginVectorMenu('Shape Tools', self.simplifyGeomAction) self.iface.removePluginVectorMenu('Shape Tools', self.geodesicLineBreakAction) self.iface.removePluginVectorMenu('Shape Tools', self.measureAction) self.iface.removePluginVectorMenu('Shape Tools', self.measureLayerAction) self.iface.removePluginVectorMenu('Shape Tools', self.transformsAction) self.iface.removePluginVectorMenu('Shape Tools', self.digitizeAction) self.iface.removePluginVectorMenu('Shape Tools', self.lineDigitizeAction) self.iface.removePluginVectorMenu('Shape Tools', self.settingsAction) self.iface.removePluginVectorMenu('Shape Tools', self.helpAction) # Remove from toolbar self.iface.removeToolBarIcon(self.createShapeToolbar) self.iface.removeToolBarIcon(self.xyLineAction) self.iface.removeToolBarIcon(self.geodesicDensifyAction) self.iface.removeToolBarIcon(self.simplifyToolbar) self.iface.removeToolBarIcon(self.geodesicLineBreakAction) self.iface.removeToolBarIcon(self.measureAction) self.iface.removeToolBarIcon(self.measureLayerAction) self.iface.removeToolBarIcon(self.transformationsAction) self.iface.removeToolBarIcon(self.digitizeAction) self.iface.removeToolBarIcon(self.lineDigitizeAction) self.iface.removeToolBarIcon(self.tranformToolbar) self.azDigitizerTool = None self.lineDigitizerTool = None # remove the toolbar del self.toolbar QgsApplication.processingRegistry().removeProvider(self.provider) def toolButtonTriggered(self, action): self.transformationButton.setDefaultAction(action) def createShapeTriggered(self, action): self.createShapeButton.setDefaultAction(action) def simplifyTriggered(self, action): self.simplifyButton.setDefaultAction(action) def setShowAzDigitizerTool(self): self.digitizeAction.setChecked(True) self.canvas.setMapTool(self.azDigitizerTool) def setShowLineDigitizeTool(self): self.lineDigitizeAction.setChecked(True) self.canvas.setMapTool(self.lineDigitizerTool) def xyLineTool(self): processing.execAlgorithmDialog('shapetools:xy2line', {}) def geodesicDensifyTool(self): processing.execAlgorithmDialog('shapetools:geodesicdensifier', {}) def pointDecimateTool(self): processing.execAlgorithmDialog('shapetools:geodesicpointdecimate', {}) def lineDecimateTool(self): processing.execAlgorithmDialog('shapetools:geodesiclinedecimate', {}) def geodesicLineBreakTool(self): processing.execAlgorithmDialog('shapetools:linebreak', {}) def measureTool(self): self.measureAction.setChecked(True) self.canvas.setMapTool(self.geodesicMeasureTool) def createArc(sefl): processing.execAlgorithmDialog('shapetools:createarc', {}) def createDonut(sefl): processing.execAlgorithmDialog('shapetools:createdonut', {}) def createEllipse(sefl): processing.execAlgorithmDialog('shapetools:createellipse', {}) def createEllipseRose(sefl): processing.execAlgorithmDialog('shapetools:createrose', {}) def createEpicycloid(sefl): processing.execAlgorithmDialog('shapetools:createepicycloid', {}) def createHeart(sefl): processing.execAlgorithmDialog('shapetools:createheart', {}) def createHypocycloid(sefl): processing.execAlgorithmDialog('shapetools:createhypocycloid', {}) def createLOB(sefl): processing.execAlgorithmDialog('shapetools:createlob', {}) def createPie(sefl): processing.execAlgorithmDialog('shapetools:createpie', {}) def createPolyfoil(sefl): processing.execAlgorithmDialog('shapetools:createpolyfoil', {}) def createPolygon(sefl): processing.execAlgorithmDialog('shapetools:createpolygon', {}) def createRadialLines(sefl): processing.execAlgorithmDialog('shapetools:createradiallines', {}) def createStar(sefl): processing.execAlgorithmDialog('shapetools:createstar', {}) def measureLayerTool(self): processing.execAlgorithmDialog('shapetools:measurelayer', {}) def transformTool(self): processing.execAlgorithmDialog('shapetools:geodesictransformations', {}) def flipRotateTool(self): processing.execAlgorithmDialog('shapetools:geodesicflip', {}) def flipHorizontalTool(self): layer = self.iface.activeLayer() flipLayer(self.iface, layer, 0) def flipVerticalTool(self): layer = self.iface.activeLayer() flipLayer(self.iface, layer, 1) def rotate180Tool(self): layer = self.iface.activeLayer() flipLayer(self.iface, layer, 2) def rotate90CWTool(self): layer = self.iface.activeLayer() flipLayer(self.iface, layer, 3) def rotate90CCWTool(self): layer = self.iface.activeLayer() flipLayer(self.iface, layer, 4) def settings(self): if self.settingsDialog is None: self.settingsDialog = SettingsWidget(self.iface, self.iface.mainWindow()) self.settingsDialog.show() def help(self): '''Display a help page''' url = QUrl.fromLocalFile(self.plugin_dir + '/index.html').toString() webbrowser.open(url, new=2) def currentLayerChanged(self): layer = self.iface.activeLayer() if self.previousLayer is not None: try: self.previousLayer.editingStarted.disconnect( self.layerEditingChanged) except Exception: pass try: self.previousLayer.editingStopped.disconnect( self.layerEditingChanged) except Exception: pass self.previousLayer = None if layer is not None: if isinstance(layer, QgsVectorLayer): layer.editingStarted.connect(self.layerEditingChanged) layer.editingStopped.connect(self.layerEditingChanged) self.previousLayer = layer self.enableTools() def layerEditingChanged(self): self.enableTools() def enableTools(self): self.digitizeAction.setEnabled(False) self.lineDigitizeAction.setEnabled(False) self.flipHorizontalAction.setEnabled(False) self.flipVerticalAction.setEnabled(False) self.rotate180Action.setEnabled(False) self.rotate90CWAction.setEnabled(False) self.rotate90CCWAction.setEnabled(False) layer = self.iface.activeLayer() if not layer or not layer.isValid() or ( layer.type() != QgsMapLayer.VectorLayer) or not layer.isEditable(): return wkbtype = layer.wkbType() geomtype = QgsWkbTypes.geometryType(wkbtype) self.lineDigitizeAction.setEnabled(True) if geomtype == QgsWkbTypes.PointGeometry or geomtype == QgsWkbTypes.LineGeometry: self.digitizeAction.setEnabled(True) if geomtype == QgsWkbTypes.LineGeometry or geomtype == QgsWkbTypes.PolygonGeometry: self.flipHorizontalAction.setEnabled(True) self.flipVerticalAction.setEnabled(True) self.rotate180Action.setEnabled(True) self.rotate90CWAction.setEnabled(True) self.rotate90CCWAction.setEnabled(True)
class PythonConsoleWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) ##------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) #self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) #self.splitterObj.setSizes([0, 0]) #self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) #self.splitterEditor.addWidget(self.widgetEditor) #self.splitterObj.addWidget(self.listClassMethod) #self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() sizes = self.splitter.sizes() self.splitter.setSizes(sizes) ##----------------Restore Settings------------------------------------ self.restoreSettingsConsole() ##------------------Toolbar Editor------------------------------------- ## Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open Script...") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("console/iconOpenConsole.png")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate( "PythonConsole", "Open in External Editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) ## Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveConsole.png")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) ## Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("console/iconSaveAsConsole.png")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) ## Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCut.svg")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) ## Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCopy.svg")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) ## Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditPaste.svg")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) ## Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconRunScriptConsole.png")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) ## Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.png")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) ## Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.png")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) ## Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector...") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) ## Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) ##----------------Toolbar Console------------------------------------- ## Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show Editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.png")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) ## Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear Console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.png")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) ## Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Options...") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.png")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) ## Action menu for class actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class") self.actionClass = QAction(self) self.actionClass.setCheckable(False) self.actionClass.setEnabled(True) self.actionClass.setIcon( QgsApplication.getThemeIcon("console/iconClassConsole.png")) self.actionClass.setMenuRole(QAction.PreferencesRole) self.actionClass.setIconVisibleInMenu(True) self.actionClass.setToolTip(actionClassBt) self.actionClass.setText(actionClassBt) ## Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run Command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/iconRunConsole.png")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) ## Help action helpBt = QCoreApplication.translate("PythonConsole", "Help...") self.helpButton = QAction(self) self.helpButton.setCheckable(False) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.png")) self.helpButton.setMenuRole(QAction.PreferencesRole) self.helpButton.setIconVisibleInMenu(True) self.helpButton.setToolTip(helpBt) self.helpButton.setText(helpBt) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(QSize(16, 16)) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.actionClass) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addAction(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(QSize(16, 16)) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) ## Menu Import Class default_command = { (QCoreApplication.translate("PythonConsole", "Import Processing Class"), QgsApplication.getThemeIcon("console/iconProcessingConsole.png")): ["import processing"], (QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore Class"), QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")): ["from qgis.PyQt.QtCore import *"], (QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui Class"), QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")): [ "from qgis.PyQt.QtGui import *", "from qgis.PyQt.QtWidgets import *" ] } self.classMenu = QMenu() for (title, icon), commands in default_command.items(): action = self.classMenu.addAction(icon, title) action.triggered.connect( partial(self.shell.commandConsole, commands)) cM = self.toolBar.widgetForAction(self.actionClass) cM.setMenu(self.classMenu) cM.setPopupMode(QToolButton.InstantPopup) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) ##------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) ## Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...") self.lineEditFind.setPlaceholderText(placeHolderTxt) self.findNextButton = QToolButton() self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.png")) self.findNextButton.setIconSize(QSize(24, 24)) self.findNextButton.setAutoRaise(True) self.findPrevButton = QToolButton() self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.png")) self.findPrevButton.setIconSize(QSize(24, 24)) self.findPrevButton.setAutoRaise(True) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1) self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1) self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1) self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1) self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1) self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1) ##------------ Add first Tab in Editor ------------------------------- #self.tabEditorWidget.newTabEditor(tabName='first', filename=None) ##------------ Signal ------------------------------- self.findTextButton.triggered.connect(self._toggleFind) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpButton.triggered.connect(self.openHelp) self.listClassMethod.itemClicked.connect(self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findNext) self.findNextButton.clicked.connect(self._findNext) self.findPrevButton.clicked.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) self.findScut = QShortcut(QKeySequence.Find, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._openFind) self.findNextScut = QShortcut(QKeySequence.FindNext, self.widgetEditor) self.findNextScut.setContext(Qt.WidgetWithChildrenShortcut) self.findNextScut.activated.connect(self._findNext) self.findPreviousScut = QShortcut(QKeySequence.FindPrevious, self.widgetEditor) self.findPreviousScut.setContext(Qt.WidgetWithChildrenShortcut) self.findPreviousScut.activated.connect(self._findPrev) # Escape on editor hides the find bar self.findScut = QShortcut(Qt.Key_Escape, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._closeFind) def _toggleFind(self): self.tabEditorWidget.currentWidget().newEditor.toggleFindWidget() def _openFind(self): self.tabEditorWidget.currentWidget().newEditor.openFindWidget() def _closeFind(self): self.tabEditorWidget.currentWidget().newEditor.closeFindWidget() def _findNext(self): self.tabEditorWidget.currentWidget().newEditor.findText(True) def _findPrev(self): self.tabEditorWidget.currentWidget().newEditor.findText(False) def _textFindChanged(self): if self.lineEditFind.text(): self.findNextButton.setEnabled(True) self.findPrevButton.setEnabled(True) self.tabEditorWidget.currentWidget().newEditor.findText( True, showMessage=False, findFirst=True) else: self.lineEditFind.setStyleSheet('') self.findNextButton.setEnabled(False) self.findPrevButton.setEnabled(False) def onClickGoToLine(self, item, column): tabEditor = self.tabEditorWidget.currentWidget().newEditor if item.text(1) == 'syntaxError': check = tabEditor.syntaxCheck(fromContextMenu=False) if check and not tabEditor.isReadOnly(): self.tabEditorWidget.currentWidget().save() return linenr = int(item.text(1)) itemName = str(item.text(0)) charPos = itemName.find(' ') if charPos != -1: objName = itemName[0:charPos] else: objName = itemName tabEditor.goToLine(objName, linenr) def toggleEditor(self, checked): self.splitterObj.show() if checked else self.splitterObj.hide() if not self.tabEditorWidget: self.tabEditorWidget.enableToolBarEditor(checked) self.tabEditorWidget.restoreTabsOrAddNew() def toggleObjectListWidget(self, checked): self.listClassMethod.show() if checked else self.listClassMethod.hide() def pasteEditor(self): self.tabEditorWidget.currentWidget().newEditor.paste() def cutEditor(self): self.tabEditorWidget.currentWidget().newEditor.cut() def copyEditor(self): self.tabEditorWidget.currentWidget().newEditor.copy() def runScriptEditor(self): self.tabEditorWidget.currentWidget().newEditor.runScriptCode() def commentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True) def uncommentCode(self): self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False) def openScriptFileExtEditor(self): tabWidget = self.tabEditorWidget.currentWidget() path = tabWidget.path import subprocess try: subprocess.Popen([os.environ['EDITOR'], path]) except KeyError: QDesktopServices.openUrl(QUrl.fromLocalFile(path)) def openScriptFile(self): lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath()) openFileTr = QCoreApplication.translate("PythonConsole", "Open File") fileList, selected_filter = QFileDialog.getOpenFileNames( self, openFileTr, lastDirPath, "Script file (*.py)") if fileList: for pyFile in fileList: for i in range(self.tabEditorWidget.count()): tabWidget = self.tabEditorWidget.widget(i) if tabWidget.path == pyFile: self.tabEditorWidget.setCurrentWidget(tabWidget) break else: tabName = QFileInfo(pyFile).fileName() self.tabEditorWidget.newTabEditor(tabName, pyFile) lastDirPath = QFileInfo(pyFile).path() self.settings.setValue("pythonConsole/lastDirPath", pyFile) self.updateTabListScript(pyFile, action='append') def saveScriptFile(self): tabWidget = self.tabEditorWidget.currentWidget() try: tabWidget.save() except (IOError, OSError) as error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}').format( tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) def saveAsScriptFile(self, index=None): tabWidget = self.tabEditorWidget.currentWidget() if not index: index = self.tabEditorWidget.currentIndex() if not tabWidget.path: fileName = self.tabEditorWidget.tabText(index) + '.py' folder = self.settings.value("pythonConsole/lastDirPath", QDir.home()) pathFileName = os.path.join(folder, fileName) fileNone = True else: pathFileName = tabWidget.path fileNone = False saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As") filename, filter = QFileDialog.getSaveFileName(self, saveAsFileTr, pathFileName, "Script file (*.py)") if filename: try: tabWidget.save(filename) except (IOError, OSError) as error: msgText = QCoreApplication.translate( 'PythonConsole', 'The file <b>{0}</b> could not be saved. Error: {1}' ).format(tabWidget.path, error.strerror) self.callWidgetMessageBarEditor(msgText, 2, False) if fileNone: tabWidget.path = None else: tabWidget.path = pathFileName return if not fileNone: self.updateTabListScript(pathFileName, action='remove') def openHelp(self): QgsContextHelp.run("PythonConsole") def openSettings(self): if optionsDialog(self).exec_(): self.shell.refreshSettingsShell() self.shellOut.refreshSettingsOutput() self.tabEditorWidget.refreshSettingsEditor() def callWidgetMessageBar(self, text): self.shellOut.widgetMessageBar(iface, text) def callWidgetMessageBarEditor(self, text, level, timed): self.tabEditorWidget.widgetMessageBar(iface, text, level, timed) def updateTabListScript(self, script, action=None): if action == 'remove': self.tabListScript.remove(script) elif action == 'append': if not self.tabListScript: self.tabListScript = [] if script not in self.tabListScript: self.tabListScript.append(script) else: self.tabListScript = [] self.settings.setValue("pythonConsole/tabScripts", self.tabListScript) def saveSettingsConsole(self): self.settings.setValue("pythonConsole/splitterConsole", self.splitter.saveState()) self.settings.setValue("pythonConsole/splitterObj", self.splitterObj.saveState()) self.settings.setValue("pythonConsole/splitterEditor", self.splitterEditor.saveState()) self.shell.writeHistoryFile(True) def restoreSettingsConsole(self): storedTabScripts = self.settings.value("pythonConsole/tabScripts", []) self.tabListScript = storedTabScripts self.splitter.restoreState( self.settings.value("pythonConsole/splitterConsole", QByteArray())) self.splitterEditor.restoreState( self.settings.value("pythonConsole/splitterEditor", QByteArray())) self.splitterObj.restoreState( self.settings.value("pythonConsole/splitterObj", QByteArray()))
class PdokServicesPlugin(object): def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # docked or dialog, defaults to dialog # 2018 may: RD: deprecating Docked window, as the content is getting to big anyway # if isinstance(QSettings().value("/pdokservicesplugin/docked"), QVariant): # self.docked = QSettings().value("/pdokservicesplugin/docked", QVariant(False)) # else: # self.docked = QSettings().value("/pdokservicesplugin/docked", False) # # # Create the dialog and keep reference # if "True" == self.docked or "true" == self.docked or True is self.docked: # self.dlg = PdokServicesPluginDockWidget() # self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg) # else: # self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow()) self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow()) # initialize plugin directory self.plugin_dir = os.path.dirname(__file__) self.currentLayer = None self.SETTINGS_SECTION = '/pdokservicesplugin/' self.pointer = None self.pdokgeocoder = PDOKGeoLocator(self.iface) self.geocoderSourceModel = None def getSettingsValue(self, key, default=''): if QSettings().contains(self.SETTINGS_SECTION + key): key = self.SETTINGS_SECTION + key if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 return str(QSettings().value(key).toString()) else: return str(QSettings().value(key)) else: return default def setSettingsValue(self, key, value): key = self.SETTINGS_SECTION + key if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 QSettings().setValue(key, QVariant(value)) else: QSettings().setValue(key, value) def initGui(self): # Create action that will start plugin configuration self.runIcon = QIcon( os.path.join(self.plugin_dir, 'icon_add_service.svg')) self.run_action = QAction(self.runIcon, "PDOK Services plugin", self.iface.mainWindow()) self.run_button = QToolButton() self.run_button.setMenu(QMenu()) self.run_button.setPopupMode(QToolButton.MenuButtonPopup) self.run_button.setDefaultAction(self.run_action) self.servicesLoaded = False # connect the action to the run method self.run_action.triggered.connect(self.run) self.setupfq() # Add toolbar button and menu item #self.iface.addToolBarIcon(self.action) self.toolbar = self.iface.addToolBar("PDOK services plugin") self.toolbar.setObjectName("PDOK services plugin") #self.toolbar.addAction(self.run_action) self.toolbar.addWidget(self.run_button) #self.run_button.menu().addSection('Favorieten') self.favourite_1_action = QAction('Favoriet 1', self.iface.mainWindow()) self.favourite_1_action.setIcon(self.runIcon) self.favourite_1_action.triggered.connect( lambda: self.load_favourite(1)) self.set_favourite_action(self.favourite_1_action, 1) self.run_button.menu().addAction(self.favourite_1_action) self.favourite_2_action = QAction('Favoriet 2', self.iface.mainWindow()) self.favourite_2_action.setIcon(self.runIcon) self.favourite_2_action.triggered.connect( lambda: self.load_favourite(2)) self.set_favourite_action(self.favourite_2_action, 2) self.run_button.menu().addAction(self.favourite_2_action) # TODO :-) #self.run_button.menu().addSection('Meest Recent') #self.run_button.menu().addSeparator() self.toolbarSearch = QLineEdit() self.toolbarSearch.setMaximumWidth(200) self.toolbarSearch.setAlignment(Qt.AlignLeft) self.toolbarSearch.setPlaceholderText("PDOK Locatieserver zoek") self.toolbar.addWidget(self.toolbarSearch) self.toolbarSearch.returnPressed.connect(self.searchAddressFromToolbar) # address/point cleanup eraserIcon = QIcon( os.path.join(self.plugin_dir, 'icon_remove_cross.svg')) self.clean_action = QAction(eraserIcon, "Cleanup", self.eraseAddress()) self.toolbar.addAction(self.clean_action) self.clean_action.triggered.connect(self.eraseAddress) self.clean_action.setEnabled(False) self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.run_action) # about self.aboutAction = QAction(QIcon(":/plugins/pdokservicesplugin/icon_help.png"), \ "About", self.iface.mainWindow()) self.aboutAction.setWhatsThis("Pdok Services Plugin About") self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.aboutAction) self.aboutAction.triggered.connect(self.about) self.dlg.ui.btnLoadLayer.clicked.connect(self.loadService) self.dlg.geocoderSearch.returnPressed.connect(self.searchAddress) self.dlg.geocoderSearch.textEdited.connect(self.searchAddress) self.dlg.geocoderSearch.setPlaceholderText( "PDOK Locatieserver zoek, bv postcode of postcode huisnummer") self.dlg.geocoderResultSearch.textChanged.connect( self.filterGeocoderResult) self.dlg.geocoderResultSearch.setPlaceholderText( "een of meer zoekwoorden uit resultaat") #self.iface.mapCanvas().renderStarting.connect(self.extentsChanged) ui = self.dlg.ui cbxs = [ ui.cbx_gem, ui.cbx_wpl, ui.cbx_weg, ui.cbx_pcd, ui.cbx_adr, ui.cbx_pcl, ui.cbx_hmp ] # connect all fq checkboxes with suggest, so upon a change in fq filter we re-search for cbx in cbxs: cbx.stateChanged.connect(self.searchAddress) self.run(True) # for now hiding the pointer as soon as the extent changes #def extentsChanged(self): # self.removePointer() # 2021-02 hiding the check JSON: to much hassle def checkPdokJson(self): myversion = self.getSettingsValue('pdokversion', '1') msgtxt = '' msglvl = 0 # QgsMessageBar.INFO try: response = urllib.request.urlopen( 'http://www.qgis.nl/pdok.version') str_response = response.read().decode('utf-8') pdokversion = json.loads(str_response) if pdokversion > int(myversion): response = urllib.request.urlopen( 'http://www.qgis.nl/pdok.json') str_response = response.read().decode('utf-8') pdokjson = json.loads(str_response) with open(os.path.join(self.plugin_dir, 'pdok.json'), 'w') as outfile: json.dump(pdokjson, outfile) msgtxt = "De laatste versie is opgehaald en zal worden gebruikt " + \ str(pdokversion) + ' (was ' + myversion +')' self.servicesLoaded = False # reset reading of json self.run() self.setSettingsValue('pdokversion', pdokversion) else: msgtxt = "Geen nieuwere versie beschikbaar dan " + str( pdokversion) except Exception as e: #print e msgtxt = "Fout bij ophalen van service info. Netwerk probleem?" msglvl = 2 # QgsMessageBar.CRITICAL # msg if hasattr(self.iface, 'messageBar'): self.iface.messageBar().pushMessage("PDOK services update", msgtxt, level=msglvl, duration=10) else: # 1.8 QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin", msgtxt) def showAndRaise(self): self.dlg.show() self.dlg.raise_() # also remove the pointer self.removePointer() def about(self): infoString = "Written by Richard Duivenvoorde\nEmail - [email protected]\n" infoString += "Company - Zuidt - http://www.zuidt.nl\n" infoString += "Source: https://github.com/rduivenvoorde/pdokservicesplugin" QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin About", infoString) def unload(self): self.removePointer() # Remove the plugin menu item and icon self.iface.removePluginMenu("&Pdok Services Plugin", self.run_action) self.iface.removePluginMenu("&Pdok Services Plugin", self.aboutAction) del self.toolbarSearch del self.run_action del self.aboutAction def showService(self, selectedIndexes): if len(selectedIndexes) == 0: self.currentLayer = None self.dlg.ui.layerInfo.setHtml('') self.dlg.ui.comboSelectProj.clear() return # needed to scroll To the selected row incase of using the keyboard / arrows self.dlg.servicesView.scrollTo( self.dlg.servicesView.selectedIndexes()[0]) # itemType holds the data (== column 1) self.currentLayer = self.dlg.servicesView.selectedIndexes()[1].data( Qt.UserRole) if isinstance(self.currentLayer, QVariant): self.currentLayer = self.currentLayer.toMap() # QGIS 1.8: QVariants currentLayer = {} for key in list(self.currentLayer.keys()): val = self.currentLayer[key] currentLayer[str(key)] = str(val.toString()) self.currentLayer = currentLayer url = self.currentLayer['url'] title = self.currentLayer['title'] style = '' if 'style' in self.currentLayer: style = self.currentLayer['style'] title += f' [{style}]' servicetitle = self.currentLayer['servicetitle'] layername = self.currentLayer['layers'] abstract = self.currentLayer['abstract'] stype = self.currentLayer['type'].upper() minscale = '' if 'minscale' in self.currentLayer and self.currentLayer[ 'minscale'] != None and self.currentLayer['minscale'] != '': minscale = "min. schaal 1:" + self.currentLayer['minscale'] maxscale = '' if 'maxscale' in self.currentLayer and self.currentLayer[ 'maxscale'] != None and self.currentLayer['maxscale'] != '': maxscale = "max. schaal 1:" + self.currentLayer['maxscale'] self.dlg.ui.layerInfo.setText('') self.dlg.ui.btnLoadLayer.setEnabled(True) self.dlg.ui.layerInfo.setHtml( '<h4>%s</h4><h3>%s</h3><lu><li>%s</li><li> </li><li>%s</li><li>%s</li><li>%s</li><li>%s</li><li>%s</li><li>%s</li></lu>' % (servicetitle, title, abstract, stype, url, layername, style, minscale, maxscale)) self.dlg.ui.comboSelectProj.clear() if stype == "WMS": try: crs = self.currentLayer['crs'] except KeyError: crs = 'EPSG:28992' crs = crs.split(',') self.dlg.ui.comboSelectProj.addItems(crs) for i in range(len(crs)): if crs[i] == 'EPSG:28992': self.dlg.ui.comboSelectProj.setCurrentIndex(i) if stype == "WMTS": tilematrixsets = self.currentLayer['tilematrixsets'].split(',') self.dlg.ui.comboSelectProj.addItems(tilematrixsets) for i in range(len(tilematrixsets)): if tilematrixsets[i].startswith('EPSG:28992'): self.dlg.ui.comboSelectProj.setCurrentIndex(i) def set_favourite_action(self, action, favourite_number): if QSettings().contains( f'/pdokservicesplugin/favourite_{favourite_number}'): layer = QSettings().value( f'/pdokservicesplugin/favourite_{favourite_number}', None) if layer: action.setToolTip(layer['title'].capitalize()) title = layer['title'].capitalize() if 'style' in layer: style = layer['style'] title += f' [{style}]' if 'type' in layer: stype = layer['type'].upper() title += f' ({stype})' action.setText(title) action.setIcon(self.runIcon) def load_favourite(self, favourite_number): if QSettings().contains( f'/pdokservicesplugin/favourite_{favourite_number}'): layer = QSettings().value( f'/pdokservicesplugin/favourite_{favourite_number}', None) if layer and layer in self.pdok['services']: self.currentLayer = layer self.loadService() return QMessageBox.warning(self.iface.mainWindow(), "Geen Favoriet aanwezig (of verouderd)...", ( \ "Maak een Favoriet aan door in de dialoog met services en lagen\n via het context menu (rechter muisknop) een Favoriet te kiezen..." ), QMessageBox.Ok, QMessageBox.Ok) self.run() def loadService(self): if self.currentLayer == None: return servicetype = self.currentLayer['type'] url = self.currentLayer['url'] # some services have an url with query parameters in it, we have to urlencode those: location, query = urllib.parse.splitquery(url) url = location # RD: 20200820: lijkt of het quoten van de query problemen geeft bij WFS, is/was dit nodig??? #if query != None and query != '': # url +=('?'+urllib.parse.quote_plus(query)) title = self.currentLayer['title'] if 'style' in self.currentLayer: style = self.currentLayer['style'] title += f' [{style}]' else: style = '' # == default for this service layers = self.currentLayer['layers'] # mmm, tricky: we take the first one while we can actually want png/gif or jpeg if servicetype == "wms": imgformat = self.currentLayer['imgformats'].split(',')[0] if self.dlg.ui.comboSelectProj.currentIndex() == -1: crs = 'EPSG:28992' else: crs = self.dlg.ui.comboSelectProj.currentText() if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 uri = url self.iface.addRasterLayer( uri, # service uri title, # name for layer (as seen in QGIS) "wms", # dataprovider key [layers], # array of layername(s) for provider (id's) ["" ], # array of stylename(s) NOTE: ignoring styles here!!! imgformat, # image format searchstring crs) # crs code searchstring else: # qgis > 1.8 uri = "crs=" + crs + "&layers=" + layers + "&styles=" + style + "&format=" + imgformat + "&url=" + url self.iface.addRasterLayer(uri, title, "wms") elif servicetype == "wmts": if Qgis.QGIS_VERSION_INT < 10900: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( "Sorry, dit type layer: '" + servicetype.upper() + "' \nkan niet worden geladen in deze versie van QGIS.\nMisschien kunt u QGIS 2.0 installeren (die kan het WEL)?\nOf is de laag niet ook beschikbaar als wms of wfs?" ), QMessageBox.Ok, QMessageBox.Ok) return if self.dlg.ui.comboSelectProj.currentIndex() == -1: tilematrixset = 'EPSG:28992' else: tilematrixset = self.dlg.ui.comboSelectProj.currentText() imgformat = self.currentLayer['imgformats'].split(',')[0] # special case for luchtfoto #if layers=="luchtfoto": # # tileMatrixSet=nltilingschema&crs=EPSG:28992&layers=luchtfoto&styles=&format=image/jpeg&url=http://geodata1.nationaalgeoregister.nl/luchtfoto/wmts/1.0.0/WMTSCapabilities.xml # # {u'layers': u'luchtfoto', u'imgformats': u'image/jpeg', u'title': u'PDOK-achtergrond luchtfoto', u'url': u'http://geodata1.nationaalgeoregister.nl/luchtfoto/wms', u'abstract': u'', u'tilematrixsets': u'nltilingschema', u'type': u'wmts'} # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url #else: # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url; #uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=default&format="+imgformat+"&url="+url; if tilematrixset.startswith('EPSG:'): crs = tilematrixset i = crs.find(':', 5) if i > -1: crs = crs[:i] elif tilematrixset.startswith('OGC:1.0'): crs = 'EPSG:3857' uri = "tileMatrixSet=" + tilematrixset + "&crs=" + crs + "&layers=" + layers + "&styles=default&format=" + imgformat + "&url=" + url #print "############ PDOK URI #################" #print uri self.iface.addRasterLayer(uri, title, "wms") elif servicetype == "wfs": location, query = urllib.parse.splitquery(url) #uri = location+"?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME="+layers+"&SRSNAME=EPSG:28992" #uri = location + "?SERVICE=WFS&REQUEST=GetFeature&TYPENAME=" + layers + "&SRSNAME=EPSG:28992" # adding a bbox paramater forces QGIS to NOT cache features but retrieve new features all the time # QGIS will update the BBOX to the right value #uri += "&BBOX=-10000,310000,290000,650000" uri = " pagingEnabled='true' restrictToRequestBBOX='1' srsname='EPSG:28992' typename='" + layers + "' url='" + url + "' version='2.0.0' " self.iface.addVectorLayer(uri, title, "WFS") elif servicetype == "wcs": # cache=AlwaysCache&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs uri = '' # cache=AlwaysCache # cache=PreferNetwork # cache=AlwaysNetwork # cache=AlwaysNetwork&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=image/tiff&version=1.1.1&identifier="+layers+"&url="+url # working for ahn1 ahn2 and ahn3: GEOTIFF_FLOAT32 format = 'GEOTIFF_FLOAT32' # working for ahn25m is only image/tiff if layers == 'ahn25m': format = 'image/tiff' # we handcrated some wcs layers with 2 different image formats: tiff (RGB) and tiff (float32): if 'imgformats' in self.currentLayer: format = self.currentLayer['imgformats'].split(',')[0] uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=" + format + "&identifier=" + layers + "&url=" + url #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format="+format+"&version=1.1.2&identifier=" + layers + "&url=" + url #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=image/tiff&version=1.1.2&identifier=" + layers + "&url=" + url self.iface.addRasterLayer(uri, title, "wcs") else: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( "Sorry, dit type layer: '" + servicetype.upper() + "' \nkan niet worden geladen door de plugin of door QGIS.\nIs het niet beschikbaar als wms, wmts of wfs?" ), QMessageBox.Ok, QMessageBox.Ok) return def filterGeocoderResult(self, string): #print "filtering geocoder results: %s" % string self.dlg.geocoderResultView.selectRow(0) self.geocoderProxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.geocoderProxyModel.setFilterFixedString(string) def searchAddressFromToolbar(self): self.removePointer() self.geocoderSourceModel.clear() self.geocode() def searchAddress(self): self.removePointer() #print "search geocoder for: %s" % self.dlg.geocoderSearch.text() self.geocoderSourceModel.clear() #self.geocode(self.dlg.geocoderSearch.text()) self.suggest() def eraseAddress(self): """ clean the input and remove the pointer """ self.removePointer() if self.geocoderSourceModel is not None: self.geocoderSourceModel.clear() if self.dlg.geocoderSearch is not None: self.dlg.geocoderSearch.clear() if self.toolbarSearch is not None: self.toolbarSearch.clear() def filterLayers(self, string): # remove selection if one row is selected self.dlg.servicesView.selectRow(0) #self.currentLayer = None self.proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.proxyModel.setFilterFixedString(string) #def addSourceRow(self, service, layer): def addSourceRow(self, serviceLayer): # you can attache different "data's" to to an QStandarditem # default one is the visible one: itemType = QStandardItem("%s" % (serviceLayer["type"].upper())) # userrole is a free form one: # only attach the data to the first item # service layer = a dict/object with all props of the layer itemType.setData(serviceLayer, Qt.UserRole) itemType.setToolTip( "%s - %s" % (serviceLayer["type"].upper(), serviceLayer["title"])) # only wms services have styles (sometimes) layername = serviceLayer["title"] if 'style' in serviceLayer: itemLayername = QStandardItem( "%s [%s]" % (serviceLayer["title"], serviceLayer["style"])) layername = "%s [%s]" % (serviceLayer["title"], serviceLayer["style"]) else: itemLayername = QStandardItem("%s" % (serviceLayer["title"])) itemLayername.setToolTip( "%s - %s" % (serviceLayer["type"].upper(), serviceLayer["servicetitle"])) # itemFilter is the item used to search filter in. That is why layername is a combi of layername + filter here itemFilter = QStandardItem( "%s %s %s %s" % (serviceLayer["type"], layername, serviceLayer["servicetitle"], serviceLayer["abstract"])) itemServicetitle = QStandardItem("%s" % (serviceLayer["servicetitle"])) itemServicetitle.setToolTip( "%s - %s" % (serviceLayer["type"].upper(), serviceLayer["title"])) self.sourceModel.appendRow( [itemLayername, itemType, itemServicetitle, itemFilter]) # run method that performs all the real work def run(self, hiddenDialog=False): # enable possible remote pycharm debugging #import pydevd #pydevd.settrace('localhost', port=5678, stdoutToServer=True, stderrToServer=True) # last viewed/selected tab if QSettings().contains("/pdokservicesplugin/currenttab"): if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 self.dlg.tabs.widget(QSettings().value( "/pdokservicesplugin/currenttab").toInt()[0]) else: self.dlg.tabs.widget( int(QSettings().value("/pdokservicesplugin/currenttab"))) if self.servicesLoaded == False: pdokjson = os.path.join(self.plugin_dir, "pdok.json") with open(pdokjson, 'r', encoding='utf-8') as f: self.pdok = json.load(f) print(f'self.pdok type = {type(self.pdok)}') self.proxyModel = QSortFilterProxyModel() self.sourceModel = QStandardItemModel() self.proxyModel.setSourceModel(self.sourceModel) # filter == search on itemFilter column: self.proxyModel.setFilterKeyColumn(3) self.dlg.servicesView.setModel(self.proxyModel) self.dlg.servicesView.setEditTriggers( QAbstractItemView.NoEditTriggers) self.geocoderProxyModel = QSortFilterProxyModel() self.geocoderSourceModel = QStandardItemModel() self.geocoderProxyModel.setSourceModel(self.geocoderSourceModel) self.geocoderProxyModel.setFilterKeyColumn(0) self.dlg.geocoderResultView.setModel(self.geocoderProxyModel) self.dlg.geocoderResultView.setEditTriggers( QAbstractItemView.NoEditTriggers) #{"services":[ # {"naam":"WMS NHI","url":"http://geodata.nationaalgeoregister.nl/nhi/ows","layers":["dmlinks","dmnodes"],"type":"wms"}, # {"naam":"WMS NHI","url":"http://geodata.nationaalgeoregister.nl/nhi/ows","layers":["dmlinks","dmnodes"],"type":"wms"} # ]} # for service in self.pdok["services"]: # service[layer] was an array if isinstance(service["layers"], str): self.addSourceRow(service) self.dlg.layerSearch.textChanged.connect(self.filterLayers) self.dlg.layerSearch.setPlaceholderText( "woord uit laagnaam, type of service ") self.dlg.servicesView.selectionModel().selectionChanged.connect( self.showService) self.dlg.servicesView.doubleClicked.connect(self.loadService) self.dlg.servicesView.setContextMenuPolicy(Qt.CustomContextMenu) self.dlg.servicesView.customContextMenuRequested.connect( self.make_favourite) # actually I want to load a service when doubleclicked on header # but as I cannot get this to work, let's disable clicking it then self.dlg.servicesView.verticalHeader().setSectionsClickable(False) self.dlg.servicesView.horizontalHeader().setSectionsClickable( False) #self.dlg.geocoderResultView.doubleClicked.connect(self.zoomToAddress) self.dlg.geocoderResultView.selectionModel( ).selectionChanged.connect(self.zoomToAddress) # hide itemFilter column: self.dlg.servicesView.hideColumn(3) self.servicesLoaded = True self.sourceModel.setHeaderData(2, Qt.Horizontal, "Service") self.sourceModel.setHeaderData(1, Qt.Horizontal, "Type") self.sourceModel.setHeaderData(0, Qt.Horizontal, "Laagnaam [style]") self.sourceModel.horizontalHeaderItem(2).setTextAlignment(Qt.AlignLeft) self.sourceModel.horizontalHeaderItem(1).setTextAlignment(Qt.AlignLeft) self.sourceModel.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) #self.dlg.servicesView.verticalHeader().hide() #self.dlg.servicesView.resizeColumnsToContents() self.dlg.servicesView.setColumnWidth( 0, 300) # set name to 300px (there are some huge layernames) self.dlg.servicesView.horizontalHeader().setStretchLastSection(True) # show the dialog ? if not hiddenDialog: self.dlg.show() # Run the dialog event loop #result = self.dlg.exec_() if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 QSettings().setValue("/pdokservicesplugin/currenttab", QVariant(self.dlg.tabs.currentIndex())) else: QSettings().setValue("/pdokservicesplugin/currenttab", self.dlg.tabs.currentIndex()) self.removePointer() def make_favourite(self, position): menu = QMenu() create_fav1_action = menu.addAction("Maak Deze Laag Favoriet 1") create_fav2_action = menu.addAction("Maak Deze Laag Favoriet 2") action = menu.exec_(self.dlg.servicesView.mapToGlobal(position)) if action == create_fav1_action: QSettings().setValue("/pdokservicesplugin/favourite_1", self.currentLayer) self.set_favourite_action(self.favourite_1_action, 1) elif action == create_fav2_action: QSettings().setValue("/pdokservicesplugin/favourite_2", self.currentLayer) self.set_favourite_action(self.favourite_2_action, 2) def setupfq(self): """ Setup the fq checkboxes in the gui, by looking into the settings for the 'pdokservicesplugin/checkedfqs' key, which contains a list of type strings like ['weg','adres'] """ checked_fqs = self.getSettingsValue('checkedfqs', []) #self.info('setup fq: {}'.format(checked_fqs)) if len(checked_fqs ) > 0: # else there is not saved state... take gui defaults self.dlg.ui.cbx_gem.setChecked('gemeente' in checked_fqs) self.dlg.ui.cbx_wpl.setChecked('woonplaats' in checked_fqs) self.dlg.ui.cbx_weg.setChecked('weg' in checked_fqs) self.dlg.ui.cbx_pcd.setChecked('postcode' in checked_fqs) self.dlg.ui.cbx_adr.setChecked('adres' in checked_fqs) self.dlg.ui.cbx_pcl.setChecked('perceel' in checked_fqs) self.dlg.ui.cbx_hmp.setChecked('hectometerpaal' in checked_fqs) def createfq(self): """ This creates a fq-string (Filter Query, see https://github.com/PDOK/locatieserver/wiki/Zoekvoorbeelden-Locatieserver) Based on the checkboxes in the dialog. Defaults to '' Example: 'fq=+type:adres+type:gemeente' (only gemeente AND addresses) :return: """ fqlist = [] if self.dlg.ui.cbx_gem.isChecked(): fqlist.append('gemeente') if self.dlg.ui.cbx_wpl.isChecked(): fqlist.append('woonplaats') if self.dlg.ui.cbx_weg.isChecked(): fqlist.append('weg') if self.dlg.ui.cbx_pcd.isChecked(): fqlist.append('postcode') if self.dlg.ui.cbx_adr.isChecked(): fqlist.append('adres') if self.dlg.ui.cbx_pcl.isChecked(): fqlist.append('perceel') if self.dlg.ui.cbx_hmp.isChecked(): fqlist.append('hectometerpaal') self.setSettingsValue('checkedfqs', fqlist) #self.info(self.getSettingsValue('checkedfqs', ['leeg?'])) fq = '' if len(fqlist) > 0: fq = '&fq=+type:' + '+type:'.join(fqlist) return fq def suggest(self): self.dlg.ui.lookupinfo.setHtml('') search_text = self.dlg.geocoderSearch.text() if len(search_text) <= 1: # QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ # "meer input aub: {}".format(search_text) # ), QMessageBox.Ok, QMessageBox.Ok) return # QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ # "zoeken: {}".format(search_text) # ), QMessageBox.Ok, QMessageBox.Ok) results = self.pdokgeocoder.suggest(search_text, self.createfq()) if len(results) == 0: # ignore, as we are suggesting, maybe more characters will reveal something... return for result in results: #print address adrestekst = QStandardItem("%s" % (result["adrestekst"])) adrestekst.setData(result, Qt.UserRole) type = QStandardItem("%s" % (result["type"])) id = QStandardItem("%s" % (result["id"])) score = QStandardItem("%s" % (result["score"])) adrestekst.setData(result, Qt.UserRole) self.geocoderSourceModel.appendRow([adrestekst, type]) self.geocoderSourceModel.setHeaderData(0, Qt.Horizontal, "Resultaat") self.geocoderSourceModel.setHeaderData(1, Qt.Horizontal, "Type") self.geocoderSourceModel.horizontalHeaderItem(0).setTextAlignment( Qt.AlignLeft) self.dlg.geocoderResultView.resizeColumnsToContents() self.dlg.geocoderResultView.horizontalHeader().setStretchLastSection( True) def geocode(self): self.dlg.geocoderSearch.setText(self.toolbarSearch.text()) self.suggest() if self.dlg.geocoderResultView.model().rowCount() > 0: self.dlg.geocoderResultView.selectRow(0) self.zoomToAddress() else: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ "Niets gevonden.\nProbeer een andere spelling, of alleen postcode/huisnummer?\n\nSelecteer meer (Locatieserver) 'typen' in de PdokServicesPlugin dialoog.\n\nOf gebruik de 'PDOK geocoder'-tab in de PdokServicesPlugin dialoog." ), QMessageBox.Ok, QMessageBox.Ok) # def geocode(self): # self.dlg.ui.lookupinfo.setHtml('') # search_text = self.toolbarSearch.text() # addresses = self.pdokgeocoder.search(search_text) # if len(addresses) == 0: # QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ # "Niets gevonden. Probeer een andere spelling of alleen postcode/huisnummer." # ), QMessageBox.Ok, QMessageBox.Ok) # return # for address in addresses: # #print address # adrestekst = QStandardItem("%s" % (address["adrestekst"])) # adrestekst.setData(address, Qt.UserRole) # straat = QStandardItem("%s" % (address["straat"])) # nummer = QStandardItem("%s" % (address["nummer"])) # postcode = QStandardItem("%s" % (address["postcode"])) # plaats = QStandardItem("%s" % (address["plaats"])) # gemeente = QStandardItem("%s" % (address["gemeente"])) # provincie = QStandardItem("%s" % (address["provincie"])) # self.geocoderSourceModel.appendRow([adrestekst, straat, nummer, postcode, plaats, gemeente, provincie]) # # self.dlg.geocoderResultView.selectRow(0) # self.zoomToAddress() # # self.geocoderSourceModel.setHeaderData(0, Qt.Horizontal, "Resultaat") # self.geocoderSourceModel.setHeaderData(1, Qt.Horizontal, "Straat") # self.geocoderSourceModel.setHeaderData(2, Qt.Horizontal, "Nr") # self.geocoderSourceModel.setHeaderData(3, Qt.Horizontal, "Postcode") # self.geocoderSourceModel.setHeaderData(4, Qt.Horizontal, "Plaats") # self.geocoderSourceModel.setHeaderData(5, Qt.Horizontal, "Gemeente") # self.geocoderSourceModel.setHeaderData(6, Qt.Horizontal, "Provincie") # # self.geocoderSourceModel.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(1).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(2).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(3).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(4).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(5).setTextAlignment(Qt.AlignLeft) # self.geocoderSourceModel.horizontalHeaderItem(6).setTextAlignment(Qt.AlignLeft) # # self.dlg.geocoderResultView.resizeColumnsToContents() # self.dlg.geocoderResultView.horizontalHeader().setStretchLastSection(True) def zoomToAddress(self): # get x,y from data of record self.removePointer() data = self.dlg.geocoderResultView.selectedIndexes()[0].data( Qt.UserRole) if 'centroide_rd' in data: # free OR lookup service geom = QgsGeometry.fromWkt(data['centroide_rd']) adrestekst = data['adrestekst'] else: # no centroid yet, probably only object id, retrieve it via lookup service id = data['id'] data = self.pdokgeocoder.lookup(id) geom = QgsGeometry.fromWkt(data['centroide_rd']) adrestekst = data['adrestekst'] lookup_data = data['data'] lis = '' for key in lookup_data.keys(): lis = lis + '<li>{}: {}</li>'.format(key, lookup_data[key]) self.dlg.ui.lookupinfo.setHtml('<h4>{}</h4><lu>{}</lu>'.format( adrestekst, lis)) # just always transform from 28992 to mapcanvas crs crs = self.iface.mapCanvas().mapSettings().destinationCrs() crs28992 = QgsCoordinateReferenceSystem() crs28992.createFromId(28992) crsTransform = QgsCoordinateTransform(crs28992, crs, QgsProject.instance()) z = 1587 if adrestekst.lower().startswith('adres'): z = 794 elif adrestekst.lower().startswith('perceel'): z = 794 elif adrestekst.lower().startswith('hectometer'): z = 1587 elif adrestekst.lower().startswith('straat'): z = 3175 elif adrestekst.lower().startswith('postcode'): z = 6350 elif adrestekst.lower().startswith('woonplaats'): z = 25398 elif adrestekst.lower().startswith('gemeente'): z = 50797 elif adrestekst.lower().startswith('provincie'): z = 812750 geom.transform(crsTransform) center = geom.asPoint() self.setPointer(center) # zoom to with center is actually setting a point rectangle and then zoom rect = QgsRectangle(center, center) self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().zoomScale(z) self.iface.mapCanvas().refresh() def setPointer(self, point): self.removePointer() self.pointer = QgsVertexMarker(self.iface.mapCanvas()) self.pointer.setColor(QColor(255, 255, 0)) self.pointer.setIconSize(10) self.pointer.setPenWidth(5) self.pointer.setCenter(point) self.clean_action.setEnabled(True) def removePointer(self): if self.pointer is not None and self.pointer.scene() is not None: self.iface.mapCanvas().scene().removeItem(self.pointer) self.pointer = None self.clean_action.setEnabled(False) def info(self, msg=""): QgsMessageLog.logMessage('{}'.format(msg), 'PDOK-services Plugin', Qgis.Info)
class PdokServicesPlugin(object): def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface # docked or dialog, defaults to dialog if isinstance(QSettings().value("/pdokservicesplugin/docked"), QVariant): self.docked = QSettings().value("/pdokservicesplugin/docked", QVariant(False)) else: self.docked = QSettings().value("/pdokservicesplugin/docked", False) # Create the dialog and keep reference if "True" == self.docked or "true" == self.docked or True is self.docked: self.dlg = PdokServicesPluginDockWidget() self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg) else: self.dlg = PdokServicesPluginDialog(parent=self.iface.mainWindow()) # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/pdokservicesplugin" # initialize locale localePath = "" if isinstance(QSettings().value("locale/userLocale"), QVariant): locale = QSettings().value("locale/userLocale").toString()[0:2] else: locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/pdokservicesplugin_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.currentLayer = None self.SETTINGS_SECTION = '/pdokservicesplugin/' self.pointer = None self.pdokgeocoder = PDOKGeoLocator(self.iface) self.geocoderSourceModel = None def getSettingsValue(self, key, default=''): if QSettings().contains(self.SETTINGS_SECTION + key): key = self.SETTINGS_SECTION + key if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 return str(QSettings().value(key).toString()) else: return str(QSettings().value(key)) else: return default def setSettingsValue(self, key, value): key = self.SETTINGS_SECTION + key if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 QSettings().setValue(key, QVariant(value)) else: QSettings().setValue(key, value) def initGui(self): # Create action that will start plugin configuration self.run_action = QAction(QIcon(":/plugins/pdokservicesplugin/icon.png"), \ u"Pdok Services Plugin", self.iface.mainWindow()) self.servicesLoaded = False # connect the action to the run method if "True" == self.docked or "true" == self.docked or True == self.docked: self.run_action.triggered.connect(self.showAndRaise) self.dlg.radioDocked.setChecked(True) # docked the dialog is immidiately visible, so should run NOW else: self.run_action.triggered.connect(self.run) self.dlg.radioDocked.setChecked(False) # Add toolbar button and menu item #self.iface.addToolBarIcon(self.action) self.toolbar = self.iface.addToolBar("PDOK services plugin") self.toolbar.setObjectName("PDOK services plugin") self.toolbar.addAction(self.run_action) self.toolbarSearch = QLineEdit() self.toolbarSearch.setMaximumWidth(200) self.toolbarSearch.setAlignment(Qt.AlignLeft) self.toolbarSearch.setPlaceholderText("PDOK Geocoder zoek") self.toolbar.addWidget(self.toolbarSearch) self.toolbarSearch.returnPressed.connect(self.searchAddressFromToolbar) # address/point cleanup self.clean_action = QAction(QIcon(":/plugins/pdokservicesplugin/eraser.png"), \ u"Cleanup", self.eraseAddress()) self.toolbar.addAction(self.clean_action) self.clean_action.triggered.connect(self.eraseAddress) self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.run_action) # about self.aboutAction = QAction(QIcon(":/plugins/pdokservicesplugin/help.png"), \ "About", self.iface.mainWindow()) self.aboutAction.setWhatsThis("Pdok Services Plugin About") self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.aboutAction) self.aboutAction.triggered.connect(self.about) self.dlg.ui.btnLoadLayer.clicked.connect(self.loadService) self.dlg.geocoderSearchBtn.clicked.connect(self.searchAddress) self.dlg.geocoderSearch.returnPressed.connect(self.searchAddress) self.dlg.geocoderSearch.textEdited.connect(self.searchAddress) self.dlg.geocoderSearch.setPlaceholderText("PDOK Geocoder zoek, bv postcode of postcode huisnummer") self.dlg.geocoderResultSearch.textChanged.connect(self.filterGeocoderResult) self.dlg.geocoderResultSearch.setPlaceholderText("een of meer zoekwoorden uit resultaat") self.dlg.radioDocked.toggled.connect(self.set_docked) self.dlg.btnCheckPdokJson.clicked.connect(self.checkPdokJson) #self.iface.mapCanvas().renderStarting.connect(self.extentsChanged) self.run(True) # for now hiding the pointer as soon as the extent changes #def extentsChanged(self): # self.removePointer() def checkPdokJson(self): myversion = self.getSettingsValue('pdokversion', '1') msgtxt = '' msglvl = 0 # QgsMessageBar.INFO try: response = urllib.request.urlopen('http://www.qgis.nl/pdok.version') str_response = response.read().decode('utf-8') pdokversion = json.loads(str_response) if pdokversion > int(myversion): response = urllib.request.urlopen('http://www.qgis.nl/pdok.json') str_response = response.read().decode('utf-8') pdokjson = json.loads(str_response) with open(self.plugin_dir +'/pdok.json', 'w') as outfile: json.dump(pdokjson, outfile) msgtxt = "De laatste versie is opgehaald en zal worden gebruikt " + \ str(pdokversion) + ' (was ' + myversion +')' self.servicesLoaded = False # reset reading of json self.run() self.setSettingsValue('pdokversion', pdokversion) else: msgtxt = "Geen nieuwere versie beschikbaar dan " + str(pdokversion) except Exception as e: #print e msgtxt = "Fout bij ophalen van service info. Netwerk probleem?" msglvl = 2 # QgsMessageBar.CRITICAL # msg if hasattr(self.iface, 'messageBar'): self.iface.messageBar().pushMessage("PDOK services update", msgtxt, level=msglvl, duration=10) else: # 1.8 QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin", msgtxt) def set_docked(self, foo): self.setSettingsValue('docked', self.dlg.radioDocked.isChecked()) #if Qgis.QGIS_VERSION_INT < 10900: # # qgis <= 1.8 # QSettings().setValue("/pdokservicesplugin/docked", QVariant(self.dlg.radioDocked.isChecked())) #else: # QSettings().setValue("/pdokservicesplugin/docked", self.dlg.radioDocked.isChecked()) def showAndRaise(self): self.dlg.show() self.dlg.raise_() # also remove the pointer self.removePointer() def about(self): infoString = "Written by Richard Duivenvoorde\nEmail - [email protected]\n" infoString += "Company - Zuidt - http://www.zuidt.nl\n" infoString += "Source: https://github.com/rduivenvoorde/pdokservicesplugin" QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin About", infoString) def unload(self): self.removePointer() # Remove the plugin menu item and icon self.iface.removePluginMenu(u"&Pdok Services Plugin",self.run_action) del self.toolbarSearch def showService(self, selectedIndexes): if len(selectedIndexes)==0: self.currentLayer = None self.dlg.ui.layerInfo.setHtml('') self.dlg.ui.comboSelectProj.clear() return # needed to scroll To the selected row incase of using the keyboard / arrows self.dlg.servicesView.scrollTo(self.dlg.servicesView.selectedIndexes()[0]) # itemType holds the data (== column 1) self.currentLayer = self.dlg.servicesView.selectedIndexes()[1].data(Qt.UserRole) if isinstance(self.currentLayer, QVariant): self.currentLayer = self.currentLayer.toMap() # QGIS 1.8: QVariants currentLayer = {} for key in list(self.currentLayer.keys()): val = self.currentLayer[key] currentLayer[str(key)]=str(val.toString()) self.currentLayer = currentLayer url = self.currentLayer['url'] title = self.currentLayer['title'] style = '' if 'style' in self.currentLayer: style = self.currentLayer['style'] title = title + ' [' + style + ']' servicetitle = self.currentLayer['servicetitle'] layername = self.currentLayer['layers'] abstract = self.currentLayer['abstract'] stype = self.currentLayer['type'].upper() minscale ='' if 'minscale' in self.currentLayer and self.currentLayer['minscale'] != None and self.currentLayer['minscale'] != '': minscale = "min. schaal 1:"+self.currentLayer['minscale'] maxscale = '' if 'maxscale' in self.currentLayer and self.currentLayer['maxscale'] != None and self.currentLayer['maxscale'] != '': maxscale = "max. schaal 1:"+self.currentLayer['maxscale'] self.dlg.ui.layerInfo.setText('') self.dlg.ui.btnLoadLayer.setEnabled(True) self.dlg.ui.layerInfo.setHtml('<h4>%s</h4><h3>%s</h3><lu><li>%s</li><li> </li><li>%s</li><li>%s</li><li>%s</li><li>%s</li><li>%s</li><li>%s</li></lu>' % (servicetitle, title, abstract, stype, url, layername, style, minscale, maxscale)) self.dlg.ui.comboSelectProj.clear() if stype=="WMS": try: crs = self.currentLayer['crs'] except KeyError: crs = 'EPSG:28992' crs = crs.split(',') self.dlg.ui.comboSelectProj.addItems(crs) for i in range(len(crs)): if crs[i] == 'EPSG:28992': self.dlg.ui.comboSelectProj.setCurrentIndex(i) if stype=="WMTS": tilematrixsets = self.currentLayer['tilematrixsets'].split(',') self.dlg.ui.comboSelectProj.addItems(tilematrixsets) for i in range(len(tilematrixsets)): if tilematrixsets[i].startswith('EPSG:28992'): self.dlg.ui.comboSelectProj.setCurrentIndex(i) def loadService(self): if self.currentLayer == None: return servicetype = self.currentLayer['type'] url = self.currentLayer['url'] # some services have an url with query parameters in it, we have to urlencode those: location,query = urllib.parse.splitquery(url) url = location if query != None and query != '': url +=('?'+urllib.parse.quote_plus(query)) title = self.currentLayer['title'] if 'style' in self.currentLayer: style = self.currentLayer['style'] title = title + ' [' + style + ']' else: style = '' # == default for this service layers = self.currentLayer['layers'] # mmm, tricky: we take the first one while we can actually want png/gif or jpeg if servicetype=="wms": imgformat = self.currentLayer['imgformats'].split(',')[0] if self.dlg.ui.comboSelectProj.currentIndex() == -1: crs = 'EPSG:28992' else: crs = self.dlg.ui.comboSelectProj.currentText() if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 uri = url self.iface.addRasterLayer( uri, # service uri title, # name for layer (as seen in QGIS) "wms", # dataprovider key [layers], # array of layername(s) for provider (id's) [""], # array of stylename(s) NOTE: ignoring styles here!!! imgformat, # image format searchstring crs) # crs code searchstring else: # qgis > 1.8 uri = "crs="+crs+"&layers="+layers+"&styles="+style+"&format="+imgformat+"&url="+url; self.iface.addRasterLayer(uri, title, "wms") elif servicetype=="wmts": if Qgis.QGIS_VERSION_INT < 10900: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ("Sorry, dit type layer: '"+servicetype.upper()+"' \nkan niet worden geladen in deze versie van QGIS.\nMisschien kunt u QGIS 2.0 installeren (die kan het WEL)?\nOf is de laag niet ook beschikbaar als wms of wfs?"), QMessageBox.Ok, QMessageBox.Ok) return if self.dlg.ui.comboSelectProj.currentIndex() == -1: tilematrixset = 'EPSG:28992' else: tilematrixset = self.dlg.ui.comboSelectProj.currentText() imgformat = self.currentLayer['imgformats'].split(',')[0] # special case for luchtfoto #if layers=="luchtfoto": # # tileMatrixSet=nltilingschema&crs=EPSG:28992&layers=luchtfoto&styles=&format=image/jpeg&url=http://geodata1.nationaalgeoregister.nl/luchtfoto/wmts/1.0.0/WMTSCapabilities.xml # # {u'layers': u'luchtfoto', u'imgformats': u'image/jpeg', u'title': u'PDOK-achtergrond luchtfoto', u'url': u'http://geodata1.nationaalgeoregister.nl/luchtfoto/wms', u'abstract': u'', u'tilematrixsets': u'nltilingschema', u'type': u'wmts'} # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url #else: # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url; #uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=default&format="+imgformat+"&url="+url; if tilematrixset.startswith('EPSG:'): crs=tilematrixset i = crs.find(':', 5) if i > -1: crs=crs[:i] elif tilematrixset.startswith('OGC:1.0'): crs='EPSG:3857' uri = "tileMatrixSet="+tilematrixset+"&crs="+crs+"&layers="+layers+"&styles=default&format="+imgformat+"&url="+url; #print "############ PDOK URI #################" #print uri self.iface.addRasterLayer(uri, title, "wms") elif servicetype=="wfs": location,query = urllib.parse.splitquery(url) uri = location+"?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME="+layers+"&SRSNAME=EPSG:28992" # adding a bbox paramater forces QGIS to NOT cache features but retrieve new features all the time # QGIS will update the BBOX to the right value uri += "&BBOX=-10000,310000,290000,650000" self.iface.addVectorLayer(uri, title, "WFS") elif servicetype=="wcs": # cache=AlwaysCache&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs uri = '' # cache=AlwaysCache # cache=PreferNetwork # cache=AlwaysNetwork # cache=AlwaysNetwork&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=GeoTIFF&identifier="+layers+"&url="+url self.iface.addRasterLayer(uri, title, "wcs") else: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ("Sorry, dit type layer: '"+servicetype.upper()+"' \nkan niet worden geladen door de plugin of door QGIS.\nIs het niet beschikbaar als wms, wmts of wfs?"), QMessageBox.Ok, QMessageBox.Ok) return def filterGeocoderResult(self, string): #print "filtering geocoder results: %s" % string self.dlg.geocoderResultView.selectRow(0) self.geocoderProxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.geocoderProxyModel.setFilterFixedString(string) def searchAddressFromToolbar(self): self.removePointer() self.geocoderSourceModel.clear() self.geocode(self.toolbarSearch.text()) def searchAddress(self): self.removePointer() #print "search geocoder for: %s" % self.dlg.geocoderSearch.text() self.geocoderSourceModel.clear() #self.geocode(self.dlg.geocoderSearch.text()) self.suggest(self.dlg.geocoderSearch.text()) def eraseAddress(self): """ clean the input and remove the pointer """ self.removePointer() if self.geocoderSourceModel is not None: self.geocoderSourceModel.clear() if self.dlg.geocoderSearch is not None: self.dlg.geocoderSearch.clear() if self.toolbarSearch is not None: self.toolbarSearch.clear() def filterLayers(self, string): # remove selection if one row is selected self.dlg.servicesView.selectRow(0) #self.currentLayer = None self.proxyModel.setFilterCaseSensitivity(Qt.CaseInsensitive) self.proxyModel.setFilterFixedString(string) #def addSourceRow(self, service, layer): def addSourceRow(self, serviceLayer): # you can attache different "data's" to to an QStandarditem # default one is the visible one: itemType = QStandardItem("%s" % (serviceLayer["type"].upper()) ) # userrole is a free form one: # only attach the data to the first item # service layer = a dict/object with all props of the layer itemType.setData( serviceLayer, Qt.UserRole ) itemType.setToolTip("%s - %s" % (serviceLayer["type"].upper() ,serviceLayer["title"] )) # only wms services have styles (sometimes) layername = serviceLayer["title"] if 'style' in serviceLayer: itemLayername = QStandardItem("%s [%s]" % (serviceLayer["title"], serviceLayer["style"]) ) layername = "%s [%s]" % (serviceLayer["title"], serviceLayer["style"]) else: itemLayername = QStandardItem("%s" % (serviceLayer["title"])) itemLayername.setToolTip("%s - %s" % (serviceLayer["type"].upper() ,serviceLayer["servicetitle"] )) # itemFilter is the item used to search filter in. That is why layername is a combi of layername + filter here itemFilter = QStandardItem("%s %s %s %s" % (serviceLayer["type"], layername, serviceLayer["servicetitle"], serviceLayer["abstract"]) ) itemServicetitle = QStandardItem("%s" % (serviceLayer["servicetitle"])) itemServicetitle.setToolTip("%s - %s" % (serviceLayer["type"].upper() ,serviceLayer["title"] )) self.sourceModel.appendRow( [ itemLayername, itemType, itemServicetitle, itemFilter ] ) # run method that performs all the real work def run(self, hiddenDialog=False): # last viewed/selected tab if QSettings().contains("/pdokservicesplugin/currenttab"): if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 self.dlg.tabs.widget(QSettings().value("/pdokservicesplugin/currenttab").toInt()[0]) else: self.dlg.tabs.widget(int(QSettings().value("/pdokservicesplugin/currenttab"))) if self.servicesLoaded == False: pdokjson = os.path.join(os.path.dirname(__file__), ".","pdok.json") f = open(pdokjson, 'r', encoding='utf-8') self.pdok = json.load(f) f.close() self.proxyModel = QSortFilterProxyModel() self.sourceModel = QStandardItemModel() self.proxyModel.setSourceModel(self.sourceModel) # filter == search on itemFilter column: self.proxyModel.setFilterKeyColumn(3) self.dlg.servicesView.setModel(self.proxyModel) self.dlg.servicesView.setEditTriggers(QAbstractItemView.NoEditTriggers) self.geocoderProxyModel = QSortFilterProxyModel() self.geocoderSourceModel = QStandardItemModel() self.geocoderProxyModel.setSourceModel(self.geocoderSourceModel) self.geocoderProxyModel.setFilterKeyColumn(0) self.dlg.geocoderResultView.setModel(self.geocoderProxyModel) self.dlg.geocoderResultView.setEditTriggers(QAbstractItemView.NoEditTriggers) #{"services":[ # {"naam":"WMS NHI","url":"http://geodata.nationaalgeoregister.nl/nhi/ows","layers":["dmlinks","dmnodes"],"type":"wms"}, # {"naam":"WMS NHI","url":"http://geodata.nationaalgeoregister.nl/nhi/ows","layers":["dmlinks","dmnodes"],"type":"wms"} # ]} # for service in self.pdok["services"]: # service[layer] was an array if isinstance(service["layers"], str) or isinstance(service["layers"], str): self.addSourceRow(service) self.dlg.layerSearch.textChanged.connect(self.filterLayers) self.dlg.layerSearch.setPlaceholderText("woord uit laagnaam, type of service ") self.dlg.servicesView.selectionModel().selectionChanged.connect(self.showService) self.dlg.servicesView.doubleClicked.connect(self.loadService) # actually I want to load a service when doubleclicked on header # but as I cannot get this to work, let's disable clicking it then self.dlg.servicesView.verticalHeader().setSectionsClickable(False) self.dlg.servicesView.horizontalHeader().setSectionsClickable(False) #self.dlg.geocoderResultView.doubleClicked.connect(self.zoomToAddress) self.dlg.geocoderResultView.selectionModel().selectionChanged.connect(self.zoomToAddress) # hide itemFilter column: self.dlg.servicesView.hideColumn(3) self.servicesLoaded = True; self.sourceModel.setHeaderData(2, Qt.Horizontal, "Service") self.sourceModel.setHeaderData(1, Qt.Horizontal, "Type") self.sourceModel.setHeaderData(0, Qt.Horizontal, "Laagnaam [style]") self.sourceModel.horizontalHeaderItem(2).setTextAlignment(Qt.AlignLeft) self.sourceModel.horizontalHeaderItem(1).setTextAlignment(Qt.AlignLeft) self.sourceModel.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) #self.dlg.servicesView.verticalHeader().hide() #self.dlg.servicesView.resizeColumnsToContents() self.dlg.servicesView.setColumnWidth(0, 300) # set name to 300px (there are some huge layernames) self.dlg.servicesView.horizontalHeader().setStretchLastSection(True) # show the dialog ? if not hiddenDialog: self.dlg.show() # Run the dialog event loop #result = self.dlg.exec_() if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 QSettings().setValue("/pdokservicesplugin/currenttab", QVariant(self.dlg.tabs.currentIndex())) else: QSettings().setValue("/pdokservicesplugin/currenttab", self.dlg.tabs.currentIndex()) self.removePointer() def suggest(self, search_text): self.dlg.ui.lookupinfo.setHtml('') if len(search_text) <= 1: # QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ # "meer input aub: {}".format(search_text) # ), QMessageBox.Ok, QMessageBox.Ok) return # QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ # "zoeken: {}".format(search_text) # ), QMessageBox.Ok, QMessageBox.Ok) results = self.pdokgeocoder.suggest(search_text) if len(results) == 0: # ignore, as we are suggesting, maybe more characters will reveal something... return for result in results: #print address adrestekst = QStandardItem("%s" % (result["adrestekst"])) adrestekst.setData(result, Qt.UserRole) type = QStandardItem("%s" % (result["type"])) id = QStandardItem("%s" % (result["id"])) score = QStandardItem("%s" % (result["score"])) adrestekst.setData(result, Qt.UserRole) self.geocoderSourceModel.appendRow([adrestekst, type # , id, score ]) # self.dlg.geocoderResultView.selectRow(0) # self.zoomToAddress() self.geocoderSourceModel.setHeaderData(0, Qt.Horizontal, "Resultaat") self.geocoderSourceModel.setHeaderData(1, Qt.Horizontal, "Type") #self.geocoderSourceModel.setHeaderData(2, Qt.Horizontal, "Id") #self.geocoderSourceModel.setHeaderData(3, Qt.Horizontal, "Score") self.geocoderSourceModel.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) self.dlg.geocoderResultView.resizeColumnsToContents() self.dlg.geocoderResultView.horizontalHeader().setStretchLastSection(True) def geocode(self, search_text): self.dlg.ui.lookupinfo.setHtml('') addresses = self.pdokgeocoder.search(search_text) if len(addresses) == 0: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ( \ "Niets gevonden. Probeer een andere spelling of alleen postcode/huisnummer." ), QMessageBox.Ok, QMessageBox.Ok) return for address in addresses: #print address adrestekst = QStandardItem("%s" % (address["adrestekst"])) adrestekst.setData(address, Qt.UserRole) straat = QStandardItem("%s" % (address["straat"])) nummer = QStandardItem("%s" % (address["nummer"])) postcode = QStandardItem("%s" % (address["postcode"])) plaats = QStandardItem("%s" % (address["plaats"])) gemeente = QStandardItem("%s" % (address["gemeente"])) provincie = QStandardItem("%s" % (address["provincie"])) self.geocoderSourceModel.appendRow([adrestekst, straat, nummer, postcode, plaats, gemeente, provincie]) self.dlg.geocoderResultView.selectRow(0) self.zoomToAddress() self.geocoderSourceModel.setHeaderData(0, Qt.Horizontal, "Resultaat") self.geocoderSourceModel.setHeaderData(1, Qt.Horizontal, "Straat") self.geocoderSourceModel.setHeaderData(2, Qt.Horizontal, "Nr") self.geocoderSourceModel.setHeaderData(3, Qt.Horizontal, "Postcode") self.geocoderSourceModel.setHeaderData(4, Qt.Horizontal, "Plaats") self.geocoderSourceModel.setHeaderData(5, Qt.Horizontal, "Gemeente") self.geocoderSourceModel.setHeaderData(6, Qt.Horizontal, "Provincie") self.geocoderSourceModel.horizontalHeaderItem(0).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(1).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(2).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(3).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(4).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(5).setTextAlignment(Qt.AlignLeft) self.geocoderSourceModel.horizontalHeaderItem(6).setTextAlignment(Qt.AlignLeft) self.dlg.geocoderResultView.resizeColumnsToContents() self.dlg.geocoderResultView.horizontalHeader().setStretchLastSection(True) def zoomToAddress(self): # get x,y from data of record self.removePointer() data = self.dlg.geocoderResultView.selectedIndexes()[0].data(Qt.UserRole) if 'centroide_rd' in data: # free OR lookup service geom = QgsGeometry.fromWkt(data['centroide_rd']) adrestekst = data['adrestekst'] else: # no centroid yet, probably only object id, retrieve it via lookup service id = data['id'] data = self.pdokgeocoder.lookup(id) geom = QgsGeometry.fromWkt(data['centroide_rd']) adrestekst = data['adrestekst'] lookup_data= data['data'] lis = '' for key in lookup_data.keys(): lis = lis + '<li>{}: {}</li>'.format(key, lookup_data[key]) self.dlg.ui.lookupinfo.setHtml( '<h4>{}</h4><lu>{}</lu>'.format(adrestekst, lis)) # just always transform from 28992 to mapcanvas crs crs = self.iface.mapCanvas().mapSettings().destinationCrs() crs28992 = QgsCoordinateReferenceSystem() crs28992.createFromId(28992) crsTransform = QgsCoordinateTransform(crs28992, crs, QgsProject.instance()) z = 1587 if adrestekst.startswith('adres'): z = 1587 elif adrestekst.startswith('straat'): z = 3175 elif adrestekst.startswith('postcode'): z = 6350 elif adrestekst.startswith('woonplaats'): z = 25398 elif adrestekst.startswith('gemeente'): z = 50797 elif adrestekst.startswith('provincie'): z = 812750 geom.transform(crsTransform) center = geom.asPoint() self.setPointer(center) # zoom to with center is actually setting a point rectangle and then zoom rect = QgsRectangle(center, center) self.iface.mapCanvas().setExtent(rect) self.iface.mapCanvas().zoomScale(z) self.iface.mapCanvas().refresh() def setPointer(self, point): self.removePointer() self.pointer = QgsVertexMarker(self.iface.mapCanvas()) self.pointer.setColor(QColor(255, 255, 0)) self.pointer.setIconSize(10) self.pointer.setPenWidth(5) self.pointer.setCenter(point) def removePointer(self): if self.pointer is not None: self.iface.mapCanvas().scene().removeItem(self.pointer)