def load_files(self): charset = utils.ask_for_charset() if not charset: raise utils.UserInterruptError() filename = utils.select_files(only_one_file=True, extension=ru(QCoreApplication.translate('GeneralCsvImportGui', "Comma or semicolon separated csv file %s;;Comma or semicolon separated csv text file %s;;Comma or semicolon separated file %s"))%('(*.csv)', '(*.txt)', '(*.*)')) if isinstance(filename, (list, tuple)): filename = filename[0] filename = ru(filename) delimiter = utils.get_delimiter(filename=filename, charset=charset, delimiters=[',', ';']) self.file_data = self.file_to_list(filename, charset, delimiter) header_question = utils.Askuser(question="YesNo", msg=ru(QCoreApplication.translate('GeneralCsvImportGui', """Does the file contain a header?"""))) utils.start_waiting_cursor() if header_question.result: # Remove duplicate header entries header = self.file_data[0] seen = set() seen_add = seen.add remove_cols = [idx for idx, x in enumerate(header) if x and (x in seen or seen_add(x))] self.file_data = [[col for idx, col in enumerate(row) if idx not in remove_cols] for row in self.file_data] self.table_chooser.file_header = self.file_data[0] else: header = ['Column ' + str(colnr) for colnr in range(len(self.file_data[0]))] self.table_chooser.file_header = header self.file_data.reverse() self.file_data.append(header) self.file_data.reverse() utils.stop_waiting_cursor()
def testFetchingResults(self): def got_hit(result): got_hit._results_.append(result.displayString) got_hit._results_ = [] context = QgsLocatorContext() # one filter l = QgsLocator() filter_a = test_filter('a') l.registerFilter(filter_a) l.foundResult.connect(got_hit) l.fetchResults('a', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'a0', 'a1', 'a2'}) # two filters filter_b = test_filter('b') l.registerFilter(filter_b) got_hit._results_ = [] l.fetchResults('a', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'a0', 'a1', 'a2', 'b0', 'b1', 'b2'})
def removeDir(path): result = "" if not QFile(path).exists(): result = QCoreApplication.translate("QgsPluginInstaller", "Nothing to remove! Plugin directory doesn't exist:") + "\n" + path elif QFile(path).remove(): # if it is only link, just remove it without resolving. pass else: fltr = QDir.Dirs | QDir.Files | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QFile(item).remove(): pass fltr = QDir.Dirs | QDir.Hidden iterator = QDirIterator(path, fltr, QDirIterator.Subdirectories) while iterator.hasNext(): item = iterator.next() if QDir().rmpath(item): pass if QFile(path).exists(): result = QCoreApplication.translate("QgsPluginInstaller", "Failed to remove the directory:") + "\n" + path + "\n" + QCoreApplication.translate("QgsPluginInstaller", "Check permissions or remove it manually") # restore plugin directory if removed by QDir().rmpath() pluginDir = qgis.utils.home_plugin_path if not QDir(pluginDir).exists(): QDir().mkpath(pluginDir) return result
def execute(self, sql, all_args=None): """ :param sql: :param all_args: A list of lists of equal lenght to sql (if sql is a list) containing arguments for ? in the corresponding sql. :return: """ if isinstance(sql, str): sql = [sql] elif not isinstance(sql, (list, tuple)): raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: sql must be type string or a list/tuple of strings. Was %s'))%ru(type(sql))) for idx, line in enumerate(sql): if all_args is None: try: self.cursor.execute(line) except Exception as e: textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nMsg:\n%s""")) % (ru(line), ru(str(e))) utils.MessagebarAndLog.warning( bar_msg=utils.sql_failed_msg(), log_msg=textstring) raise elif isinstance(all_args, (list, tuple)): args = all_args[idx] try: self.cursor.execute(line, args) except Exception as e: textstring = ru(QCoreApplication.translate('sql_load_fr_db', """DB error!\n SQL causing this error:%s\nusing args %s\nMsg:\n%s""")) % (ru(line), ru(args), ru(str(e))) utils.MessagebarAndLog.warning( bar_msg=utils.sql_failed_msg(), log_msg=textstring) raise else: raise TypeError(ru(QCoreApplication.translate('DbConnectionManager', 'DbConnectionManager.execute: all_args must be a list/tuple. Was %s')) % ru(type(all_args)))
def __init__(self, alg, in_place=False, parent=None): super().__init__(parent) self.feedback_dialog = None self.in_place = in_place self.active_layer = None self.context = None self.feedback = None self.setAlgorithm(alg) self.setMainWidget(self.getParametersPanel(alg, self)) if not self.in_place: self.runAsBatchButton = QPushButton(QCoreApplication.translate("AlgorithmDialog", "Run as Batch Process…")) self.runAsBatchButton.clicked.connect(self.runAsBatch) self.buttonBox().addButton(self.runAsBatchButton, QDialogButtonBox.ResetRole) # reset role to ensure left alignment else: self.active_layer = iface.activeLayer() self.runAsBatchButton = None has_selection = self.active_layer and (self.active_layer.selectedFeatureCount() > 0) self.buttonBox().button(QDialogButtonBox.Ok).setText(QCoreApplication.translate("AlgorithmDialog", "Modify Selected Features") if has_selection else QCoreApplication.translate("AlgorithmDialog", "Modify All Features")) self.buttonBox().button(QDialogButtonBox.Close).setText(QCoreApplication.translate("AlgorithmDialog", "Cancel")) self.setWindowTitle(self.windowTitle() + ' | ' + self.active_layer.name())
def testTaskFromFunctionWithSubTaskCompletedIsCalledOnce(self): # spellok """ test that when a parent task has subtasks it does emit taskCompleted only once""" self.finished = 0 self.completed = 0 def _on_finished(e): self.finished += 1 def _on_completed(): self.completed += 1 task = QgsTask.fromFunction('test task', run_no_result, on_finished=_on_finished) task.taskCompleted.connect(_on_completed) spy = QSignalSpy(task.taskCompleted) sub_task_1 = QgsTask.fromFunction('test subtask 1', run_no_result, on_finished=_on_finished) sub_task_2 = QgsTask.fromFunction('test subtask 2', run_no_result, on_finished=_on_finished) task.addSubTask(sub_task_1, [], QgsTask.ParentDependsOnSubTask) task.addSubTask(sub_task_2, [], QgsTask.ParentDependsOnSubTask) QgsApplication.taskManager().addTask(task) while task.status() not in [QgsTask.Complete, QgsTask.Terminated]: QCoreApplication.processEvents() while QgsApplication.taskManager().countActiveTasks() > 0: QCoreApplication.processEvents() self.assertEqual(self.completed, 1) self.assertEqual(self.finished, 3) self.assertEqual(len(spy), 1)
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 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)
def switchToolMode(self): self.setCommandViewerEnabled(not self.batchCheck.isChecked()) self.progressBar.setVisible(self.batchCheck.isChecked()) self.inSelector.setType(self.inSelector.FILE if self.batchCheck.isChecked() else self.inSelector.FILE_LAYER) self.outSelector.clear() if self.batchCheck.isChecked(): self.inFileLabel = self.label.text() self.outFileLabel = self.label_2.text() self.label.setText(QCoreApplication.translate("GdalTools", "&Input directory")) self.label_2.setText(QCoreApplication.translate("GdalTools", "&Output directory")) self.inSelector.selectClicked.disconnect(self.fillInputFile) self.outSelector.selectClicked.disconnect(self.fillOutputFileEdit) self.inSelector.selectClicked.connect(self.fillInputDir) self.outSelector.selectClicked.connect(self.fillOutputDir) else: self.label.setText(self.inFileLabel) self.label_2.setText(self.outFileLabel) self.inSelector.selectClicked.disconnect(self.fillInputDir) self.outSelector.selectClicked.disconnect(self.fillOutputDir) self.inSelector.selectClicked.connect(self.fillInputFile) self.outSelector.selectClicked.connect(self.fillOutputFileEdit)
def test_priority(self): env = "QGIS_OPTIONS_PATH" dpath = "conf0" QCoreApplication.setOrganizationName(dpath) # load settings os.environ[env] = self.testdata_path self.settings.load() # test conf self.assertTrue(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 3) # set environment variables and test priority env_pr = "QGIS_SERVER_PARALLEL_RENDERING" os.environ[env_pr] = "0" env_mt = "QGIS_SERVER_MAX_THREADS" os.environ[env_mt] = "5" self.settings.load() self.assertFalse(self.settings.parallelRendering()) self.assertEqual(self.settings.maxThreads(), 5) # clear environment os.environ.pop(env) os.environ.pop(env_pr) os.environ.pop(env_mt)
def show(self): QDialog.show(self) self.setWindowModality(0) if self.firstShow: inet = internet_on(proxyUrl=self.proxy, timeout=self.timeout) #filters if inet: self.poiThemes = dict( self.poi.listPoiThemes() ) poiThemes = [""] + list(self.poiThemes.keys()) poiThemes.sort() self.ui.filterPoiThemeCombo.addItems( poiThemes ) self.poiCategories = dict( self.poi.listPoiCategories() ) poiCategories = [""] + list(self.poiCategories.keys()) poiCategories.sort() self.ui.filterPoiCategoryCombo.addItems( poiCategories ) self.poiTypes = dict( self.poi.listPoitypes() ) poiTypes = [""] + list(self.poiTypes.keys()) poiTypes.sort() self.ui.filterPoiTypeCombo.addItems( poiTypes ) gemeentes = json.load( open(os.path.join(os.path.dirname(__file__), "data/gemeentenVL.json")) ) self.NIScodes= { n["Naam"] : n["Niscode"] for n in gemeentes } gemeenteNamen = [n["Naam"] for n in gemeentes] gemeenteNamen.sort() self.ui.filterPoiNIS.addItems( gemeenteNamen ) #connect when inet on self.ui.filterPoiThemeCombo.activated.connect(self.onThemeFilterChange) self.ui.filterPoiCategoryCombo.activated.connect(self.onCategorieFilterChange) self.firstShow = False else: self.bar.pushMessage( QCoreApplication.translate("geopunt4QgisPoidialog", "Waarschuwing "), QCoreApplication.translate("geopunt4QgisPoidialog", "Kan geen verbing maken met het internet."), level=Qgis.Warning, duration=3)
def showPopupMenu(self, point): item = self.algorithmTree.itemAt(point) popupmenu = QMenu() if isinstance(item, TreeAlgorithmItem): alg = item.alg executeAction = QAction(QCoreApplication.translate('ProcessingToolbox', 'Execute…'), self.algorithmTree) executeAction.triggered.connect(self.executeAlgorithm) popupmenu.addAction(executeAction) if alg.flags() & QgsProcessingAlgorithm.FlagSupportsBatch: executeBatchAction = QAction( QCoreApplication.translate('ProcessingToolbox', 'Execute as Batch Process…'), self.algorithmTree) executeBatchAction.triggered.connect( self.executeAlgorithmAsBatchProcess) popupmenu.addAction(executeBatchAction) popupmenu.addSeparator() editRenderingStylesAction = QAction( QCoreApplication.translate('ProcessingToolbox', 'Edit Rendering Styles for Outputs…'), self.algorithmTree) editRenderingStylesAction.triggered.connect( self.editRenderingStyles) popupmenu.addAction(editRenderingStylesAction) actions = ProviderContextMenuActions.actions if len(actions) > 0: popupmenu.addSeparator() for action in actions: action.setData(item.alg, self) if action.isEnabled(): contextMenuAction = QAction(action.name, self.algorithmTree) contextMenuAction.triggered.connect(action.execute) popupmenu.addAction(contextMenuAction) popupmenu.exec_(self.algorithmTree.mapToGlobal(point))
def startServerPlugin(packageName): """ initialize the plugin """ global server_plugins, server_active_plugins, serverIface if packageName in server_active_plugins: return False if packageName not in sys.modules: return False package = sys.modules[packageName] errMsg = QCoreApplication.translate("Python", "Couldn't load server plugin %s") % packageName # create an instance of the plugin try: server_plugins[packageName] = package.serverClassFactory(serverIface) except: _unloadPluginModules(packageName) msg = QCoreApplication.translate("Python", "%s due to an error when calling its serverClassFactory() method") % errMsg showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg) return False # add to active plugins server_active_plugins.append(packageName) return True
def selectExtent(self): popupmenu = QMenu() useCanvasExtentAction = QAction( QCoreApplication.translate("ExtentSelectionPanel", 'Use Canvas Extent'), self.btnSelect) useLayerExtentAction = QAction( QCoreApplication.translate("ExtentSelectionPanel", 'Use Layer Extent…'), self.btnSelect) selectOnCanvasAction = QAction( self.tr('Select Extent on Canvas'), self.btnSelect) popupmenu.addAction(useCanvasExtentAction) popupmenu.addAction(selectOnCanvasAction) popupmenu.addSeparator() popupmenu.addAction(useLayerExtentAction) selectOnCanvasAction.triggered.connect(self.selectOnCanvas) useLayerExtentAction.triggered.connect(self.useLayerExtent) useCanvasExtentAction.triggered.connect(self.useCanvasExtent) if self.param.flags() & QgsProcessingParameterDefinition.FlagOptional: useMincoveringExtentAction = QAction( self.tr('Use Min Covering Extent from Input Layers'), self.btnSelect) useMincoveringExtentAction.triggered.connect( self.useMinCoveringExtent) popupmenu.addAction(useMincoveringExtentAction) popupmenu.exec_(QCursor.pos())
def testLayerRemovalBeforeRun(self): """test behavior when layer is removed before task begins""" path = os.path.join(unitTestDataPath(), 'raster', 'with_color_table.tif') raster_layer = QgsRasterLayer(path, "test") self.assertTrue(raster_layer.isValid()) pipe = QgsRasterPipe() self.assertTrue(pipe.set(raster_layer.dataProvider().clone())) tmp = create_temp_filename('remove_layer.tif') writer = QgsRasterFileWriter(tmp) task = QgsRasterFileWriterTask(writer, pipe, 100, 100, raster_layer.extent(), raster_layer.crs()) task.writeComplete.connect(self.onSuccess) task.errorOccurred.connect(self.onFail) # remove layer raster_layer = None QgsApplication.taskManager().addTask(task) while not self.success and not self.fail: QCoreApplication.processEvents() # in this case will still get a positive result - since the pipe is cloned before the task # begins the task is no longer dependent on the original layer self.assertTrue(self.success) self.assertFalse(self.fail) self.assertTrue(os.path.exists(tmp))
def testClear(self): """ Test clearing the collection """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() collection.clear() # add a page page = QgsLayoutItemPage(l) page.setPageSize('A4') collection.addPage(page) # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') collection.addPage(page2) page_about_to_be_removed_spy = QSignalSpy(collection.pageAboutToBeRemoved) # clear collection.clear() self.assertEqual(collection.pageCount(), 0) self.assertEqual(len(page_about_to_be_removed_spy), 2) QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) self.assertTrue(sip.isdeleted(page)) self.assertTrue(sip.isdeleted(page2))
def startProcessingPlugin(packageName): """ initialize only the Processing components of a plugin """ global plugins, active_plugins, iface, plugin_times start = time.process_time() if not _startPlugin(packageName): return False errMsg = QCoreApplication.translate("Python", "Couldn't load plugin '{0}'").format(packageName) if not hasattr(plugins[packageName], 'initProcessing'): del plugins[packageName] _unloadPluginModules(packageName) msg = QCoreApplication.translate("Python", "{0} - plugin has no initProcessing() method").format(errMsg) showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True) return False # initProcessing try: plugins[packageName].initProcessing() except: del plugins[packageName] _unloadPluginModules(packageName) msg = QCoreApplication.translate("Python", "{0} due to an error when calling its initProcessing() method").format(errMsg) showException(sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2], msg, messagebar=True) return False end = time.process_time() _addToActivePlugins(packageName, end - start) return True
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.homePath()) 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 createMenu(self): self.menu.clear() self.menu.setMinimumWidth(self.width()) fill_down_action = QAction(self.tr('Fill Down'), self.menu) fill_down_action.triggered.connect(self.fillDown) fill_down_action.setToolTip(self.tr('Copy the first value down to all other rows')) self.menu.addAction(fill_down_action) calculate_by_expression = QAction(QCoreApplication.translate('BatchPanel', 'Calculate by Expression…'), self.menu) calculate_by_expression.setIcon(QgsApplication.getThemeIcon('/mActionCalculateField.svg')) calculate_by_expression.triggered.connect(self.calculateByExpression) calculate_by_expression.setToolTip(self.tr('Calculates parameter values by evaluating an expression')) self.menu.addAction(calculate_by_expression) add_by_expression = QAction(QCoreApplication.translate('BatchPanel', 'Add Values by Expression…'), self.menu) add_by_expression.triggered.connect(self.addByExpression) add_by_expression.setToolTip(self.tr('Adds new parameter values by evaluating an expression')) self.menu.addAction(add_by_expression) if isinstance(self.parameterDefinition, (QgsProcessingParameterFile, QgsProcessingParameterMapLayer, QgsProcessingParameterRasterLayer, QgsProcessingParameterMeshLayer, QgsProcessingParameterVectorLayer, QgsProcessingParameterFeatureSource)): self.menu.addSeparator() find_by_pattern_action = QAction(QCoreApplication.translate('BatchPanel', 'Add Files by Pattern…'), self.menu) find_by_pattern_action.triggered.connect(self.addFilesByPattern) find_by_pattern_action.setToolTip(self.tr('Adds files by a file pattern match')) self.menu.addAction(find_by_pattern_action)
def __init__(self, parent): QDialog.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console")) self.parent = parent self.setupUi(self) self.listPath = [] self.lineEdit.setReadOnly(True) self.restoreSettings() self.initialCheck() self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.svg")) self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path")) self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.svg")) self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path")) self.preloadAPI.stateChanged.connect(self.initialCheck) self.addAPIpath.clicked.connect(self.loadAPIFile) self.removeAPIpath.clicked.connect(self.removeAPI) self.compileAPIs.clicked.connect(self._prepareAPI) self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColor.setIconSize(QSize(18, 18)) self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColorEditor.setIconSize(QSize(18, 18)) self.resetFontColor.clicked.connect(self._resetFontColor) self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
def update_settings(self, _db_settings): db_settings = None if not _db_settings or _db_settings is None: return try: db_settings = ast.literal_eval(_db_settings) except: utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Reading db_settings failed using string %s'))%_db_settings) else: pass for setting in [db_settings, _db_settings]: if isinstance(setting, str): # Assume that the db_settings is an old spatialite database if os.path.isfile(setting) and setting.endswith('.sqlite'): db_settings = {'spatialite': {'dbpath': setting}} break if isinstance(db_settings, dict): for dbtype, settings in db_settings.items(): self.dbtype_combobox = dbtype self.choose_dbtype() for setting_name, value in settings.items(): try: if hasattr(self.db_settings_obj, str(setting_name)): setattr(self.db_settings_obj, str(setting_name), value) else: utils.MessagebarAndLog.warning(log_msg=ru(QCoreApplication.translate('DatabaseSettings', "Databasetype %s didn' t have setting %s"))%(dbtype, setting_name)) except: print(str(setting_name)) raise else: utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('DatabaseSettings', "Could not load database settings. Select database again!")), log_msg=ru(QCoreApplication.translate('DatabaseSettings', 'Tried to load db_settings string %s'))%_db_settings)
def write(self, m): if self.style == "_traceback": # Show errors in red stderrColor = QColor(self.sO.settings.value("pythonConsole/stderrFontColor", QColor(Qt.red))) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01, stderrColor) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True) self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True) pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS) self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31) self.sO.append(m) self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01) else: self.sO.append(m) if self.out: self.out.write(m) self.move_cursor_to_end() if self.style != "_traceback": QCoreApplication.processEvents() if self.fire_keyboard_interrupt: self.fire_keyboard_interrupt = False raise KeyboardInterrupt
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 a 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', 'NNJoin_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.NNJOIN = self.tr('NNJoin') self.NNJOINAMP = self.tr('&NNJoin') self.toolbar = None
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', 'GBIFOccurrences_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = GBIFOccurrencesDialog() # Declare instance attributes self.actions = [] self.menu = self.tr(u'&GBIF Occurrences') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'GBIFOccurrences') self.toolbar.setObjectName(u'GBIFOccurrences')
def import_foreign_keys(self, dbconnection, goal_table, temptablename, foreign_keys, existing_columns_in_temptable): #TODO: Empty foreign keys are probably imported now. Must add "case when...NULL" to a couple of sql questions here #What I want to do: # import all foreign keys from temptable that doesn't already exist in foreign key table # insert into fk_table (to1, to2) select distinct from1(cast as), from2(cast as) from temptable where concatted_from_and_case_when_null not in concatted_to_and_case_when_null for fk_table, from_to_fields in foreign_keys.items(): from_list = [x[0] for x in from_to_fields] to_list = [x[1] for x in from_to_fields] if not all([_from in existing_columns_in_temptable for _from in from_list]): utils.MessagebarAndLog.warning(bar_msg=ru(QCoreApplication.translate('midv_data_importer', 'Import of foreign keys failed, see log message panel')), log_msg=ru(QCoreApplication.translate('midv_data_importer', 'There were keys missing for importing to fk_table %s, so no import was done.'))%fk_table) continue nr_fk_before = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0] table_info = db_utils.db_tables_columns_info(table=fk_table, dbconnection=dbconnection)[fk_table] column_headers_types = dict([(row[1], row[2]) for row in table_info]) null_replacement_string = 'NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL_NULL' concatted_from_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in from_list]) concatted_to_string = '||'.join(["CASE WHEN %s is NULL THEN '%s' ELSE %s END"%(x, null_replacement_string, x) for x in to_list]) sql = u'INSERT INTO %s (%s) SELECT DISTINCT %s FROM %s AS b WHERE %s NOT IN (SELECT %s FROM %s) AND %s'%(fk_table, u', '.join([u'"{}"'.format(k) for k in to_list]), u', '.join([u'''CAST("b"."%s" as "%s")'''%(k, column_headers_types[to_list[idx]]) for idx, k in enumerate(from_list)]), temptablename, concatted_from_string, concatted_to_string, fk_table, ' AND '.join([''' b.{} IS NOT NULL and b.{} != '' '''.format(k, k, k) for k in from_list])) dbconnection.execute(sql) nr_fk_after = dbconnection.execute_and_fetchall('''select count(*) from %s''' % fk_table)[0][0] if nr_fk_after > nr_fk_before: utils.MessagebarAndLog.info(log_msg=ru(QCoreApplication.translate('midv_data_importer', 'In total %s rows were imported to foreign key table %s while importing to %s.'))%(str(nr_fk_after - nr_fk_before), fk_table, goal_table))
def __init__(self, iface): locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( os.path.dirname(__file__), 'i18n', 'qdraw_{}.qm'.format(locale)) self.translator = None if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.iface = iface self.sb = self.iface.statusBarIface() self.tool = None self.toolname = None self.bGeom = None self.actions = [] self.menu = '&Qdraw' self.toolbar = self.iface.addToolBar('Qdraw') self.toolbar.setObjectName('Qdraw') self.settings = QdrawSettings()
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 = QLocale(QSettings().value('locale/userLocale')) locale_path = os.path.join(self.plugin_dir, 'i18n') self.translator = QTranslator() self.translator.load(locale, 'QFieldSync', '_', locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&QFieldSync') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.addToolBar(u'QFieldSync') self.toolbar.setObjectName(u'QFieldSync') # instance of the QgsOfflineEditing self.offline_editing = QgsOfflineEditing() self.preferences = Preferences() QgsProject.instance().readProject.connect(self.update_button_enabled_status) # store warnings from last run self.last_action_warnings = []
def defineCharacteristicsFromFile(self): lines = open(self.descriptionFile) line = lines.readline().strip('\n').strip() self.name = line self.i18n_name = QCoreApplication.translate("TAUDEMAlgorithm", line) line = lines.readline().strip('\n').strip() self.cmdName = line line = lines.readline().strip('\n').strip() self.group = line self.i18n_group = QCoreApplication.translate("TAUDEMAlgorithm", line) line = lines.readline().strip('\n').strip() while line != '': try: line = line.strip('\n').strip() if line.startswith('Parameter'): param = getParameterFromString(line) self.addParameter(param) else: self.addOutput(getOutputFromString(line)) line = lines.readline().strip('\n').strip() except Exception as e: ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, self.tr('Could not load TauDEM algorithm: %s\n%s' % (self.descriptionFile, line))) raise e lines.close()
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 a reference to the QGIS interface self.iface = iface # initialize the plugin directory pluginPath = os.path.dirname(__file__) # initialize the locale using the QGIS locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( pluginPath, 'i18n', '{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep the reference self.dlg = linedirectionhistogramDialog(self.iface) # Declare instance attributes self.menuname = self.tr(u'&Line Direction Histogram')
def initAlgorithm(self, config=None): class ParameterVrtDestination(QgsProcessingParameterRasterDestination): def __init__(self, name, description): super().__init__(name, description) def clone(self): copy = ParameterVrtDestination(self.name(), self.description()) return copy def type(self): return 'vrt_destination' def defaultFileExtension(self): return 'vrt' self.addParameter(QgsProcessingParameterMultipleLayers(self.INPUT, QCoreApplication.translate("ParameterVrtDestination", 'Input layers'), QgsProcessing.TypeRaster)) self.addParameter(QgsProcessingParameterEnum(self.RESOLUTION, QCoreApplication.translate("ParameterVrtDestination", 'Resolution'), options=self.RESOLUTION_OPTIONS, defaultValue=0)) self.addParameter(QgsProcessingParameterBoolean(self.SEPARATE, QCoreApplication.translate("ParameterVrtDestination", 'Layer stack'), defaultValue=True)) self.addParameter(QgsProcessingParameterBoolean(self.PROJ_DIFFERENCE, QCoreApplication.translate("ParameterVrtDestination", 'Allow projection difference'), defaultValue=False)) self.addParameter(ParameterVrtDestination(self.OUTPUT, QCoreApplication.translate("ParameterVrtDestination", 'Virtual')))
def __init__(self): self.name = QCoreApplication.translate('DeleteModelAction', 'Delete Model…')
def progress_changed(self, value): QCoreApplication.processEvents() # Listen to cancel from the user self.progress.setValue(value)
def fill_right_of_way_relations(self, db): layers = { ADMINISTRATIVE_SOURCE_TABLE: { 'name': ADMINISTRATIVE_SOURCE_TABLE, 'geometry': None, LAYER: None }, PARCEL_TABLE: { 'name': PARCEL_TABLE, 'geometry': None, LAYER: None }, PLOT_TABLE: { 'name': PLOT_TABLE, 'geometry': QgsWkbTypes.PolygonGeometry, LAYER: None }, RESTRICTION_TABLE: { 'name': RESTRICTION_TABLE, 'geometry': None, LAYER: None }, RIGHT_OF_WAY_TABLE: { 'name': RIGHT_OF_WAY_TABLE, 'geometry': QgsWkbTypes.PolygonGeometry, LAYER: None }, RRR_SOURCE_RELATION_TABLE: { 'name': RRR_SOURCE_RELATION_TABLE, 'geometry': None, LAYER: None }, SURVEY_POINT_TABLE: { 'name': SURVEY_POINT_TABLE, 'geometry': None, LAYER: None }, UEBAUNIT_TABLE: { 'name': UEBAUNIT_TABLE, 'geometry': None, LAYER: None } } # Load layers self.qgis_utils.get_layers(db, layers, load=True) if not layers: return None if layers[PLOT_TABLE][LAYER].selectedFeatureCount( ) == 0 or layers[RIGHT_OF_WAY_TABLE][LAYER].selectedFeatureCount( ) == 0 or layers[ADMINISTRATIVE_SOURCE_TABLE][ LAYER].selectedFeatureCount() == 0: if self.qgis_utils.get_layer_from_layer_tree( db, PLOT_TABLE, geometry_type=QgsWkbTypes.PolygonGeometry) is None: self.qgis_utils.message_with_button_load_layer_emitted.emit( QCoreApplication.translate( "RightOfWay", "First load the layer {} into QGIS and select at least one plot!" ).format(PLOT_TABLE), QCoreApplication.translate( "RightOfWay", "Load layer {} now").format(PLOT_TABLE), [PLOT_TABLE, None], Qgis.Warning) else: self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "RightOfWay", "Select at least one benefited plot, one right of way and at least one administrative source to create relations!" ), Qgis.Warning) return else: ue_baunit_features = layers[UEBAUNIT_TABLE][LAYER].getFeatures() # Get unique pairs id_right_of_way-id_parcel existing_pairs = [ (ue_baunit_feature[UEBAUNIT_TABLE_PARCEL_FIELD], ue_baunit_feature[UEBAUNIT_TABLE_RIGHT_OF_WAY_FIELD]) for ue_baunit_feature in ue_baunit_features ] existing_pairs = set(existing_pairs) plot_ids = [ f[ID_FIELD] for f in layers[PLOT_TABLE][LAYER].selectedFeatures() ] right_of_way_id = layers[RIGHT_OF_WAY_TABLE][ LAYER].selectedFeatures()[0].attribute(ID_FIELD) id_pairs = list() for plot in plot_ids: exp = "\"{uebaunit}\" = {plot}".format( uebaunit=UEBAUNIT_TABLE_PLOT_FIELD, plot=plot) parcels = layers[UEBAUNIT_TABLE][LAYER].getFeatures(exp) for parcel in parcels: id_pair = (parcel.attribute(UEBAUNIT_TABLE_PARCEL_FIELD), right_of_way_id) id_pairs.append(id_pair) if len(id_pairs) < len(plot_ids): # If any relationship plot-parcel is not found, we don't need to continue self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "RightOfWay", "One or more pairs id_plot-id_parcel weren't found, this is needed to create benefited and restriction relations." ), Qgis.Warning) return if id_pairs: new_features = list() for id_pair in id_pairs: if not id_pair in existing_pairs: #Create feature new_feature = QgsVectorLayerUtils().createFeature( layers[UEBAUNIT_TABLE][LAYER]) new_feature.setAttribute(UEBAUNIT_TABLE_PARCEL_FIELD, id_pair[0]) new_feature.setAttribute( UEBAUNIT_TABLE_RIGHT_OF_WAY_FIELD, id_pair[1]) self.log.logMessage( "Saving RightOfWay-Parcel: {}-{}".format( id_pair[1], id_pair[0]), PLUGIN_NAME, Qgis.Info) new_features.append(new_feature) layers[UEBAUNIT_TABLE][LAYER].dataProvider().addFeatures( new_features) self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "RightOfWay", "{} out of {} records were saved into {}! {} out of {} records already existed in the database." ).format(len(new_features), len(id_pairs), UEBAUNIT_TABLE, len(id_pairs) - len(new_features), len(id_pairs)), Qgis.Info) spatial_join_layer = processing.run( "qgis:joinattributesbylocation", { 'INPUT': layers[PLOT_TABLE][LAYER], 'JOIN': QgsProcessingFeatureSourceDefinition( layers[RIGHT_OF_WAY_TABLE][LAYER].id(), True), 'PREDICATE': [0], 'JOIN_FIELDS': [ID_FIELD, RIGHT_OF_WAY_TABLE_IDENTIFICATOR_FIELD], 'METHOD': 0, 'DISCARD_NONMATCHING': True, 'PREFIX': '', 'OUTPUT': 'memory:' })['OUTPUT'] restriction_features = layers[RESTRICTION_TABLE][ LAYER].getFeatures() existing_restriction_pairs = [ (restriction_feature[RESTRICTION_TABLE_PARCEL_FIELD], restriction_feature[RESTRICTION_TABLE_DESCRIPTION_FIELD]) for restriction_feature in restriction_features ] existing_restriction_pairs = set(existing_restriction_pairs) id_pairs_restriction = list() plot_ids = spatial_join_layer.getFeatures() for plot in plot_ids: exp = "\"uebaunit\" = {plot}".format( uebaunit=UEBAUNIT_TABLE_PLOT_FIELD, plot=plot.attribute(ID_FIELD)) parcels = layers[UEBAUNIT_TABLE][LAYER].getFeatures(exp) for parcel in parcels: id_pair_restriction = ( parcel.attribute(UEBAUNIT_TABLE_PARCEL_FIELD), "Asociada a la servidumbre {}".format( plot.attribute( RIGHT_OF_WAY_TABLE_IDENTIFICATOR_FIELD))) id_pairs_restriction.append(id_pair_restriction) new_restriction_features = list() if id_pairs_restriction: for id_pair in id_pairs_restriction: if not id_pair in existing_restriction_pairs: #Create feature new_feature = QgsVectorLayerUtils().createFeature( layers[RESTRICTION_TABLE][LAYER]) new_feature.setAttribute( RESTRICTION_TABLE_PARCEL_FIELD, id_pair[0]) new_feature.setAttribute( RESTRICTION_TABLE_DESCRIPTION_FIELD, id_pair[1]) new_feature.setAttribute( TYPE_FIELD, COL_RESTRICTION_TYPE_RIGHT_OF_WAY_VALUE) self.log.logMessage( "Saving RightOfWay-Parcel: {}-{}".format( id_pair[1], id_pair[0]), PLUGIN_NAME, Qgis.Info) new_restriction_features.append(new_feature) layers[RESTRICTION_TABLE][LAYER].dataProvider().addFeatures( new_restriction_features) self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "RightOfWay", "{} out of {} records were saved into {}! {} out of {} records already existed in the database." ).format( len(new_restriction_features), len(id_pairs_restriction), RESTRICTION_TABLE, len(id_pairs_restriction) - len(new_restriction_features), len(id_pairs_restriction)), Qgis.Info) administrative_source_ids = [ f[ID_FIELD] for f in layers[ADMINISTRATIVE_SOURCE_TABLE] [LAYER].selectedFeatures() ] source_relation_features = layers[RRR_SOURCE_RELATION_TABLE][ LAYER].getFeatures() existing_source_pairs = [ (source_relation_feature[RRR_SOURCE_SOURCE_FIELD], source_relation_feature[RRR_SOURCE_RESTRICTION_FIELD]) for source_relation_feature in source_relation_features ] existing_source_pairs = set(existing_source_pairs) rrr_source_relation_pairs = list() for administrative_source_id in administrative_source_ids: for restriction_feature in new_restriction_features: rrr_source_relation_pair = ( administrative_source_id, restriction_feature.attribute(ID_FIELD)) rrr_source_relation_pairs.append(rrr_source_relation_pair) new_rrr_source_relation_features = list() if rrr_source_relation_pairs: for id_pair in rrr_source_relation_pairs: if not id_pair in existing_source_pairs: new_feature = QgsVectorLayerUtils().createFeature( layers[RRR_SOURCE_RELATION_TABLE][LAYER]) new_feature.setAttribute(RRR_SOURCE_SOURCE_FIELD, id_pair[0]) new_feature.setAttribute(RRR_SOURCE_RESTRICTION_FIELD, id_pair[1]) self.log.logMessage( "Saving Restriction-Source: {}-{}".format( id_pair[1], id_pair[0]), PLUGIN_NAME, Qgis.Info) new_rrr_source_relation_features.append(new_feature) layers[RRR_SOURCE_RELATION_TABLE][LAYER].dataProvider( ).addFeatures(new_rrr_source_relation_features) self.qgis_utils.message_emitted.emit( QCoreApplication.translate( "RightOfWay", "{} out of {} records were saved into {}! {} out of {} records already existed in the database." ).format( len(new_rrr_source_relation_features), len(rrr_source_relation_pairs), RRR_SOURCE_RELATION_TABLE, len(rrr_source_relation_pairs) - len(new_rrr_source_relation_features), len(rrr_source_relation_pairs)), Qgis.Info)
def testModel(self): m = QgsLocatorModel() p = QgsLocatorProxyModel(m) p.setSourceModel(m) l = QgsLocator() filter_a = test_filter('a') l.registerFilter(filter_a) l.foundResult.connect(m.addResult) context = QgsLocatorContext() l.fetchResults('a', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() # 4 results - one is locator name self.assertEqual(p.rowCount(), 4) self.assertEqual(p.data(p.index(0, 0)), 'test_a') self.assertEqual(p.data(p.index(0, 0), QgsLocatorModel.ResultTypeRole), 0) self.assertEqual( p.data(p.index(0, 0), QgsLocatorModel.ResultFilterNameRole), 'test_a') self.assertEqual(p.data(p.index(1, 0)), 'a0') self.assertEqual(p.data(p.index(1, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual( p.data(p.index(1, 0), QgsLocatorModel.ResultFilterNameRole), 'test_a') self.assertEqual(p.data(p.index(2, 0)), 'a1') self.assertEqual(p.data(p.index(2, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual( p.data(p.index(2, 0), QgsLocatorModel.ResultFilterNameRole), 'test_a') self.assertEqual(p.data(p.index(3, 0)), 'a2') self.assertEqual(p.data(p.index(3, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual( p.data(p.index(3, 0), QgsLocatorModel.ResultFilterNameRole), 'test_a') m.clear() self.assertEqual(p.rowCount(), 0) l.fetchResults('b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(p.rowCount(), 4) self.assertEqual(p.data(p.index(1, 0)), 'a0') self.assertEqual(p.data(p.index(2, 0)), 'a1') self.assertEqual(p.data(p.index(3, 0)), 'a2') m.deferredClear() # should not be immediately cleared! self.assertEqual(p.rowCount(), 4) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(p.rowCount(), 0) m.clear() # test with groups self.assertEqual(p.rowCount(), 0) filter_b = test_filter('b', None, True) l.registerFilter(filter_b) l.fetchResults('c', context) for i in range(200): sleep(0.002) QCoreApplication.processEvents() self.assertEqual( p.rowCount(), 16) # 1 title a + 3 results + 1 title b + 2 groups + 9 results self.assertEqual(p.data(p.index(0, 0)), 'test_a') self.assertEqual(p.data(p.index(0, 0), QgsLocatorModel.ResultTypeRole), 0) self.assertEqual(p.data(p.index(1, 0)), 'a0') self.assertEqual(p.data(p.index(1, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual(p.data(p.index(2, 0)), 'a1') self.assertEqual(p.data(p.index(2, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual(p.data(p.index(3, 0)), 'a2') self.assertEqual(p.data(p.index(3, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup) self.assertEqual(p.data(p.index(4, 0)), 'test_b') self.assertEqual(p.data(p.index(4, 0), QgsLocatorModel.ResultTypeRole), 0) self.assertEqual( p.data(p.index(4, 0), QgsLocatorModel.ResultFilterNameRole), 'test_b') self.assertEqual(p.data(p.index(5, 0)).strip(), 'first group') self.assertEqual(p.data(p.index(5, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(6, 0)), 'b0') self.assertEqual(p.data(p.index(6, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(7, 0)), 'b1') self.assertEqual(p.data(p.index(7, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(8, 0)), 'b2') self.assertEqual(p.data(p.index(8, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(9, 0)), 'b3') self.assertEqual(p.data(p.index(9, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(10, 0)), 'b4') self.assertEqual( p.data(p.index(10, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(11, 0)), 'b5') self.assertEqual( p.data(p.index(11, 0), QgsLocatorModel.ResultTypeRole), 1) self.assertEqual(p.data(p.index(12, 0)).strip(), 'second group') self.assertEqual( p.data(p.index(12, 0), QgsLocatorModel.ResultTypeRole), 2) self.assertEqual(p.data(p.index(13, 0)), 'b6') self.assertEqual( p.data(p.index(13, 0), QgsLocatorModel.ResultTypeRole), 2) self.assertEqual(p.data(p.index(14, 0)), 'b7') self.assertEqual( p.data(p.index(14, 0), QgsLocatorModel.ResultTypeRole), 2) self.assertEqual(p.data(p.index(15, 0)), 'b8') self.assertEqual( p.data(p.index(15, 0), QgsLocatorModel.ResultTypeRole), QgsLocatorModel.NoGroup)
def testPrefixes(self): """ Test custom (active) prefixes """ def got_hit(result): got_hit._results_.append(result.displayString) got_hit._results_ = [] context = QgsLocatorContext() l = QgsLocator() # filter with prefix filter_a = test_filter('a', 'aaa') l.registerFilter(filter_a) self.assertEqual(filter_a.prefix(), 'aaa') self.assertEqual(filter_a.activePrefix(), 'aaa') self.assertEqual(filter_a.useWithoutPrefix(), True) l.foundResult.connect(got_hit) l.fetchResults('aaa a', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'a0', 'a1', 'a2'}) got_hit._results_ = [] l.fetchResults('bbb b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'a0', 'a1', 'a2'}) got_hit._results_ = [] filter_a.setUseWithoutPrefix(False) self.assertEqual(filter_a.useWithoutPrefix(), False) l.fetchResults('bbb b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(got_hit._results_, []) got_hit._results_ = [] # test with two filters filter_b = test_filter('b', 'bbb') l.registerFilter(filter_b) self.assertEqual(filter_b.prefix(), 'bbb') self.assertEqual(filter_b.activePrefix(), 'bbb') got_hit._results_ = [] l.fetchResults('bbb b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'b0', 'b1', 'b2'}) l.deregisterFilter(filter_b) # test with two filters with same prefix filter_b = test_filter('b', 'aaa') l.registerFilter(filter_b) self.assertEqual(filter_b.prefix(), 'aaa') self.assertEqual(filter_b.activePrefix(), 'aaa') got_hit._results_ = [] l.fetchResults('aaa b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'a0', 'a1', 'a2', 'b0', 'b1', 'b2'}) l.deregisterFilter(filter_b) # filter with invalid prefix (less than 3 char) filter_c = test_filter('c', 'bb') l.registerFilter(filter_c) self.assertEqual(filter_c.prefix(), 'bb') self.assertEqual(filter_c.activePrefix(), '') got_hit._results_ = [] l.fetchResults('b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'c0', 'c1', 'c2'}) l.deregisterFilter(filter_c) # filter with custom prefix QgsSettings().setValue("locator_filters/prefix_test_custom", 'xyz', QgsSettings.Gui) filter_c = test_filter('custom', 'abc') l.registerFilter(filter_c) self.assertEqual(filter_c.prefix(), 'abc') self.assertEqual(filter_c.activePrefix(), 'xyz') got_hit._results_ = [] l.fetchResults('b', context) for i in range(100): sleep(0.002) QCoreApplication.processEvents() self.assertEqual(set(got_hit._results_), {'custom0', 'custom1', 'custom2'}) l.deregisterFilter(filter_c) del l
def defineCharacteristicsFromFile(self): """ Create algorithm parameters and outputs from a text file. """ with open(self.descriptionFile) as lines: # First line of the file is the Grass algorithm name line = lines.readline().strip('\n').strip() self.grass7Name = line # Second line if the algorithm name in Processing line = lines.readline().strip('\n').strip() self._name = line self._display_name = QCoreApplication.translate( "GrassAlgorithm", line) if " - " not in self._name: self._name = self.grass7Name + " - " + self._name self._display_name = self.grass7Name + " - " + self._display_name self._name = self._name[:self._name.find(' ')].lower() # Read the grass group line = lines.readline().strip('\n').strip() self._group = QCoreApplication.translate("GrassAlgorithm", line) self._groupId = self.groupIdRegex.search(line).group(0).lower() hasRasterOutput = False hasRasterInput = False hasVectorInput = False vectorOutputs = False # Then you have parameters/output definition line = lines.readline().strip('\n').strip() while line != '': try: line = line.strip('\n').strip() if line.startswith('Hardcoded'): self.hardcodedStrings.append(line[len('Hardcoded|'):]) parameter = getParameterFromString(line) if parameter is not None: self.params.append(parameter) if isinstance(parameter, (QgsProcessingParameterVectorLayer, QgsProcessingParameterFeatureSource)): hasVectorInput = True elif isinstance(parameter, QgsProcessingParameterRasterLayer): hasRasterInput = True elif isinstance(parameter, QgsProcessingParameterMultipleLayers): if parameter.layerType( ) < 3 or parameter.layerType() == 5: hasVectorInput = True elif parameter.layerType() == 3: hasRasterInput = True elif isinstance( parameter, QgsProcessingParameterVectorDestination): vectorOutputs = True elif isinstance( parameter, QgsProcessingParameterRasterDestination): hasRasterOutput = True line = lines.readline().strip('\n').strip() except Exception as e: QgsMessageLog.logMessage( self.tr( 'Could not open GRASS GIS 7 algorithm: {0}\n{1}'). format(self.descriptionFile, line), self.tr('Processing'), Qgis.Critical) raise e param = QgsProcessingParameterExtent( self.GRASS_REGION_EXTENT_PARAMETER, self.tr('GRASS GIS 7 region extent'), optional=True) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) if hasRasterOutput or hasRasterInput: # Add a cellsize parameter param = QgsProcessingParameterNumber( self.GRASS_REGION_CELLSIZE_PARAMETER, self.tr('GRASS GIS 7 region cellsize (leave 0 for default)'), type=QgsProcessingParameterNumber.Double, minValue=0.0, maxValue=sys.float_info.max + 1, defaultValue=0.0) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) if hasRasterOutput: # Add a createopt parameter for format export param = QgsProcessingParameterString( self.GRASS_RASTER_FORMAT_OPT, self.tr('Output Rasters format options (createopt)'), multiLine=True, optional=True) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) # Add a metadata parameter for format export param = QgsProcessingParameterString( self.GRASS_RASTER_FORMAT_META, self.tr('Output Rasters format metadata options (metaopt)'), multiLine=True, optional=True) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) if hasVectorInput: param = QgsProcessingParameterNumber( self.GRASS_SNAP_TOLERANCE_PARAMETER, self.tr('v.in.ogr snap tolerance (-1 = no snap)'), type=QgsProcessingParameterNumber.Double, minValue=-1.0, maxValue=sys.float_info.max + 1, defaultValue=-1.0) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) param = QgsProcessingParameterNumber( self.GRASS_MIN_AREA_PARAMETER, self.tr('v.in.ogr min area'), type=QgsProcessingParameterNumber.Double, minValue=0.0, maxValue=sys.float_info.max + 1, defaultValue=0.0001) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param) if vectorOutputs: param = QgsProcessingParameterEnum( self.GRASS_OUTPUT_TYPE_PARAMETER, self.tr('v.out.ogr output type'), self.OUTPUT_TYPES) param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.params.append(param)
def tr(self, string, context=''): if context == '': context = self.__class__.__name__ return QCoreApplication.translate(context, string)
def tr(self, string, context=''): if context == '': context = 'ProcessingConfig' return QCoreApplication.translate(context, string)
def __init__(self): self.name = QCoreApplication.translate("CreateNewScriptAction", "Create New Script…") self.group = self.tr("Tools")
def tr(self, string, context=''): if context == '': context = 'MessageBarProgress' return QCoreApplication.translate(context, string)
def initAlgorithm(self, config=None): class ParameterVrtDestination(QgsProcessingParameterRasterDestination): def __init__(self, name, description): super().__init__(name, description) def clone(self): copy = ParameterVrtDestination(self.name(), self.description()) return copy def type(self): return 'vrt_destination' def defaultFileExtension(self): return 'vrt' self.addParameter( QgsProcessingParameterMultipleLayers( self.INPUT, QCoreApplication.translate("ParameterVrtDestination", 'Input layers'), QgsProcessing.TypeRaster)) self.addParameter( QgsProcessingParameterEnum(self.RESOLUTION, QCoreApplication.translate( "ParameterVrtDestination", 'Resolution'), options=self.RESOLUTION_OPTIONS, defaultValue=0)) self.addParameter( QgsProcessingParameterBoolean( self.SEPARATE, QCoreApplication.translate( "ParameterVrtDestination", 'Place each input file into a separate band'), defaultValue=True)) self.addParameter( QgsProcessingParameterBoolean(self.PROJ_DIFFERENCE, QCoreApplication.translate( "ParameterVrtDestination", 'Allow projection difference'), defaultValue=False)) add_alpha_param = QgsProcessingParameterBoolean( self.ADD_ALPHA, QCoreApplication.translate( "ParameterVrtDestination", 'Add alpha mask band to VRT when source raster has none'), defaultValue=False) add_alpha_param.setFlags( add_alpha_param.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(add_alpha_param) assign_crs = QgsProcessingParameterCrs( self.ASSIGN_CRS, QCoreApplication.translate( "ParameterVrtDestination", 'Override projection for the output file'), defaultValue=None, optional=True) assign_crs.setFlags(assign_crs.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(assign_crs) resampling = QgsProcessingParameterEnum( self.RESAMPLING, QCoreApplication.translate("ParameterVrtDestination", 'Resampling algorithm'), options=self.RESAMPLING_OPTIONS, defaultValue=0) resampling.setFlags(resampling.flags() | QgsProcessingParameterDefinition.FlagAdvanced) self.addParameter(resampling) self.addParameter( ParameterVrtDestination( self.OUTPUT, QCoreApplication.translate("ParameterVrtDestination", 'Virtual')))
def tr(self, string): return QCoreApplication.translate('Processing', string)
def displayName(self): return QCoreApplication.translate("buildvrt", 'Build virtual raster')
__author__ = 'Juergen E. Fischer' __date__ = 'June 2013' __copyright__ = '(C) 2013, Juergen E. Fischer' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '787f7c50423eba59a3aeda934de638caea9cb97a' from qgis.PyQt.QtCore import QCoreApplication, QSettings def chunks(l, n): for i in xrange(0, len(l), n): yield l[i:i + n] QCoreApplication.setOrganizationName("QGIS") QCoreApplication.setOrganizationDomain("qgis.org") QCoreApplication.setApplicationName("QGIS3") s = QSettings() ba = s.value("/UI/geometry").toByteArray() f = open("src/app/ui_defaults.h", "w") f.write( "#ifndef UI_DEFAULTS_H\n#define UI_DEFAULTS_H\n\nstatic const unsigned char defaultUIgeometry[] =\n{\n" ) for chunk in chunks(ba, 16): f.write(" %s,\n" % ", ".join(map(lambda x: "0x%02x" % ord(x), chunk)))
def __init__(self): self.name = QCoreApplication.translate('OpenModelFromFileAction', 'Open Existing Model…') self.group = self.tr('Tools')
def group(self): return QCoreApplication.translate("buildvrt", 'Raster miscellaneous')
def appendfile(layer): with open(filename, 'a') as f: f.write('3,tiger\n') # print "Appended to file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
class DestinationSelectionPanel(BASE, WIDGET): SAVE_TO_TEMP_FILE = QCoreApplication.translate( 'DestinationSelectionPanel', '[Save to temporary file]') SAVE_TO_TEMP_FOLDER = QCoreApplication.translate( 'DestinationSelectionPanel', '[Save to temporary folder]') SAVE_TO_TEMP_LAYER = QCoreApplication.translate( 'DestinationSelectionPanel', '[Create temporary layer]') SKIP_OUTPUT = QCoreApplication.translate( 'DestinationSelectionPanel', '[Skip output]') skipOutputChanged = pyqtSignal(bool) destinationChanged = pyqtSignal() def __init__(self, parameter, alg, default_selection=False): super(DestinationSelectionPanel, self).__init__(None) self.setupUi(self) self.parameter = parameter self.alg = alg self.default_selection = default_selection settings = QgsSettings() self.encoding = settings.value('/Processing/encoding', 'System') self.use_temporary = True self.setValue(self.parameter.defaultValue()) self.btnSelect.clicked.connect(self.selectOutput) self.leText.textEdited.connect(self.textChanged) def textChanged(self): self.use_temporary = not self.leText.text() self.destinationChanged.emit() def outputIsSkipped(self): """ Returns true if output is set to be skipped """ return not self.leText.text() and not self.use_temporary def skipOutput(self): self.leText.setPlaceholderText(self.SKIP_OUTPUT) self.leText.setText('') self.use_temporary = False self.skipOutputChanged.emit(True) self.destinationChanged.emit() 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 saveToTemporary(self): if isinstance(self.parameter, QgsProcessingParameterFeatureSink) and self.parameter.supportsNonFileBasedOutput(): self.leText.setPlaceholderText(self.SAVE_TO_TEMP_LAYER) elif isinstance(self.parameter, QgsProcessingParameterFolderDestination): self.leText.setPlaceholderText(self.SAVE_TO_TEMP_FOLDER) else: self.leText.setPlaceholderText(self.SAVE_TO_TEMP_FILE) self.leText.setText('') self.use_temporary = True self.skipOutputChanged.emit(False) self.destinationChanged.emit() def saveToPostGIS(self): dlg = PostgisTableSelector(self, self.parameter.name().lower()) dlg.exec_() if dlg.connection: self.use_temporary = False settings = QgsSettings() mySettings = '/PostgreSQL/connections/' + dlg.connection dbname = settings.value(mySettings + '/database') user = settings.value(mySettings + '/username') host = settings.value(mySettings + '/host') port = settings.value(mySettings + '/port') password = settings.value(mySettings + '/password') uri = QgsDataSourceUri() uri.setConnection(host, str(port), dbname, user, password) uri.setDataSource(dlg.schema, dlg.table, "the_geom" if isinstance(self.parameter, QgsProcessingParameterFeatureSink) and self.parameter.hasGeometry() else None) connInfo = uri.connectionInfo() (success, user, passwd) = QgsCredentials.instance().get(connInfo, None, None) if success: QgsCredentials.instance().put(connInfo, user, passwd) self.leText.setText("postgis:" + uri.uri()) self.skipOutputChanged.emit(False) self.destinationChanged.emit() def saveToGeopackage(self): file_filter = self.tr('GeoPackage files (*.gpkg);;All files (*.*)', 'OutputFile') settings = QgsSettings() if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) filename, filter = QFileDialog.getSaveFileName(self, self.tr("Save to GeoPackage"), path, file_filter, options=QFileDialog.DontConfirmOverwrite) if not filename: return layer_name, ok = QInputDialog.getText(self, self.tr('Save to GeoPackage'), self.tr('Layer name'), text=self.parameter.name().lower()) if ok: self.use_temporary = False if not filename.lower().endswith('.gpkg'): filename += '.gpkg' settings.setValue('/Processing/LastOutputPath', os.path.dirname(filename)) uri = QgsDataSourceUri() uri.setDatabase(filename) uri.setDataSource('', layer_name, 'geom' if isinstance(self.parameter, QgsProcessingParameterFeatureSink) and self.parameter.hasGeometry() else None) self.leText.setText("ogr:" + uri.uri()) self.skipOutputChanged.emit(False) self.destinationChanged.emit() def selectFile(self): file_filter = getFileFilter(self.parameter) settings = QgsSettings() if isinstance(self.parameter, QgsProcessingParameterFeatureSink): last_ext_path = '/Processing/LastVectorOutputExt' last_ext = settings.value(last_ext_path, '.gpkg') elif isinstance(self.parameter, QgsProcessingParameterRasterDestination): last_ext_path = '/Processing/LastRasterOutputExt' last_ext = settings.value(last_ext_path, '.tif') else: last_ext_path = None last_ext = None # get default filter filters = file_filter.split(';;') try: last_filter = [f for f in filters if '*{}'.format(last_ext) in f.lower()][0] except: last_filter = None if settings.contains('/Processing/LastOutputPath'): path = settings.value('/Processing/LastOutputPath') else: path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER) filename, filter = QFileDialog.getSaveFileName(self, self.tr("Save file"), path, file_filter, last_filter) if filename: self.use_temporary = False if not filename.lower().endswith( tuple(re.findall("\\*(\\.[a-z]{1,10})", file_filter))): ext = re.search("\\*(\\.[a-z]{1,10})", filter) if ext: filename += ext.group(1) self.leText.setText(filename) settings.setValue('/Processing/LastOutputPath', os.path.dirname(filename)) if not last_ext_path is None: settings.setValue(last_ext_path, os.path.splitext(filename)[1].lower()) self.skipOutputChanged.emit(False) self.destinationChanged.emit() def selectEncoding(self): dialog = QgsEncodingSelectionDialog( self, self.tr('File encoding'), self.encoding) if dialog.exec_() == QDialog.Accepted: self.encoding = dialog.encoding() settings = QgsSettings() settings.setValue('/Processing/encoding', self.encoding) self.destinationChanged.emit() dialog.deleteLater() def selectDirectory(self): lastDir = self.leText.text() settings = QgsSettings() if not lastDir: lastDir = settings.value("/Processing/LastOutputPath", QDir.homePath()) dirName = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.leText.setText(QDir.toNativeSeparators(dirName)) settings.setValue('/Processing/LastOutputPath', dirName) self.use_temporary = False self.skipOutputChanged.emit(False) self.destinationChanged.emit() def setValue(self, value): if not value: if self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional and \ not self.parameter.createByDefault(): self.skipOutput() else: self.saveToTemporary() else: if value == 'memory:': self.saveToTemporary() elif isinstance(value, QgsProcessingOutputLayerDefinition): if value.sink.staticValue() in ('memory:', ''): self.saveToTemporary() else: self.leText.setText(value.sink.staticValue()) self.use_temporary = False self.skipOutputChanged.emit(False) self.destinationChanged.emit() self.encoding = value.createOptions['fileEncoding'] else: self.leText.setText(value) self.use_temporary = False self.skipOutputChanged.emit(False) self.destinationChanged.emit() def getValue(self): key = None if self.use_temporary and isinstance(self.parameter, QgsProcessingParameterFeatureSink): key = 'memory:' elif self.use_temporary and not self.default_selection: key = self.parameter.generateTemporaryDestination() else: key = self.leText.text() if not key and self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional: return None if isinstance(self.parameter, QgsProcessingParameterFolderDestination): return key if isinstance(self.parameter, QgsProcessingParameterFileDestination): return key value = QgsProcessingOutputLayerDefinition(key) value.createOptions = {'fileEncoding': self.encoding} return value
def processAlgorithm(self, parameters, context, feedback): network = self.parameterAsSource(parameters, self.INPUT, context) if network is None: raise QgsProcessingException( self.invalidSourceError(parameters, self.INPUT)) startPoint = self.parameterAsPoint(parameters, self.START_POINT, context, network.sourceCrs()) strategy = self.parameterAsEnum(parameters, self.STRATEGY, context) travelCost = self.parameterAsDouble(parameters, self.TRAVEL_COST, context) directionFieldName = self.parameterAsString(parameters, self.DIRECTION_FIELD, context) forwardValue = self.parameterAsString(parameters, self.VALUE_FORWARD, context) backwardValue = self.parameterAsString(parameters, self.VALUE_BACKWARD, context) bothValue = self.parameterAsString(parameters, self.VALUE_BOTH, context) defaultDirection = self.parameterAsEnum(parameters, self.DEFAULT_DIRECTION, context) speedFieldName = self.parameterAsString(parameters, self.SPEED_FIELD, context) defaultSpeed = self.parameterAsDouble(parameters, self.DEFAULT_SPEED, context) tolerance = self.parameterAsDouble(parameters, self.TOLERANCE, context) include_bounds = True # default to true to maintain 3.0 API if self.INCLUDE_BOUNDS in parameters: include_bounds = self.parameterAsBool(parameters, self.INCLUDE_BOUNDS, context) directionField = -1 if directionFieldName: directionField = network.fields().lookupField(directionFieldName) speedField = -1 if speedFieldName: speedField = network.fields().lookupField(speedFieldName) director = QgsVectorLayerDirector(network, directionField, forwardValue, backwardValue, bothValue, defaultDirection) distUnit = context.project().crs().mapUnits() multiplier = QgsUnitTypes.fromUnitToUnitFactor( distUnit, QgsUnitTypes.DistanceMeters) if strategy == 0: strategy = QgsNetworkDistanceStrategy() else: strategy = QgsNetworkSpeedStrategy(speedField, defaultSpeed, multiplier * 1000.0 / 3600.0) director.addStrategy(strategy) builder = QgsGraphBuilder(network.sourceCrs(), True, tolerance) feedback.pushInfo( QCoreApplication.translate('ServiceAreaFromPoint', 'Building graph…')) snappedPoints = director.makeGraph(builder, [startPoint], feedback) feedback.pushInfo( QCoreApplication.translate('ServiceAreaFromPoint', 'Calculating service area…')) graph = builder.graph() idxStart = graph.findVertex(snappedPoints[0]) tree, cost = QgsGraphAnalyzer.dijkstra(graph, idxStart, 0) vertices = set() points = [] lines = [] for vertex, start_vertex_cost in enumerate(cost): inbound_edge_index = tree[vertex] if inbound_edge_index == -1 and vertex != idxStart: # unreachable vertex continue if start_vertex_cost > travelCost: # vertex is too expensive, discard continue vertices.add(vertex) start_point = graph.vertex(vertex).point() # find all edges coming from this vertex for edge_id in graph.vertex(vertex).outgoingEdges(): edge = graph.edge(edge_id) end_vertex_cost = start_vertex_cost + edge.cost(0) end_point = graph.vertex(edge.toVertex()).point() if end_vertex_cost <= travelCost: # end vertex is cheap enough to include vertices.add(edge.toVertex()) lines.append([start_point, end_point]) else: # travelCost sits somewhere on this edge, interpolate position interpolated_end_point = QgsGeometryUtils.interpolatePointOnLineByValue( start_point.x(), start_point.y(), start_vertex_cost, end_point.x(), end_point.y(), end_vertex_cost, travelCost) points.append(interpolated_end_point) lines.append([start_point, interpolated_end_point]) for i in vertices: points.append(graph.vertex(i).point()) feedback.pushInfo( QCoreApplication.translate('ServiceAreaFromPoint', 'Writing results…')) fields = QgsFields() fields.append(QgsField('type', QVariant.String, '', 254, 0)) fields.append(QgsField('start', QVariant.String, '', 254, 0)) feat = QgsFeature() feat.setFields(fields) (point_sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context, fields, QgsWkbTypes.MultiPoint, network.sourceCrs()) results = {} if point_sink is not None: results[self.OUTPUT] = dest_id geomPoints = QgsGeometry.fromMultiPointXY(points) feat.setGeometry(geomPoints) feat['type'] = 'within' feat['start'] = startPoint.toString() point_sink.addFeature(feat, QgsFeatureSink.FastInsert) if include_bounds: upperBoundary = [] lowerBoundary = [] vertices = [] for i, v in enumerate(cost): if v > travelCost and tree[i] != -1: vertexId = graph.edge(tree[i]).fromVertex() if cost[vertexId] <= travelCost: vertices.append(i) for i in vertices: upperBoundary.append( graph.vertex(graph.edge(tree[i]).toVertex()).point()) lowerBoundary.append( graph.vertex(graph.edge(tree[i]).fromVertex()).point()) geomUpper = QgsGeometry.fromMultiPointXY(upperBoundary) geomLower = QgsGeometry.fromMultiPointXY(lowerBoundary) feat.setGeometry(geomUpper) feat['type'] = 'upper' feat['start'] = startPoint.toString() point_sink.addFeature(feat, QgsFeatureSink.FastInsert) feat.setGeometry(geomLower) feat['type'] = 'lower' feat['start'] = startPoint.toString() point_sink.addFeature(feat, QgsFeatureSink.FastInsert) (line_sink, line_dest_id) = self.parameterAsSink(parameters, self.OUTPUT_LINES, context, fields, QgsWkbTypes.MultiLineString, network.sourceCrs()) if line_sink is not None: results[self.OUTPUT_LINES] = line_dest_id geom_lines = QgsGeometry.fromMultiPolylineXY(lines) feat.setGeometry(geom_lines) feat['type'] = 'lines' feat['start'] = startPoint.toString() line_sink.addFeature(feat, QgsFeatureSink.FastInsert) return results
def rewritefile(layer): with open(filename, 'w') as f: f.write("name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n") # print "Rewritten file - sleeping" time.sleep(1) QCoreApplication.instance().processEvents()
def __init__(self): self.name = QCoreApplication.translate("EditScriptAction", "Edit Script…")
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QgsSettings() 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() icon_size = iface.iconSize(dockedToolbar=True) if iface else QSize(16, 16) 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 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/mIconRunConsole.svg")) 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(icon_size) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) 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(icon_size) 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) 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.toolBarFindText = QToolBar() self.toolBarFindText.setIconSize(icon_size) self.findNextButton = QAction(self) self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchNextEditorConsole.png")) self.findPrevButton = QAction(self) self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchPrevEditorConsole.png")) 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.toolBarFindText.addWidget(self.lineEditFind) self.toolBarFindText.addAction(self.findPrevButton) self.toolBarFindText.addAction(self.findNextButton) self.toolBarFindText.addWidget(self.caseSensitive) self.toolBarFindText.addWidget(self.wholeWord) self.toolBarFindText.addWidget(self.wrapAround) self.layoutFind.addWidget(self.toolBarFindText, 0, 1, 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.triggered.connect(self._findNext) self.findPrevButton.triggered.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 setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain(cls.__name__) QCoreApplication.setApplicationName(cls.__name__) start_app()
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', 'cocotrainer_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&cocotrainer') # Check if plugin was started the first time in current QGIS session # Must be set in initGui() to survive plugin reloads self.first_start = None self.license_dict = { "MIT license": { "url": "https://opensource.org/licenses/MIT", "id": 0, "name": "The MIT License" }, "GNU GPL 3": { "url": "https://www.gnu.org/licenses/gpl-3.0.en.html", "id": 1, "name": "GNU General Public License version 3" }, "GNU GPL 2": { "url": "https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html", "id": 2, "name": "GNU General Public License version 2" }, "BSD 3": { "url": "https://opensource.org/licenses/BSD-3-Clause", "id": 3, "name": "The 3-Clause BSD License" }, "BSD 2": { "url": "https://opensource.org/licenses/BSD-2-Clause", "id": 4, "name": "The 2-Clause BSD License" }, "Apache 2.0": { "url": "http://www.apache.org/licenses/", "id": 5, "name": "Apache License, Version 2.0" }, "MPL 2.0": { "url": "https://www.mozilla.org/en-US/MPL/2.0/FAQ/", "id": 6, "name": "Mozilla Public License 2.0" }, "Creative Commons 1.0": { "url": "http://creativecommons.org/licenses/by-nc-sa/2.0/", "id": 7, "name": "Attribution-NonCommercial-ShareAlike License" } }
def initGui(self): self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction(self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction(self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', 'Graphical &Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction(self.modelerAction, QKeySequence('Ctrl+Alt+M').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QgsApplication.getThemeIcon("/mIconHistory.svg"), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction(self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction(self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect(self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.toolbox.processingToolbar.addSeparator() self.editInPlaceAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Features In-Place'), self.iface.mainWindow()) self.editInPlaceAction.setObjectName('editInPlaceFeatures') self.editInPlaceAction.setCheckable(True) self.editInPlaceAction.toggled.connect(self.editSelected) self.toolbox.processingToolbar.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addSeparator() self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() # In-place editing button state sync self.iface.currentLayerChanged.connect(self.sync_in_place_button_state) self.iface.mapCanvas().selectionChanged.connect(self.sync_in_place_button_state) self.iface.actionToggleEditing().triggered.connect(partial(self.sync_in_place_button_state, None)) self.sync_in_place_button_state()
def tr(self, string): return QCoreApplication.translate("SAGAAlgorithm", string)
def tr(string): return QCoreApplication.translate('Help2Html', string)
def tr(self, message): return QCoreApplication.translate('ProcessingPlugin', message)
def _translate(context, text, disambig): return QCoreApplication.translate(context, text, disambig)
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]