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 installAllFromRepository(): """Install Boundless plugins from remote repository """ installer = pyplugin_installer.instance() initPluginManager(installer) errors = [] pluginsList = plugins.all().copy() for plugin in pluginsList: if isBoundlessPlugin(pluginsList[plugin]): if (pluginsList[plugin]['installed'] and pluginsList[plugin]['deprecated']) or \ not pluginsList[plugin]['deprecated'] and \ pluginsList[plugin]["zip_repository"] != '': dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugins.all()[plugin]) dlg.exec_() if dlg.result(): errors.append(dlg.result()) else: updateAvailablePlugins() loadPlugin(plugins.all()[plugin]['id']) plugins.getAllInstalled(testLoad=True) plugins.rebuild() if not plugins.all()[plugin]["error"]: if startPlugin(plugins.all()[plugin]['id']): settings = QSettings() settings.setValue('/PythonPlugins/' + plugins.all()[plugin]['id'], True) installer.exportPluginsToManager() return errors
def __init__(self, alg, model, algName=None, configuration=None): QDialog.__init__(self) self.setModal(True) self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.context = createContext() self.widget_labels = {} class ContextGenerator(QgsProcessingContextGenerator): def __init__(self, context): super().__init__() self.processing_context = context def processingContext(self): return self.processing_context self.context_generator = ContextGenerator(self.context) self.setupUi() self.params = None settings = QgsSettings() self.restoreGeometry(settings.value("/Processing/modelParametersDialogGeometry", QByteArray()))
def getVectorWriter(self, fields, geomType, crs, context): """Returns a suitable writer to which features can be added as a result of the algorithm. Use this to transparently handle output values instead of creating your own method. Executing this method might modify the object, adding additional information to it, so the writer can be later accessed and processed within QGIS. It should be called just once, since a new call might result in previous data being replaced, thus rendering a previously obtained writer useless. @param fields a list of QgsField @param geomType a suitable geometry type, as it would be passed to a QgsVectorFileWriter constructor @param crs the crs of the layer to create @return writer instance of the vector writer class :param context: """ if self.encoding is None: settings = QgsSettings() self.encoding = settings.value('/Processing/encoding', 'System', str) w, w_dest = QgsProcessingUtils.createFeatureSink(self.value, context, fields, geomType, crs, {'fileEncoding': self.encoding}) self.value = w_dest return w
def execute(self): settings = QgsSettings() lastDir = settings.value('Processing/lastModelsDir', '') filename, selected_filter = QFileDialog.getOpenFileName(self.toolbox, self.tr('Open model', 'AddModelFromFileAction'), lastDir, self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction')) if filename: try: settings.setValue('Processing/lastModelsDir', QFileInfo(filename).absoluteDir().absolutePath()) ModelerAlgorithm.fromFile(filename) except WrongModelException: QMessageBox.warning( self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction')) return except: QMessageBox.warning(self.toolbox, self.tr('Error reading model', 'AddModelFromFileAction'), self.tr('Cannot read file', 'AddModelFromFileAction')) return destFilename = os.path.join(ModelerUtils.modelsFolders()[0], os.path.basename(filename)) shutil.copyfile(filename, destFilename) QgsApplication.processingRegistry().providerById('model').refreshAlgorithms()
def markNews(self): settings = QSettings() seenPlugins = settings.value(seenPluginGroup, list(self.plugins.keys()), str) if len(seenPlugins) > 0: for i in list(self.plugins.keys()): if seenPlugins.count(i) == 0 and self.plugins[i]['status'] == 'not installed': self.plugins[i]['status'] = 'new'
def main(): datestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if QT5: ini_out_dir = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation) else: ini_out_dir = QDesktopServices.storageLocation(QDesktopServices.DesktopLocation) ini_name = 'org.qgis.{0}-settings_{1}.ini'.format(QGIS_APP_NAME, datestamp) ini_out = QDir(ini_out_dir).absoluteFilePath(ini_name) if not os.path.exists(ini_out_dir): print('INI output directory does not exist: {0}'.format(ini_out_dir)) return if not os.access(ini_out_dir, os.W_OK | os.X_OK): print('INI output directory is not writeable: {0}'.format(ini_out_dir)) return # QGIS settings if HAS_QGSSETTINGS: qgis_settings = QgsSettings() else: qgis_settings = QSettings() # Output INI settings ini_settings = QSettings(ini_out, QSettings.IniFormat) qgis_keys = qgis_settings.allKeys() for k in qgis_keys: ini_settings.setValue(k, qgis_settings.value(k)) ini_settings.sync() print("Settings output to: {0}".format(QDir.toNativeSeparators(ini_out)))
def updateSeenPluginsList(self): settings = QSettings() seenPlugins = settings.value(seenPluginGroup, list(self.plugins.keys()), str) for i in list(self.plugins.keys()): if seenPlugins.count(i) == 0: seenPlugins += [i] settings.setValue(seenPluginGroup, seenPlugins)
def execute(self): settings = QgsSettings() lastDir = settings.value('Processing/lastScriptsDir', '') filenames, selected_filter = QFileDialog.getOpenFileNames(self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'), lastDir, self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction')) if filenames: validAlgs = 0 wrongAlgs = [] for filename in filenames: try: settings.setValue('Processing/lastScriptsDir', QFileInfo(filename).absoluteDir().absolutePath()) script = ScriptAlgorithm(filename) destFilename = os.path.join(ScriptUtils.scriptsFolders()[0], os.path.basename(filename)) with open(destFilename, 'w') as f: f.write(script.script) validAlgs += 1 except WrongScriptException: wrongAlgs.append(os.path.basename(filename)) if validAlgs: QgsApplication.processingRegistry().providerById('script').refreshAlgorithms() if wrongAlgs: QMessageBox.warning(self.toolbox, self.tr('Error reading scripts', 'AddScriptFromFileAction'), self.tr('The following files do not contain a valid script:\n-', 'AddScriptFromFileAction') + "\n-".join(wrongAlgs))
def showFileSelectionDialog(self): settings = QgsSettings() text = str(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = str(settings.value('/Processing/LastInputPath')) else: path = '' ret, selected_filter = QFileDialog.getOpenFileNames(self, self.tr('Select Files'), path, getFileFilter(self.param)) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) self.textEditingFinished() else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(str(f) for f in files)) else: rowdif = len(files) - (self._table().rowCount() - self.row) for i in range(rowdif): self._panel().addRow() for i, f in enumerate(files): self._table().cellWidget(i + self.row, self.col).setValue(f)
def createContext(): """ Creates a default processing context """ context = QgsProcessingContext() context.setProject(QgsProject.instance()) invalid_features_method = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES) if invalid_features_method is None: invalid_features_method = QgsFeatureRequest.GeometryAbortOnInvalid context.setInvalidGeometryCheck(invalid_features_method) def raise_error(f): raise GeoAlgorithmExecutionException(QCoreApplication.translate("FeatureIterator", 'Features with invalid geometries found. Please fix these geometries or specify the "Ignore invalid input features" flag')) context.setInvalidGeometryCallback(raise_error) def raise_transform_error(f): raise GeoAlgorithmExecutionException(QCoreApplication.translate("FeatureIterator", 'Encountered a transform error when reprojecting feature with id {}.'.format(f.id()))) context.setTransformErrorCallback(raise_transform_error) settings = QgsSettings() context.setDefaultEncoding(settings.value("/Processing/encoding", "System")) return context
def save(self, qsettings=None): if not qsettings: qsettings = QgsSettings() if self.valuetype == self.SELECTION: qsettings.setValue(self.qname, self.options.index(self.value)) else: qsettings.setValue(self.qname, self.value)
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 loadShortHelp(): h = {} path = os.path.dirname(__file__) for f in os.listdir(path): if f.endswith("yaml"): filename = os.path.join(path, f) with codecs.open(filename, encoding='utf-8') as stream: with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=DeprecationWarning) for k, v in yaml.load(stream, Loader=yaml.SafeLoader).items(): if v is None: continue h[k] = QCoreApplication.translate("{}Algorithm".format(f[:-5].upper()), v) version = ".".join(Qgis.QGIS_VERSION.split(".")[0:2]) overrideLocale = QgsSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QgsSettings().value('locale/userLocale', '') locale = locale.split("_")[0] def replace(s): if s is not None: return s.replace("{qgisdocs}", "https://docs.qgis.org/%s/%s/docs" % (version, locale)) else: return None h = {k: replace(v) for k, v in list(h.items())} return h
def reject(self): self.param = None settings = QgsSettings() settings.setValue("/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.reject(self)
def upgradeInstalledPlugins(): installer = pyplugin_installer.instance() initPluginManager(installer) errors = [] pluginsList = plugins.all().copy() for plugin in pluginsList: if isBoundlessPlugin(pluginsList[plugin]): if pluginsList[plugin]['installed'] and pluginsList[plugin]['status'] == 'upgradeable': dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugins.all()[plugin]) dlg.exec_() if dlg.result(): errors.append(dlg.result()) else: updateAvailablePlugins() loadPlugin(plugins.all()[plugin]['id']) plugins.getAllInstalled(testLoad=True) plugins.rebuild() if not plugins.all()[plugin]["error"]: if startPlugin(plugins.all()[plugin]['id']): settings = QSettings() settings.setValue('/PythonPlugins/' + plugins.all()[plugin]['id'], True) installer.exportPluginsToManager() return errors
def chooseOutputFile(self): # get last used dir settings = QgsSettings() lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".") # get selected filter selectedFilter = self.cboFileFormat.currentData() # ask for a filename filename, filter = QFileDialog.getSaveFileName(self, self.tr("Choose where to save the file"), lastUsedDir, selectedFilter) if filename == "": return filterString = QgsVectorFileWriter.filterForDriver(selectedFilter) ext = filterString[filterString.find('.'):] ext = ext[:ext.find(' ')] if not filename.lower().endswith(ext): filename += ext # store the last used dir settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath()) self.editOutputFile.setText(filename)
def createContext(feedback=None): """ Creates a default processing context :param feedback: Optional existing QgsProcessingFeedback object, or None to use a default feedback object :type feedback: Optional[QgsProcessingFeedback] :returns: New QgsProcessingContext object :rtype: QgsProcessingContext """ context = QgsProcessingContext() context.setProject(QgsProject.instance()) context.setFeedback(feedback) invalid_features_method = ProcessingConfig.getSetting(ProcessingConfig.FILTER_INVALID_GEOMETRIES) if invalid_features_method is None: invalid_features_method = QgsFeatureRequest.GeometryAbortOnInvalid context.setInvalidGeometryCheck(invalid_features_method) settings = QgsSettings() context.setDefaultEncoding(settings.value("/Processing/encoding", "System")) context.setExpressionContext(createExpressionContext()) return context
def loadAPIFile(self): settings = QgsSettings() lastDirPath = settings.value("pythonConsole/lastDirAPIPath", "", type=str) fileAPI, selected_filter = QFileDialog.getOpenFileName( self, "Open API File", lastDirPath, "API file (*.api)") if fileAPI: self.addAPI(fileAPI) settings.setValue("pythonConsole/lastDirAPIPath", fileAPI)
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) dialog.deleteLater()
def markNews(self): """ mark all new plugins as new """ settings = QgsSettings() seenPlugins = settings.value(settingsGroup + '/seen_plugins', list(self.mPlugins.keys()), type=str) if len(seenPlugins) > 0: for i in list(self.mPlugins.keys()): if seenPlugins.count(i) == 0 and self.mPlugins[i]["status"] == "not installed": self.mPlugins[i]["status"] = "new"
def updateSeenPluginsList(self): """ update the list of all seen plugins """ settings = QgsSettings() seenPlugins = settings.value(settingsGroup + '/seen_plugins', list(self.mPlugins.keys()), type=str) for i in list(self.mPlugins.keys()): if seenPlugins.count(i) == 0: seenPlugins += [i] settings.setValue(settingsGroup + '/seen_plugins', seenPlugins)
def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi() settings = QgsSettings() self.restoreGeometry(settings.value("/Processing/modelParametersDefinitionDialogGeometry", QByteArray()))
def setUp(self): self.cnt += 1 h, path = tempfile.mkstemp('.ini') Path(path).touch() assert QgsSettings.setGlobalSettingsPath(path) self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt) self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) self.globalsettings.sync() assert os.path.exists(self.globalsettings.fileName())
def zoomIn(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel()
def uri_from_name(conn_name): settings = QgsSettings() settings.beginGroup(u"/PostgreSQL/connections/%s" % conn_name) if not settings.contains("database"): # non-existent entry? raise QgsProcessingException(QCoreApplication.translate("PostGIS", 'There is no defined database connection "{0}".').format(conn_name)) uri = QgsDataSourceUri() settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"] service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList] useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) try: sslmode = settings.value("sslmode", QgsDataSourceUri.SslPrefer, type=int) except TypeError: sslmode = QgsDataSourceUri.SslPrefer settings.endGroup() if hasattr(authcfg, 'isNull') and authcfg.isNull(): authcfg = '' if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: uri.setConnection(host, port, database, username, password, sslmode, authcfg) uri.setUseEstimatedMetadata(useEstimatedMetadata) return uri
def runGdal(commands, feedback=None): if feedback is None: feedback = QgsProcessingFeedback() envval = os.getenv('PATH') # We need to give some extra hints to get things picked up on OS X isDarwin = False try: isDarwin = platform.system() == 'Darwin' except IOError: # https://travis-ci.org/m-kuhn/QGIS#L1493-L1526 pass if isDarwin and os.path.isfile(os.path.join(QgsApplication.prefixPath(), "bin", "gdalinfo")): # Looks like there's a bundled gdal. Let's use it. os.environ['PATH'] = "{}{}{}".format(os.path.join(QgsApplication.prefixPath(), "bin"), os.pathsep, envval) os.environ['DYLD_LIBRARY_PATH'] = os.path.join(QgsApplication.prefixPath(), "lib") else: # Other platforms should use default gdal finder codepath settings = QgsSettings() path = settings.value('/GdalTools/gdalPath', '') if not path.lower() in envval.lower().split(os.pathsep): envval += '{}{}'.format(os.pathsep, path) os.putenv('PATH', envval) fused_command = ' '.join([str(c) for c in commands]) QgsMessageLog.logMessage(fused_command, 'Processing', Qgis.Info) feedback.pushInfo('GDAL command:') feedback.pushCommandInfo(fused_command) feedback.pushInfo('GDAL command output:') success = False retry_count = 0 while not success: loglines = [] loglines.append('GDAL execution console output') try: with subprocess.Popen( fused_command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ) as proc: for line in proc.stdout: feedback.pushConsoleInfo(line) loglines.append(line) success = True except IOError as e: if retry_count < 5: retry_count += 1 else: raise IOError( str(e) + u'\nTried 5 times without success. Last iteration stopped after reading {} line(s).\nLast line(s):\n{}'.format( len(loglines), u'\n'.join(loglines[-10:]))) QgsMessageLog.logMessage('\n'.join(loglines), 'Processing', Qgis.Info) GdalUtils.consoleOutput = loglines
def connect(self, parent=None): conn_name = self.connectionName() settings = QgsSettings() settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name)) if not settings.contains("database"): # non-existent entry? raise InvalidDataException(self.tr('There is no defined database connection "{0}".').format(conn_name)) from qgis.core import QgsDataSourceUri uri = QgsDataSourceUri() settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"] service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList] useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool) sslmode = settings.value("sslmode", QgsDataSourceUri.SslPrefer, type=int) settings.endGroup() if hasattr(authcfg, 'isNull') and authcfg.isNull(): authcfg = '' if service: uri.setConnection(service, database, username, password, sslmode, authcfg) else: uri.setConnection(host, port, database, username, password, sslmode, authcfg) uri.setUseEstimatedMetadata(useEstimatedMetadata) try: return self.connectToUri(uri) except ConnectionError: return False
def closeEvent(self, e): self.unregisterAllActions() # clear preview, this will delete the layer in preview tab self.preview.loadPreview(None) # save the window state settings = QgsSettings() settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState()) settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry()) QMainWindow.closeEvent(self, e)
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)
def checkingOnStart(self): """ return true if checking for news and updates is enabled """ settings = QgsSettings() return settings.value(settingsGroup + "/checkOnStart", False, type=bool)
class TestQgsSettings(unittest.TestCase): cnt = 0 def setUp(self): self.cnt += 1 h, path = tempfile.mkstemp('.ini') assert QgsSettings.setGlobalSettingsPath(path) self.settings = QgsSettings('testqgissettings', 'testqgissettings%s' % self.cnt) self.globalsettings = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) def tearDown(self): settings_file = self.settings.fileName() settings_default_file = self.settings.globalSettingsPath() del (self.settings) try: os.unlink(settings_file) except: pass try: os.unlink(settings_default_file) except: pass def addToDefaults(self, key, value): self.globalsettings.setValue(key, value) self.globalsettings.sync() def addArrayToDefaults(self, prefix, key, values): defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) # NOQA self.globalsettings.beginWriteArray(prefix) i = 0 for v in values: self.globalsettings.setArrayIndex(i) self.globalsettings.setValue(key, v) i += 1 self.globalsettings.endArray() self.globalsettings.sync() def addGroupToDefaults(self, prefix, kvp): defaults = QSettings(self.settings.globalSettingsPath(), QSettings.IniFormat) # NOQA self.globalsettings.beginGroup(prefix) for k, v in kvp.items(): self.globalsettings.setValue(k, v) self.globalsettings.endGroup() self.globalsettings.sync() def test_basic_functionality(self): self.assertEqual( self.settings.value('testqgissettings/doesnotexists', 'notexist'), 'notexist') self.settings.setValue('testqgissettings/name', 'qgisrocks') self.settings.sync() self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks') def test_defaults(self): self.assertIsNone(self.settings.value('testqgissettings/name')) self.addToDefaults('testqgissettings/name', 'qgisrocks') self.assertEqual(self.settings.value('testqgissettings/name'), 'qgisrocks') def test_allkeys(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/name', 'qgisrocks') self.addToDefaults('testqgissettings/name2', 'qgisrocks2') self.settings.setValue('nepoti/eman', 'osaple') self.assertEqual(3, len(self.settings.allKeys())) self.assertIn('testqgissettings/name', self.settings.allKeys()) self.assertIn('nepoti/eman', self.settings.allKeys()) self.assertEqual('qgisrocks', self.settings.value('testqgissettings/name')) self.assertEqual('qgisrocks2', self.settings.value('testqgissettings/name2')) self.assertEqual('qgisrocks', self.globalsettings.value('testqgissettings/name')) self.assertEqual('osaple', self.settings.value('nepoti/eman')) self.assertEqual(3, len(self.settings.allKeys())) self.assertEqual(2, len(self.globalsettings.allKeys())) def test_precedence_simple(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1') self.settings.setValue('testqgissettings/names/name1', 'qgisrocks-1') self.assertEqual(self.settings.value('testqgissettings/names/name1'), 'qgisrocks-1') def test_precedence_group(self): """Test if user can override a group value""" self.assertEqual(self.settings.allKeys(), []) self.addGroupToDefaults( 'connections-xyz', { 'OSM': 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png', 'OSM-b': 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png', }) self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override edit self.settings.beginGroup('connections-xyz') self.settings.setValue( 'OSM', 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://c.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: the global value will be resumed!!! self.settings.beginGroup('connections-xyz') self.settings.remove('OSM') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: store a blank! self.settings.beginGroup('connections-xyz') self.settings.setValue('OSM', '') self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), '') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() # Override remove: store a None: will resume the global setting! self.settings.beginGroup('connections-xyz') self.settings.setValue('OSM', None) self.settings.endGroup() # Check it again! self.settings.beginGroup('connections-xyz') self.assertEqual(self.settings.value('OSM'), 'http://a.tile.openstreetmap.org/{z}/{x}/{y}.png') self.assertEqual(self.settings.value('OSM-b'), 'http://b.tile.openstreetmap.org/{z}/{x}/{y}.png') self.settings.endGroup() def test_uft8(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/namèé↓1', 'qgisrocks↓1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓1') self.settings.setValue('testqgissettings/names/namèé↓2', 'qgisrocks↓2') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓2'), 'qgisrocks↓2') self.settings.setValue('testqgissettings/names/namèé↓1', 'qgisrocks↓-1') self.assertEqual(self.settings.value('testqgissettings/names/namèé↓1'), 'qgisrocks↓-1') def test_groups(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/names/name1', 'qgisrocks1') self.addToDefaults('testqgissettings/names/name2', 'qgisrocks2') self.addToDefaults('testqgissettings/names/name3', 'qgisrocks3') self.addToDefaults('testqgissettings/name', 'qgisrocks') self.settings.beginGroup('testqgissettings') self.assertEqual(['names'], self.settings.childGroups()) self.settings.setValue('surnames/name1', 'qgisrocks-1') self.assertEqual(['surnames', 'names'], self.settings.childGroups()) self.settings.setValue('names/name1', 'qgisrocks-1') self.assertEqual('qgisrocks-1', self.settings.value('names/name1')) self.settings.endGroup() self.settings.beginGroup('testqgissettings/names') self.settings.setValue('name4', 'qgisrocks-4') keys = sorted(self.settings.childKeys()) self.assertEqual(keys, ['name1', 'name2', 'name3', 'name4']) self.settings.endGroup() self.assertEqual('qgisrocks-1', self.settings.value('testqgissettings/names/name1')) self.assertEqual('qgisrocks-4', self.settings.value('testqgissettings/names/name4')) def test_global_groups(self): self.assertEqual(self.settings.allKeys(), []) self.assertEqual(self.globalsettings.allKeys(), []) self.addToDefaults('testqgissettings/foo/first', 'qgis') self.addToDefaults('testqgissettings/foo/last', 'rocks') self.settings.beginGroup('testqgissettings') self.assertEqual(['foo'], self.settings.childGroups()) self.assertEqual(['foo'], self.settings.globalChildGroups()) self.settings.endGroup() self.settings.setValue('testqgissettings/bar/first', 'qgis') self.settings.setValue('testqgissettings/bar/last', 'rocks') self.settings.beginGroup('testqgissettings') self.assertEqual(sorted(['bar', 'foo']), sorted(self.settings.childGroups())) self.assertEqual(['foo'], self.settings.globalChildGroups()) self.settings.endGroup() self.globalsettings.remove('testqgissettings/foo') self.settings.beginGroup('testqgissettings') self.assertEqual(['bar'], self.settings.childGroups()) self.assertEqual([], self.settings.globalChildGroups()) self.settings.endGroup() def test_group_section(self): # Test group by using Section self.settings.beginGroup('firstgroup', section=QgsSettings.Core) self.assertEqual([], self.settings.childGroups()) self.settings.setValue('key', 'value') self.settings.setValue('key2/subkey1', 'subvalue1') self.settings.setValue('key2/subkey2', 'subvalue2') self.settings.setValue('key3', 'value3') self.assertEqual(['key', 'key2/subkey1', 'key2/subkey2', 'key3'], self.settings.allKeys()) self.assertEqual(['key', 'key3'], self.settings.childKeys()) self.assertEqual(['key2'], self.settings.childGroups()) self.settings.endGroup() # Set value by writing the group manually self.settings.setValue('firstgroup/key4', 'value4', section=QgsSettings.Core) # Checking the value that have been set self.assertEqual( self.settings.value('firstgroup/key', section=QgsSettings.Core), 'value') self.assertEqual( self.settings.value('firstgroup/key2/subkey1', section=QgsSettings.Core), 'subvalue1') self.assertEqual( self.settings.value('firstgroup/key2/subkey2', section=QgsSettings.Core), 'subvalue2') self.assertEqual( self.settings.value('firstgroup/key3', section=QgsSettings.Core), 'value3') self.assertEqual( self.settings.value('firstgroup/key4', section=QgsSettings.Core), 'value4') # Clean up firstgroup self.settings.remove('firstgroup', section=QgsSettings.Core) def test_array(self): self.assertEqual(self.settings.allKeys(), []) self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) self.assertEqual(self.settings.allKeys(), [ 'testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size' ]) self.assertEqual(self.globalsettings.allKeys(), [ 'testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size' ]) self.assertEqual( 3, self.globalsettings.beginReadArray('testqgissettings')) self.globalsettings.endArray() self.assertEqual(3, self.settings.beginReadArray('testqgissettings')) values = [] for i in range(3): self.settings.setArrayIndex(i) values.append(self.settings.value("key")) self.assertEqual(values, ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) def test_array_overrides(self): """Test if an array completely shadows the global one""" self.assertEqual(self.settings.allKeys(), []) self.addArrayToDefaults('testqgissettings', 'key', ['qgisrocks1', 'qgisrocks2', 'qgisrocks3']) self.assertEqual(self.settings.allKeys(), [ 'testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size' ]) self.assertEqual(self.globalsettings.allKeys(), [ 'testqgissettings/1/key', 'testqgissettings/2/key', 'testqgissettings/3/key', 'testqgissettings/size' ]) self.assertEqual( 3, self.globalsettings.beginReadArray('testqgissettings')) self.globalsettings.endArray() self.assertEqual(3, self.settings.beginReadArray('testqgissettings')) # Now override! self.settings.beginWriteArray('testqgissettings') self.settings.setArrayIndex(0) self.settings.setValue('key', 'myqgisrocksmore1') self.settings.setArrayIndex(1) self.settings.setValue('key', 'myqgisrocksmore2') self.settings.endArray() # Check it! self.assertEqual(2, self.settings.beginReadArray('testqgissettings')) values = [] for i in range(2): self.settings.setArrayIndex(i) values.append(self.settings.value("key")) self.assertEqual(values, ['myqgisrocksmore1', 'myqgisrocksmore2']) def test_section_getters_setters(self): self.assertEqual(self.settings.allKeys(), []) self.settings.setValue('key1', 'core1', section=QgsSettings.Core) self.settings.setValue('key2', 'core2', section=QgsSettings.Core) self.settings.setValue('key1', 'server1', section=QgsSettings.Server) self.settings.setValue('key2', 'server2', section=QgsSettings.Server) self.settings.setValue('key1', 'gui1', section=QgsSettings.Gui) self.settings.setValue('key2', 'gui2', QgsSettings.Gui) self.settings.setValue('key1', 'plugins1', section=QgsSettings.Plugins) self.settings.setValue('key2', 'plugins2', section=QgsSettings.Plugins) self.settings.setValue('key1', 'misc1', section=QgsSettings.Misc) self.settings.setValue('key2', 'misc2', section=QgsSettings.Misc) self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth) self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth) self.settings.setValue('key1', 'app1', section=QgsSettings.App) self.settings.setValue('key2', 'app2', section=QgsSettings.App) self.settings.setValue('key1', 'provider1', section=QgsSettings.Providers) self.settings.setValue('key2', 'provider2', section=QgsSettings.Providers) self.settings.setValue('key1', 'auth1', section=QgsSettings.Auth) self.settings.setValue('key2', 'auth2', section=QgsSettings.Auth) # Test that the values are namespaced self.assertEqual(self.settings.value('core/key1'), 'core1') self.assertEqual(self.settings.value('core/key2'), 'core2') self.assertEqual(self.settings.value('server/key1'), 'server1') self.assertEqual(self.settings.value('server/key2'), 'server2') self.assertEqual(self.settings.value('gui/key1'), 'gui1') self.assertEqual(self.settings.value('gui/key2'), 'gui2') self.assertEqual(self.settings.value('plugins/key1'), 'plugins1') self.assertEqual(self.settings.value('plugins/key2'), 'plugins2') self.assertEqual(self.settings.value('misc/key1'), 'misc1') self.assertEqual(self.settings.value('misc/key2'), 'misc2') # Test getters self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Core), 'core1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Core), 'core2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Server), 'server1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Server), 'server2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Gui), 'gui1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Gui), 'gui2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Plugins), 'plugins1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Plugins), 'plugins2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Misc), 'misc1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Misc), 'misc2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Auth), 'auth1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Auth), 'auth2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.App), 'app1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.App), 'app2') self.assertEqual( self.settings.value('key1', None, section=QgsSettings.Providers), 'provider1') self.assertEqual( self.settings.value('key2', None, section=QgsSettings.Providers), 'provider2') # Test default values on Section getter self.assertEqual( self.settings.value('key_not_exist', 'misc_not_exist', section=QgsSettings.Misc), 'misc_not_exist') def test_contains(self): self.assertEqual(self.settings.allKeys(), []) self.addToDefaults('testqgissettings/name', 'qgisrocks1') self.addToDefaults('testqgissettings/name2', 'qgisrocks2') self.assertTrue(self.settings.contains('testqgissettings/name')) self.assertTrue(self.settings.contains('testqgissettings/name2')) self.settings.setValue('testqgissettings/name3', 'qgisrocks3') self.assertTrue(self.settings.contains('testqgissettings/name3')) def test_remove(self): self.settings.setValue('testQgisSettings/temp', True) self.assertEqual(self.settings.value('testQgisSettings/temp'), True) self.settings.remove('testQgisSettings/temp') self.assertEqual(self.settings.value('testqQgisSettings/temp'), None) # Test remove by using Section self.settings.setValue('testQgisSettings/tempSection', True, section=QgsSettings.Core) self.assertEqual( self.settings.value('testQgisSettings/tempSection', section=QgsSettings.Core), True) self.settings.remove('testQgisSettings/temp', section=QgsSettings.Core) self.assertEqual( self.settings.value('testqQgisSettings/temp', section=QgsSettings.Core), None) def test_enumValue(self): self.settings.setValue('enum', 'LayerUnits') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits) self.settings.setValue('enum', 'dummy_setting') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels) self.assertEqual( type(self.settings.enumValue('enum', QgsTolerance.Pixels)), QgsTolerance.UnitType) def test_setEnumValue(self): self.settings.setValue('enum', 'LayerUnits') self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.LayerUnits) self.settings.setEnumValue('enum', QgsTolerance.Pixels) self.assertEqual(self.settings.enumValue('enum', QgsTolerance.Pixels), QgsTolerance.Pixels) def test_flagValue(self): pointAndLine = QgsMapLayerProxyModel.Filters( QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.LineLayer) pointAndPolygon = QgsMapLayerProxyModel.Filters( QgsMapLayerProxyModel.PointLayer | QgsMapLayerProxyModel.PolygonLayer) self.settings.setValue('flag', 'PointLayer|PolygonLayer') self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndPolygon) self.settings.setValue('flag', 'dummy_setting') self.assertEqual(self.settings.flagValue('flag', pointAndLine), pointAndLine) self.assertEqual(type(self.settings.flagValue('enum', pointAndLine)), QgsMapLayerProxyModel.Filters)
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) settings = QgsSettings() # Default font font = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setMatchedBraceBackgroundColor( QColor( settings.value( "pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR)))) self.setMatchedBraceForegroundColor( QColor( settings.value( "pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR)))) #self.setWrapMode(QsciScintilla.WrapWord) #self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, # QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor( QColor( settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR)))) self.setSelectionBackgroundColor( QColor( settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR)))) # Show line numbers fontmetrics = QFontMetrics(font) self.setMarginWidth(1, fontmetrics.width("0000") + 5) self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setMarginsBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) self.setIndentationGuidesForegroundColor( QColor( settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR)))) self.setIndentationGuidesBackgroundColor( QColor( settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR)))) # Highlight current line caretLineColorEditor = settings.value( "pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR)) cursorColorEditor = settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR)) self.setCaretLineVisible(True) self.setCaretWidth(2) self.setCaretLineBackgroundColor(caretLineColorEditor) self.setCaretForegroundColor(cursorColorEditor) # Folding self.setFolding(QsciScintilla.PlainFoldStyle) foldColor = QColor( settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR))) self.setFoldMarginColors(foldColor, foldColor) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor( QColor( settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR)))) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) self.setIndentationGuides(True) # Autocompletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setFonts(10) self.initLexer()
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QgsSettings().clear() start_app() # setup some fake connections settings = QgsSettings() key = 'qgis/connections-wms/test/' settings.setValue(key + 'url', 'aaa.bbb.com') settings.setValue(key + 'referer', 'my_ref') settings.setValue(key + 'ignoreGetMapURI', True) settings.setValue(key + 'ignoreGetFeatureInfoURI', True) settings.setValue(key + 'smoothPixmapTransform', True) settings.setValue(key + 'dpiMode', 4) settings.setValue(key + 'ignoreAxisOrientation', True) settings.setValue(key + 'invertAxisOrientation', True) key = 'qgis/connections-wfs/test/' settings.setValue(key + 'url', 'ccc.ddd.com') settings.setValue(key + 'version', '1.1.0') settings.setValue(key + 'maxnumfeatures', '47') settings.setValue(key + 'ignoreAxisOrientation', True) settings.setValue(key + 'invertAxisOrientation', True)
def setCommonOptions(self): # Enable non-ASCII characters self.setUtf8(True) # Default font font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.setFont(font) self.setMarginsFont(font) self.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.setWrapMode(QsciScintilla.WrapWord) self.setWrapVisualFlags(QsciScintilla.WrapFlagByText, QsciScintilla.WrapFlagNone, 4) self.setSelectionForegroundColor(QColor('#2e3436')) self.setSelectionBackgroundColor(QColor('#babdb6')) # Show line numbers self.setMarginWidth(1, '000') self.setMarginLineNumbers(1, True) self.setMarginsForegroundColor(QColor('#2e3436')) self.setMarginsBackgroundColor(QColor('#babdb6')) # Highlight current line self.setCaretLineVisible(True) self.setCaretLineBackgroundColor(QColor('#d3d7cf')) # Folding self.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf')) # Mark column 80 with vertical line self.setEdgeMode(QsciScintilla.EdgeLine) self.setEdgeColumn(80) self.setEdgeColor(QColor('#eeeeec')) # Indentation self.setAutoIndent(True) self.setIndentationsUseTabs(False) self.setIndentationWidth(4) self.setTabIndents(True) self.setBackspaceUnindents(True) self.setTabWidth(4) # Autocomletion self.setAutoCompletionThreshold(2) self.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.setAutoCompletionCaseSensitivity(False) # Load font from Python console settings settings = QgsSettings() fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace') fontSize = int(settings.value('pythonConsole/fontsize', 10)) self.defaultFont = QFont(fontName) self.defaultFont.setFixedPitch(True) self.defaultFont.setPointSize(fontSize) self.defaultFont.setStyleHint(QFont.TypeWriter) self.defaultFont.setStretch(QFont.SemiCondensed) self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0) self.defaultFont.setBold(False) self.boldFont = QFont(self.defaultFont) self.boldFont.setBold(True) self.italicFont = QFont(self.defaultFont) self.italicFont.setItalic(True) self.setFont(self.defaultFont) self.setMarginsFont(self.defaultFont) self.initLexer()
def save(self, qsettings=QgsSettings()): if self.valuetype == self.SELECTION: qsettings.setValue(self.qname, self.options.index(self.value)) else: qsettings.setValue(self.qname, self.value)
def drop_keys(): settings = QgsSettings() settings.remove('plugins/geomapfsih_locator_plugin/filter_name') settings.remove('plugins/geomapfsih_locator_plugin/geomapfish_url') settings.remove('plugins/geomapfsih_locator_plugin/geomapfish_crs') settings.remove('plugins/geomapfsih_locator_plugin/remove_leading_digits') settings.remove('plugins/geomapfsih_locator_plugin/replace_underscore') settings.remove('plugins/geomapfsih_locator_plugin/break_camelcase') settings.remove('plugins/geomapfsih_locator_plugin/category_limit') settings.remove('plugins/geomapfsih_locator_plugin/total_limit') settings.remove('plugins/geomapfsih_locator_plugin/geomapfish_user') settings.remove('plugins/geomapfsih_locator_plugin/geomapfish_pass')
def tearDownClass(cls): """Run after all tests""" QgsSettings().clear() #shutil.rmtree(cls.basetestpath, True) cls.vl = None # so as to properly close the provider and remove any temporary file
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("TestPyQgsAFSProvider.com") QCoreApplication.setApplicationName("TestPyQgsAFSProvider") QgsSettings().clear() start_app() # On Windows we must make sure that any backslash in the path is # replaced by a forward slash so that QUrl can process it cls.basetestpath = tempfile.mkdtemp().replace('\\', '/') endpoint = cls.basetestpath + '/fake_qgis_http_endpoint' with open(sanitize(endpoint, '?f=json'), 'wb') as f: f.write(""" {"currentVersion":10.22,"id":1,"name":"QGIS Test","type":"Feature Layer","description": "QGIS Provider Test Layer.\n","geometryType":"esriGeometryPoint","copyrightText":"","parentLayer":{"id":0,"name":"QGIS Tests"},"subLayers":[], "minScale":72225,"maxScale":0, "defaultVisibility":true, "extent":{"xmin":-71.123,"ymin":66.33,"xmax":-65.32,"ymax":78.3, "spatialReference":{"wkid":4326,"latestWkid":4326}}, "hasAttachments":false,"htmlPopupType":"esriServerHTMLPopupTypeAsHTMLText", "displayField":"LABEL","typeIdField":null, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "relationships":[],"canModifyLayer":false,"canScaleSymbols":false,"hasLabels":false, "capabilities":"Map,Query,Data","maxRecordCount":1000,"supportsStatistics":true, "supportsAdvancedQueries":true,"supportedQueryFormats":"JSON, AMF", "ownershipBasedAccessControlForFeatures":{"allowOthersToQuery":true},"useStandardizedQueries":true}""" .encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json_where=OBJECTID=OBJECTID_returnIdsOnly=true' ), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 5, 3, 1, 2, 4 ] } """.encode('UTF-8')) # Create test layer cls.vl = QgsVectorLayer( "url='http://" + endpoint + "' crs='epsg:4326'", 'test', 'arcgisfeatureserver') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() with open( sanitize( endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false' ), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json&objectIds=5,3,1,2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false&geometry=-71.123000,66.330000,-65.320000,78.300000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects' ), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 5, "pk": 5, "cnt": -200, "name": null, "name2":"NuLl", "num_char":"5" }, "geometry": { "x": -71.123, "y": 78.23 } }, { "attributes": { "OBJECTID": 3, "pk": 3, "cnt": 300, "name": "Pear", "name2":"PEaR", "num_char":"3" }, "geometry": null }, { "attributes": { "OBJECTID": 1, "pk": 1, "cnt": 100, "name": "Orange", "name2":"oranGe", "num_char":"1" }, "geometry": { "x": -70.332, "y": 66.33 } }, { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json&objectIds=2,4&inSR=4326&outSR=4326&returnGeometry=true&outFields=OBJECTID,pk,cnt,name,name2,num_char&returnM=false&returnZ=false' ), 'wb') as f: f.write(""" { "displayFieldName": "name", "fieldAliases": { "name": "name" }, "geometryType": "esriGeometryPoint", "spatialReference": { "wkid": 4326, "latestWkid": 4326 }, "fields":[{"name":"OBJECTID","type":"esriFieldTypeOID","alias":"OBJECTID","domain":null}, {"name":"pk","type":"esriFieldTypeInteger","alias":"pk","domain":null}, {"name":"cnt","type":"esriFieldTypeInteger","alias":"cnt","domain":null}, {"name":"name","type":"esriFieldTypeString","alias":"name","length":100,"domain":null}, {"name":"name2","type":"esriFieldTypeString","alias":"name2","length":100,"domain":null}, {"name":"num_char","type":"esriFieldTypeString","alias":"num_char","length":100,"domain":null}, {"name":"Shape","type":"esriFieldTypeGeometry","alias":"Shape","domain":null}], "features": [ { "attributes": { "OBJECTID": 2, "pk": 2, "cnt": 200, "name": "Apple", "name2":"Apple", "num_char":"2" }, "geometry": { "x": -68.2, "y": 70.8 } }, { "attributes": { "OBJECTID": 4, "pk": 4, "cnt": 400, "name": "Honey", "name2":"Honey", "num_char":"4" }, "geometry": { "x": -65.32, "y": 78.3 } } ] }""".encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-70.000000,67.000000,-60.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects' ), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-73.000000,70.000000,-63.000000,80.000000&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects' ), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8')) with open( sanitize( endpoint, '/query?f=json&where=OBJECTID=OBJECTID&returnIdsOnly=true&geometry=-68.721119,68.177676,-64.678700,79.123755&geometryType=esriGeometryEnvelope&spatialRel=esriSpatialRelEnvelopeIntersects' ), 'wb') as f: f.write(""" { "objectIdFieldName": "OBJECTID", "objectIds": [ 2, 4 ] } """.encode('UTF-8'))
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsColorScheme.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsColorScheme") QgsSettings().clear() start_app() # setup a fake connection settings = QgsSettings() key = QgsGeoNodeConnectionUtils.pathGeoNodeConnection() + '/test/' settings.setValue(key + 'wms/referer', 'my_ref') settings.setValue(key + 'wms/ignoreGetMapURI', True) settings.setValue(key + 'wms/ignoreGetFeatureInfoURI', True) settings.setValue(key + 'wms/smoothPixmapTransform', True) settings.setValue(key + 'wms/dpiMode', 4) settings.setValue(key + 'wms/ignoreAxisOrientation', True) settings.setValue(key + 'wms/invertAxisOrientation', True) settings.setValue(key + 'wfs/version', '1.1.0') settings.setValue(key + 'wfs/maxnumfeatures', '47') settings.setValue(key + 'wfs/ignoreAxisOrientation', True) settings.setValue(key + 'wfs/invertAxisOrientation', True)
def test_representValue(self): layer = QgsVectorLayer("point?field=int:integer&field=double:double&field=long:long", "layer", "memory") self.assertTrue(layer.isValid()) QgsProject.instance().addMapLayers([layer]) fieldFormatter = QgsRangeFieldFormatter() # Precision is ignored for integers and longlongs self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123'), '123') self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '123000'), '123000') self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'), '9999999') # no scientific notation for integers! self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123') self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123000') self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9999999') # no scientific notation for long longs! self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 1}, None, '123'), '123.0') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123000.00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0.00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123.00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0.12') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0.13') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0.000') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0.127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0.127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123.00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0.12') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0.13') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0.127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0.127') QgsSettings().setValue("locale/overrideFlag", True) QgsSettings().setValue("locale/userLocale", 'it') self.assertEqual(fieldFormatter.representValue(layer, 0, {'Precision': 1}, None, '9999999'), '9999999') # no scientific notation for integers! self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123'), '123') self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '123000'), '123000') self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, '9999999'), '9999999') # no scientific notation for long longs! self.assertEqual(fieldFormatter.representValue(layer, 2, {'Precision': 1}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, None), 'NULL') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123000'), '123000,00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0'), '0,00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '123'), '123,00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.123'), '0,12') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '0.127'), '0,13') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0'), '0,000') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '0.127'), '0,127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '1.27e-1'), '0,127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-123'), '-123,00') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.123'), '-0,12') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 2}, None, '-0.127'), '-0,13') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-0.127'), '-0,127') self.assertEqual(fieldFormatter.representValue(layer, 1, {'Precision': 3}, None, '-1.27e-1'), '-0,127') QgsProject.instance().removeAllMapLayers()
def showFileDialog(self, seldir): settings = QgsSettings() text = str(self.text.text()) if os.path.isdir(text): path = text elif not seldir and os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = str(settings.value('/Processing/LastInputPath')) else: path = '' if not seldir: ret, selected_filter = QFileDialog.getOpenFileNames( self, self.tr('Select Files'), path, self.param.createFileFilter()) else: ret = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'), path) if ret: if seldir: settings.setValue('/Processing/LastInputPath', ret) files = [] for pp in Path(ret).rglob("*"): if not pp.is_file(): continue p = pp.as_posix() if ((isinstance(self.param, QgsProcessingParameterRasterLayer) or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeRaster)) and not QgsRasterLayer.isValidRasterFileName(p)): continue files.append(p) if not files: return else: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) self.textEditingFinished() else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(str(f) for f in files)) else: rowdif = len(files) - (self._table().rowCount() - self.row) for i in range(rowdif): self._panel().addRow() for i, f in enumerate(files): self._table().cellWidget(i + self.row, self.col).setValue(f)
def testSetSequence(self): """ test setting key sequences """ QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') shortcut2 = QShortcut(None) shortcut2.setObjectName('shortcut2') action1 = QAction('action1', None) action2 = QAction('action2', None) s.registerShortcut(shortcut1, 'A') s.registerShortcut(shortcut2, 'B') s.registerAction(action1, 'C') s.registerAction(action2, 'D') # test setting by action/shortcut self.assertTrue(s.setKeySequence(shortcut1, 'E')) self.assertTrue(s.setKeySequence(shortcut2, 'F')) self.assertTrue(s.setKeySequence(action1, 'G')) self.assertTrue(s.setKeySequence(action2, 'H')) # test that action/shortcuts have been updated self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(shortcut2.key().toString(), 'F') self.assertEqual(action1.shortcut().toString(), 'G') self.assertEqual(action2.shortcut().toString(), 'H') # new manager s = QgsShortcutsManager(None) # new shortcuts shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') shortcut2 = QShortcut(None) shortcut2.setObjectName('shortcut2') action1 = QAction('action1', None) action2 = QAction('action2', None) # register them s.registerShortcut(shortcut1, 'A') s.registerShortcut(shortcut2, 'B') s.registerAction(action1, 'C') s.registerAction(action2, 'D') # check that previously set sequence has been restored self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(shortcut2.key().toString(), 'F') self.assertEqual(action1.shortcut().toString(), 'G') self.assertEqual(action2.shortcut().toString(), 'H') # same test, using setObjectKeySequence QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertTrue(s.setObjectKeySequence(shortcut1, 'E')) self.assertTrue(s.setObjectKeySequence(action1, 'G')) self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') # same test, using setKeySequence by name QgsSettings().clear() s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertFalse(s.setKeySequence('invalid_name', 'E')) self.assertTrue(s.setKeySequence('shortcut1', 'E')) self.assertTrue(s.setKeySequence('action1', 'G')) self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G') s = QgsShortcutsManager(None) shortcut1 = QShortcut(None) shortcut1.setObjectName('shortcut1') action1 = QAction('action1', None) s.registerShortcut(shortcut1, 'A') s.registerAction(action1, 'C') self.assertEqual(shortcut1.key().toString(), 'E') self.assertEqual(action1.shortcut().toString(), 'G')
def disableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', False)
def enableCompiler(self): QgsSettings().setValue('/qgis/compileExpressions', True)
def closeEvent(self, event): settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) super(ModelerParameterDefinitionDialog, self).closeEvent(event)
def old_version_import() -> Service: settings = QgsSettings() if settings.contains('plugins/geomapfsih_locator_plugin/geomapfish_url'): definition = dict() definition['name'] = settings.value( 'plugins/geomapfsih_locator_plugin/filter_name', 'geomapfish', type=str) definition['url'] = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_url', '', type=str) definition['crs'] = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_crs', '', type=str) definition['remove_leading_digits'] = settings.value( 'plugins/geomapfsih_locator_plugin/remove_leading_digits', True, type=bool) definition['replace_underscore'] = settings.value( 'plugins/geomapfsih_locator_plugin/replace_underscore', True, type=bool) definition['break_camelcase'] = settings.value( 'plugins/geomapfsih_locator_plugin/break_camelcase', True, type=bool) definition['category_limit'] = settings.value( 'plugins/geomapfsih_locator_plugin/category_limit', 8, type=int) definition['total_limit'] = settings.value( 'plugins/geomapfsih_locator_plugin/total_limit', 50, type=int) user = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_user', '', type=str) pwd = settings.value( 'plugins/geomapfsih_locator_plugin/geomapfish_pass', '', type=str) info("importing old service: {}".format(definition)) if user: reply = QMessageBox.question( None, "Geomapfish Locator", QCoreApplication.translate( "Geomapfish Locator", "User and password were saved in clear text in former Geomapfish plugin. " "Would you like to use QGIS authentication to store these credentials? " "If not, they will be removed.")) if reply == QMessageBox.Yes: config = QgsAuthMethodConfig('Basic') config.setName('geomapfish_{}'.format(definition['name'])) config.setConfig('username', user) config.setConfig('password', pwd) QgsApplication.authManager().storeAuthenticationConfig(config) definition['authid'] = config.id() dbg_info("created new auth id: {}".format(config.id())) else: drop_keys() return None drop_keys() return Service(definition) else: return None
def accept(self): description = str(self.nameTextBox.text()) if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while self.alg.parameterDefinition(name): name = safeName.lower() + str(i) i += 1 else: name = self.param.name() if (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or isinstance(self.param, QgsProcessingParameterBoolean)): self.param = QgsProcessingParameterBoolean(name, description, self.state.isChecked()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or isinstance(self.param, QgsProcessingParameterField)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() datatype = self.datatypeCombo.currentData() self.param = QgsProcessingParameterField( name, description, None, parent, datatype, self.multipleCheck.isChecked()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BAND or isinstance(self.param, QgsProcessingParameterBand)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() self.param = QgsProcessingParameterBand(name, description, None, parent) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.param = QgsProcessingParameterMapLayer(name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or isinstance(self.param, QgsProcessingParameterRasterLayer)): self.param = QgsProcessingParameterRasterLayer(name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or isinstance(self.param, QgsProcessingParameterVectorLayer)): self.param = QgsProcessingParameterVectorLayer( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or isinstance(self.param, QgsProcessingParameterFeatureSource)): self.param = QgsProcessingParameterFeatureSource( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.param = QgsProcessingParameterMultipleLayers( name, description, self.datatypeCombo.currentData()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or isinstance(self.param, QgsProcessingParameterNumber)): try: self.param = QgsProcessingParameterNumber( name, description, QgsProcessingParameterNumber.Double, self.defaultTextBox.text()) vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXPRESSION or isinstance(self.param, QgsProcessingParameterExpression)): parent = self.parentCombo.currentData() self.param = QgsProcessingParameterExpression( name, description, str(self.defaultEdit.expression()), parent) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, QgsProcessingParameterString)): self.param = QgsProcessingParameterString( name, description, str(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or isinstance(self.param, QgsProcessingParameterExtent)): self.param = QgsProcessingParameterExtent(name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or isinstance(self.param, QgsProcessingParameterFile)): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = QgsProcessingParameterFile( name, description, QgsProcessingParameterFile.Folder if isFolder else QgsProcessingParameterFile.File) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or isinstance(self.param, QgsProcessingParameterPoint)): self.param = QgsProcessingParameterPoint( name, description, str(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, QgsProcessingParameterCrs)): self.param = QgsProcessingParameterCrs( name, description, self.selector.crs().authid()) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self)
def setUp(self): QgsSettings().setValue('pythonConsole/contextHelpOnFirstLaunch', False)
def setUp(self): QgsSettings().clear()
def tearDownClass(cls): """Run after all tests""" QgsSettings().clear() if cls.basetestpath is not None: shutil.rmtree(cls.basetestpath, True)
def initLexer(self): settings = QgsSettings() self.lexer = QsciLexerPython() font = QFontDatabase.systemFont(QFontDatabase.FixedFont) loadFont = settings.value("pythonConsole/fontfamilytextEditor") if loadFont: font.setFamily(loadFont) fontSize = settings.value("pythonConsole/fontsizeEditor", type=int) if fontSize: font.setPointSize(fontSize) self.lexer.setDefaultFont(font) self.lexer.setDefaultColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR)))) self.lexer.setColor( QColor( settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR))), 1) self.lexer.setColor( QColor( settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR))), 2) self.lexer.setColor( QColor( settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR))), 5) self.lexer.setColor( QColor( settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR))), 8) self.lexer.setColor( QColor( settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR))), 9) self.lexer.setColor( QColor( settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR))), 15) self.lexer.setColor( QColor( settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR))), 12) self.lexer.setColor( QColor( settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))), 4) self.lexer.setColor( QColor( settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))), 3) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6) self.lexer.setColor( QColor( settings.value( "pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7) self.lexer.setColor( QColor( settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13) self.lexer.setFont(font, 1) self.lexer.setFont(font, 3) self.lexer.setFont(font, 4) self.lexer.setFont(font, QsciLexerPython.UnclosedString) for style in range(0, 33): paperColor = QColor( settings.value("pythonConsole/paperBackgroundColorEditor", QColor(self.BACKGROUND_COLOR))) self.lexer.setPaper(paperColor, style) self.api = QsciAPIs(self.lexer) useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True)) if useDefaultAPI: # Load QGIS API shipped with Python console self.api.loadPrepared( os.path.join(QgsApplication.pkgDataPath(), 'python', 'qsci_apis', 'pyqgis.pap')) else: # Load user-defined API files apiPaths = settings.value('pythonConsole/userAPI', []) for path in apiPaths: self.api.load(path) self.api.prepare() self.lexer.setAPIs(self.api) self.setLexer(self.lexer)
def runGdal(commands, feedback=None): if feedback is None: feedback = QgsProcessingFeedback() envval = os.getenv('PATH') # We need to give some extra hints to get things picked up on OS X isDarwin = False try: isDarwin = platform.system() == 'Darwin' except IOError: # https://travis-ci.org/m-kuhn/QGIS#L1493-L1526 pass if isDarwin and os.path.isfile( os.path.join(QgsApplication.prefixPath(), "bin", "gdalinfo")): # Looks like there's a bundled gdal. Let's use it. os.environ['PATH'] = "{}{}{}".format( os.path.join(QgsApplication.prefixPath(), "bin"), os.pathsep, envval) os.environ['DYLD_LIBRARY_PATH'] = os.path.join( QgsApplication.prefixPath(), "lib") else: # Other platforms should use default gdal finder codepath settings = QgsSettings() path = settings.value('/GdalTools/gdalPath', '') if not path.lower() in envval.lower().split(os.pathsep): envval += '{}{}'.format(os.pathsep, path) os.putenv('PATH', envval) fused_command = ' '.join([str(c) for c in commands]) QgsMessageLog.logMessage(fused_command, 'Processing', Qgis.Info) feedback.pushInfo('GDAL command:') feedback.pushCommandInfo(fused_command) feedback.pushInfo('GDAL command output:') success = False retry_count = 0 while not success: loglines = [] loglines.append('GDAL execution console output') try: with subprocess.Popen( fused_command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, universal_newlines=True, ) as proc: for line in proc.stdout: feedback.pushConsoleInfo(line) loglines.append(line) success = True except IOError as e: if retry_count < 5: retry_count += 1 else: raise IOError( str(e) + u'\nTried 5 times without success. Last iteration stopped after reading {} line(s).\nLast line(s):\n{}' .format(len(loglines), u'\n'.join(loglines[-10:]))) QgsMessageLog.logMessage('\n'.join(loglines), 'Processing', Qgis.Info) GdalUtils.consoleOutput = loglines
def setCheckingOnStart(self, state): """ set state of checking for news and updates """ settings = QgsSettings() settings.setValue(settingsGroup + "/checkOnStart", state)
class MultipleInputDialog(BASE, WIDGET): def __init__(self, options, selectedoptions=None, datatype=None): super(MultipleInputDialog, self).__init__(None) self.setupUi(self) self.datatype = datatype self.model = None self.options = [] for i, option in enumerate(options): if option is None or isinstance(option, str): self.options.append((i, option)) else: self.options.append((option[0], option[1])) self.selectedoptions = selectedoptions or [] # Additional buttons self.btnSelectAll = QPushButton(self.tr('Select all')) self.buttonBox.addButton(self.btnSelectAll, QDialogButtonBox.ActionRole) self.btnClearSelection = QPushButton(self.tr('Clear selection')) self.buttonBox.addButton(self.btnClearSelection, QDialogButtonBox.ActionRole) self.btnToggleSelection = QPushButton(self.tr('Toggle selection')) self.buttonBox.addButton(self.btnToggleSelection, QDialogButtonBox.ActionRole) if self.datatype is not None: btnAddFile = QPushButton( QCoreApplication.translate("MultipleInputDialog", 'Add file(s)…')) btnAddFile.clicked.connect(self.addFiles) self.buttonBox.addButton(btnAddFile, QDialogButtonBox.ActionRole) self.btnSelectAll.clicked.connect(lambda: self.selectAll(True)) self.btnClearSelection.clicked.connect(lambda: self.selectAll(False)) self.btnToggleSelection.clicked.connect(self.toggleSelection) self.settings = QgsSettings() self.restoreGeometry( self.settings.value("/Processing/multipleInputDialogGeometry", QByteArray())) self.lstLayers.setSelectionMode(QAbstractItemView.ExtendedSelection) self.lstLayers.setDragDropMode(QAbstractItemView.InternalMove) self.populateList() self.finished.connect(self.saveWindowGeometry) def saveWindowGeometry(self): self.settings.setValue("/Processing/multipleInputDialogGeometry", self.saveGeometry()) def populateList(self): self.model = QStandardItemModel() for value, text in self.options: item = QStandardItem(text) item.setData(value, Qt.UserRole) item.setCheckState(Qt.Checked if value in self.selectedoptions else Qt.Unchecked) item.setCheckable(True) item.setDropEnabled(False) self.model.appendRow(item) # add extra options (e.g. manually added layers) for t in [o for o in self.selectedoptions if not isinstance(o, int)]: if isinstance(t, QgsProcessingModelChildParameterSource): item = QStandardItem(t.staticValue()) else: item = QStandardItem(t) item.setData(item.text(), Qt.UserRole) item.setCheckState(Qt.Checked) item.setCheckable(True) item.setDropEnabled(False) self.model.appendRow(item) self.lstLayers.setModel(self.model) def accept(self): self.selectedoptions = [] model = self.lstLayers.model() for i in range(model.rowCount()): item = model.item(i) if item.checkState() == Qt.Checked: self.selectedoptions.append(item.data(Qt.UserRole)) QDialog.accept(self) def reject(self): self.selectedoptions = None QDialog.reject(self) def getItemsToModify(self): items = [] if len(self.lstLayers.selectedIndexes()) > 1: for i in self.lstLayers.selectedIndexes(): items.append(self.model.itemFromIndex(i)) else: for i in range(self.model.rowCount()): items.append(self.model.item(i)) return items def selectAll(self, value): for item in self.getItemsToModify(): item.setCheckState(Qt.Checked if value else Qt.Unchecked) def toggleSelection(self): for item in self.getItemsToModify(): checked = item.checkState() == Qt.Checked item.setCheckState(Qt.Unchecked if checked else Qt.Checked) def getFileFilter(self, datatype): """ Returns a suitable file filter pattern for the specified parameter definition :param param: :return: """ if datatype == QgsProcessing.TypeRaster: return QgsProviderRegistry.instance().fileRasterFilters() elif datatype == QgsProcessing.TypeFile: return self.tr('All files (*.*)') else: exts = QgsVectorFileWriter.supportedFormatExtensions() for i in range(len(exts)): exts[i] = self.tr('{0} files (*.{1})').format( exts[i].upper(), exts[i].lower()) return self.tr('All files (*.*)') + ';;' + ';;'.join(exts) def addFiles(self): filter = self.getFileFilter(self.datatype) settings = QgsSettings() path = str(settings.value('/Processing/LastInputPath')) ret, selected_filter = QFileDialog.getOpenFileNames( self, self.tr('Select File(s)'), path, filter) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0]))) for filename in files: item = QStandardItem(filename) item.setData(filename, Qt.UserRole) item.setCheckState(Qt.Checked) item.setCheckable(True) item.setDropEnabled(False) self.model.appendRow(item)
def setCheckingOnStartInterval(self, interval): """ set checking for news and updates interval """ settings = QgsSettings() settings.setValue(settingsGroup + "/checkOnStartInterval", interval)
def showSelectionDialog(self): if isinstance(self.output, QgsProcessingParameterFolderDestination): self.selectDirectory() return filefilter = getFileFilter(self.output) settings = QgsSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = str(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename, selectedFileFilter = QFileDialog.getSaveFileName( self, self.tr('Save file'), path, filefilter) if filename: if not filename.lower().endswith( tuple(re.findall("\\*(\\.[a-z]{1,10})", filefilter))): ext = re.search("\\*(\\.[a-z]{1,10})", selectedFileFilter) if ext: filename += ext.group(1) settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename)) dlg = AutofillDialog(self.alg) dlg.exec_() if dlg.mode is not None: try: if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL: self.table.cellWidget(self.row, self.col).setValue(filename) elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS: n = self.table.rowCount() - self.row for i in range(n): name = filename[:filename.rfind('.')] \ + str(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: n = self.table.rowCount() - self.row for i in range(n): widget = self.table.cellWidget( i + self.row, dlg.param_index) param = self.alg.parameterDefinitions()[ dlg.param_index] if isinstance( param, (QgsProcessingParameterRasterLayer, QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMultipleLayers)): v = widget.value() if isinstance(v, QgsMapLayer): s = v.name() else: s = os.path.basename(v) s = os.path.splitext(s)[0] elif isinstance(param, QgsProcessingParameterBoolean): s = str(widget.currentIndex() == 0) elif isinstance(param, QgsProcessingParameterEnum): s = str(widget.currentText()) elif isinstance(param, QgsProcessingParameterMatrix): s = str(widget.table) else: s = str(widget.text()) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) except: pass
def dbConnectionNames(self): settings = QgsSettings() settings.beginGroup('/PostgreSQL/connections/') return settings.childGroups()
def __init__(self, alg): super(AlgorithmDialogBase, self).__init__(iface.mainWindow() if iface else None) self.setupUi(self) # don't collapse parameters panel self.splitter.setCollapsible(0, False) # add collapse button to splitter splitterHandle = self.splitter.handle(1) handleLayout = QVBoxLayout() handleLayout.setContentsMargins(0, 0, 0, 0) self.btnCollapse = QToolButton(splitterHandle) self.btnCollapse.setAutoRaise(True) self.btnCollapse.setFixedSize(12, 12) self.btnCollapse.setCursor(Qt.ArrowCursor) handleLayout.addWidget(self.btnCollapse) handleLayout.addStretch() splitterHandle.setLayout(handleLayout) self.settings = QgsSettings() self.splitter.restoreState(self.settings.value("/Processing/dialogBaseSplitter", QByteArray())) self.restoreGeometry(self.settings.value("/Processing/dialogBase", QByteArray())) self.splitterState = self.splitter.saveState() self.splitterChanged(0, 0) self.executed = False self.mainWidget = None self.alg = alg self.setWindowTitle(self.alg.displayName()) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) # Rename OK button to Run self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok) self.btnRun.setText(self.tr('Run')) self.buttonCancel.setEnabled(False) self.btnClose = self.buttonBox.button(QDialogButtonBox.Close) self.buttonBox.helpRequested.connect(self.openHelp) self.btnCollapse.clicked.connect(self.toggleCollapsed) self.splitter.splitterMoved.connect(self.splitterChanged) # desktop = QDesktopWidget() # if desktop.physicalDpiX() > 96: # self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96) algHelp = self.formatHelp(self.alg) if algHelp is None: self.textShortHelp.hide() else: self.textShortHelp.document().setDefaultStyleSheet('''.summary { margin-left: 10px; margin-right: 10px; } h2 { color: #555555; padding-bottom: 15px; } a { text-decoration: none; color: #3498db; font-weight: bold; } p { color: #666666; } b { color: #333333; } dl dd { margin-bottom: 5px; }''') self.textShortHelp.setHtml(algHelp) def linkClicked(url): webbrowser.open(url.toString()) self.textShortHelp.anchorClicked.connect(linkClicked) self.showDebug = ProcessingConfig.getSetting( ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
def setUpClass(cls): """Run before all tests""" QCoreApplication.setOrganizationName("QGIS_Test") QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsNewGeoPackageLayerDialog.com") QCoreApplication.setApplicationName("QGIS_TestPyQgsNewGeoPackageLayerDialog") QgsSettings().clear()