def check_layers(self): local_layers, unsupported_layers, local_raster_layers = self.update_local_layers() if ((local_layers or local_raster_layers) and self.clouddb) or unsupported_layers: message = "" if local_layers or local_raster_layers: title = self.tr("Local layers found") message += self.tr( "Some layers are using local data. Please upload local layers to your cloud database in the 'Upload Data' tab before publishing.\n\n") if unsupported_layers: title = self.tr("Unsupported layers found") message += self.tr( "Raster, plugin or geometryless layers are not supported:\n\n") layer_types = ["No geometry", "Raster", "Plugin"] for layer in sorted(unsupported_layers, key=lambda layer: layer.name()): message += self.tr(" - %s (%s)\n") % ( layer.name(), layer_types[layer.type()]) message += self.tr( "\nPlease remove or replace above layers before publishing your map.\n") message += self.tr( "For raster data you can use public WMS layers or the OpenLayers Plugin.") QMessageBox.warning(self, title, message) self.refresh_databases() self.ui.tabWidget.setCurrentWidget(self.ui.uploadTab) return False return True
def create_database(self): if self.numDbs < self.maxDBs: db = self.api.create_database() self.show_api_error(db) self.refresh_databases() else: QMessageBox.warning(None, self.tr('Warning!'), self.tr('Number of %s permitted databases exceeded! Please upgrade your account!') % self.maxDBs)
def __init__(self, iface): 'initialize' # 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", "nl") if not locale: locale == 'nl' else: locale = locale[0:2] localePath = os.path.join(self.plugin_dir, 'i18n', 'geopunt4qgis_{}.qm'.format(locale)) if os.path.exists(localePath): self.translator = QTranslator() self.translator.load(localePath) QCoreApplication.installTranslator(self.translator) #version check if locale == 'nl': vc = versionChecker() if not vc.isUptoDate(): QMessageBox.warning(self.iface.mainWindow(), QCoreApplication.translate("geopunt4Qgis", "Waarschuwing"), QCoreApplication.translate("geopunt4Qgis", "Je versie van <a href='http://plugins.qgis.org/plugins/geopunt4Qgis' >geopunt4qgis</a> is niet meer up to date. <br/>Je kunt deze upgraden via het menu:<br/> "+ "<strong>Plugins > Beheer en installeer Plugins > Op te waarderen.</strong><br/>Klik daarna op <strong>Plugin opwaarderen</strong>")) # Create the dialogs (after translation) and keep reference self.adresdlg = geopunt4QgisAdresDialog(self.iface) self.batchgeoDlg = geopunt4QgisBatcGeoCodeDialog(self.iface) self.poiDlg = geopunt4QgisPoidialog(self.iface) self.gipodDlg = geopunt4QgisGipodDialog(self.iface) self.settingsDlg = geopunt4QgisSettingsDialog() if mathplotlibWorks : self.elevationDlg = geopunt4QgisElevationDialog(self.iface) self.datacatalogusDlg = geopunt4QgisDataCatalog(self.iface) self.parcelDlg = geopunt4QgisParcelDlg(self.iface) self.aboutDlg = geopunt4QgisAboutDialog()
def check_existing_id(self, group_id): gl = GroupsList() if group_id in gl.groups.keys(): QMessageBox.critical(self, self.tr('Error on save group'), self.tr('Group with such id already exists! Select new id for group!')) return False return True
def getParamValues(self): if self.mUpdateExistingGroupBox.isChecked(): fieldName = self.mExistingFieldComboBox.currentText() else: fieldName = self.mOutputFieldNameLineEdit.text() layer = self.cmbInputLayer.currentLayer() context = dataobjects.createContext() parameters = {} parameters['INPUT'] = layer parameters['FIELD_NAME'] = fieldName parameters['FIELD_TYPE'] = self.mOutputFieldTypeComboBox.currentIndex() parameters['FIELD_LENGTH'] = self.mOutputFieldWidthSpinBox.value() parameters['FIELD_PRECISION'] = self.mOutputFieldPrecisionSpinBox.value() parameters['NEW_FIELD'] = self.mNewFieldGroupBox.isChecked() parameters['FORMULA'] = self.builder.expressionText() output = QgsProcessingOutputLayerDefinition() if self.leOutputFile.text().strip(): output.sink = QgsProperty.fromValue(self.leOutputFile.text().strip()) else: output.sink = QgsProperty.fromValue('memory:') output.destinationProject = context.project() parameters['OUTPUT'] = output ok, msg = self.alg.checkParameterValues(parameters, context) if not ok: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return {} return parameters
def save_current_keywords(self): """Save keywords to the layer. It will write out the keywords for the current layer. This method is based on the KeywordsDialog class. """ current_keywords = self.get_keywords() try: self.keyword_io.write_keywords( layer=self.layer, keywords=current_keywords) except InaSAFEError as e: error_message = get_error_message(e) # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QMessageBox.warning( self, tr('InaSAFE'), tr('An error was encountered when saving the following ' 'keywords:\n {error_message}').format( error_message=error_message.to_html())) if self.dock is not None: # noinspection PyUnresolvedReferences self.dock.get_layers() # Save default value to QSetting if current_keywords.get('inasafe_default_values'): for key, value in ( list(current_keywords['inasafe_default_values'].items())): set_inasafe_default_value_qsetting( self.setting, RECENT, key, value)
def fetchAvailablePlugins(self, reloadMode): """ Fetch plugins from all enabled repositories.""" """ reloadMode = true: Fully refresh data from QSettings to mRepositories """ """ reloadMode = false: Fetch unready repositories only """ QApplication.setOverrideCursor(Qt.WaitCursor) if reloadMode: repositories.load() plugins.clearRepoCache() plugins.getAllInstalled() for key in repositories.allEnabled(): if reloadMode or repositories.all()[key]["state"] == 3: # if state = 3 (error or not fetched yet), try to fetch once again repositories.requestFetching(key) if repositories.fetchingInProgress(): fetchDlg = QgsPluginInstallerFetchingDialog(iface.mainWindow()) fetchDlg.exec_() del fetchDlg for key in repositories.all(): repositories.killConnection(key) QApplication.restoreOverrideCursor() # display error messages for every unavailable reposioty, unless Shift pressed nor all repositories are unavailable keepQuiet = QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier) if repositories.allUnavailable() and repositories.allUnavailable() != repositories.allEnabled(): for key in repositories.allUnavailable(): if not keepQuiet: QMessageBox.warning(iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self.tr("Error reading repository:") + " " + key + "\n\n" + repositories.all()[key]["error"]) if QgsApplication.keyboardModifiers() == Qt.KeyboardModifiers(Qt.ShiftModifier): keepQuiet = True # finally, rebuild plugins from the caches plugins.rebuild()
def activateAlgorithm(self): if self.model.activateChildAlgorithm(self.element.childId()): self.scene.dialog.repaintModel() else: QMessageBox.warning(None, 'Could not activate Algorithm', 'The selected algorithm depends on other currently non-active algorithms.\n' 'Activate them them before trying to activate it.')
def on_btnLoad_clicked(self): fileName, _ = QFileDialog.getOpenFileName(None, self.tr('Import Colors and elevations from XML'), QDir.homePath(), self.tr('XML files (*.xml *.XML)')) if fileName == '': return doc = QDomDocument() with codecs.open(fileName, 'r', encoding='utf-8') as f: content = f.read() if not doc.setContent(content): QMessageBox.critical(None, self.tr('Error parsing XML'), self.tr('The XML file could not be loaded')) return self.reliefClassTree.clear() reliefColorList = doc.elementsByTagName('ReliefColor') for i in range(reliefColorList.length()): elem = reliefColorList.at(i).toElement() item = QTreeWidgetItem() item.setText(0, elem.attribute('MinElevation')) item.setText(1, elem.attribute('MaxElevation')) item.setBackground(2, QBrush(QColor(int(elem.attribute('red')), int(elem.attribute('green')), int(elem.attribute('blue'))))) self.reliefClassTree.addTopLevelItem(item)
def openModel(self): filename = unicode(QFileDialog.getOpenFileName(self, self.tr('Open Model'), ModelerUtils.modelsFolder(), self.tr('Processing models (*.model *.MODEL)'))) if filename: try: alg = ModelerAlgorithm.fromFile(filename) self.alg = alg self.alg.setModelerView(self) self.textGroup.setText(alg.group) self.textName.setText(alg.name) self.repaintModel() self.view.centerOn(0, 0) self.hasChanged = False except WrongModelException as e: ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, self.tr('Could not load model %s\n%s') % (filename, e.msg)) QMessageBox.critical(self, self.tr('Could not open model'), self.tr('The selected model could not be loaded.\n' 'See the log for more information.')) except Exception as e: ProcessingLog.addToLog(ProcessingLog.LOG_ERROR, self.tr('Could not load model %s\n%s') % (filename, e.args[0])) QMessageBox.critical(self, self.tr('Could not open model'), self.tr('The selected model could not be loaded.\n' 'See the log for more information.'))
def execute(self): settings = QSettings() 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) algList.reloadProvider('model')
def checkPdokJson(self): myversion = self.getSettingsValue('pdokversion', '1') msgtxt = '' msglvl = 0 # QgsMessageBar.INFO try: response = urllib.request.urlopen('http://www.qgis.nl/pdok.version') str_response = response.read().decode('utf-8') pdokversion = json.loads(str_response) if pdokversion > int(myversion): response = urllib.request.urlopen('http://www.qgis.nl/pdok.json') str_response = response.read().decode('utf-8') pdokjson = json.loads(str_response) with open(self.plugin_dir +'/pdok.json', 'w') as outfile: json.dump(pdokjson, outfile) msgtxt = "De laatste versie is opgehaald en zal worden gebruikt " + \ str(pdokversion) + ' (was ' + myversion +')' self.servicesLoaded = False # reset reading of json self.run() self.setSettingsValue('pdokversion', pdokversion) else: msgtxt = "Geen nieuwere versie beschikbaar dan " + str(pdokversion) except Exception as e: #print e msgtxt = "Fout bij ophalen van service info. Netwerk probleem?" msglvl = 2 # QgsMessageBar.CRITICAL # msg if hasattr(self.iface, 'messageBar'): self.iface.messageBar().pushMessage("PDOK services update", msgtxt, level=msglvl, duration=10) else: # 1.8 QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin", msgtxt)
def saveModel(self, saveAs): if not self.can_save(): return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) if self.model.sourceFilePath() and not saveAs: filename = self.model.sourceFilePath() else: filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: if not filename.endswith('.model3'): filename += '.model3' self.model.setSourceFilePath(filename) if filename: if not self.model.toFile(filename): if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1]))) else: QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', ( "This model can't be saved in its original location (probably you do not " "have permission to do it). Please, use the 'Save as…' option.")) ) return self.update_model.emit() if saveAs: self.bar.pushMessage("", self.tr("Model was correctly saved to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) else: self.bar.pushMessage("", self.tr("Model was correctly saved"), level=Qgis.Success, duration=5) self.hasChanged = False
def execute(self): settings = QSettings() 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: algList.reloadProvider('script') 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 batchFinished(self): self.base.stop() if len(self.errors) > 0: msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join(self.errors) QErrorMessage(self).showMessage(msg) inDir = self.getInputFileName() outDir = self.getOutputFileName() if outDir is None or inDir == outDir: self.outFiles = self.inFiles # load layers managing the render flag to avoid waste of time canvas = self.iface.mapCanvas() previousRenderFlag = canvas.renderFlag() canvas.setRenderFlag(False) notCreatedList = [] for item in self.outFiles: fileInfo = QFileInfo(item) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) else: notCreatedList.append(item) canvas.setRenderFlag(previousRenderFlag) if len(notCreatedList) == 0: QMessageBox.information(self, self.tr("Finished"), self.tr("Operation completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("The following files were not created: \n{0}").format(', '.join(notCreatedList)))
def setParamValues(self): if self.mUpdateExistingGroupBox.isChecked(): fieldName = self.mExistingFieldComboBox.currentText() else: fieldName = self.mOutputFieldNameLineEdit.text() layer = dataobjects.getObjectFromName(self.cmbInputLayer.currentText()) self.alg.setParameterValue('INPUT_LAYER', layer) self.alg.setParameterValue('FIELD_NAME', fieldName) self.alg.setParameterValue('FIELD_TYPE', self.mOutputFieldTypeComboBox.currentIndex()) self.alg.setParameterValue('FIELD_LENGTH', self.mOutputFieldWidthSpinBox.value()) self.alg.setParameterValue('FIELD_PRECISION', self.mOutputFieldPrecisionSpinBox.value()) self.alg.setParameterValue('NEW_FIELD', self.mNewFieldGroupBox.isChecked()) self.alg.setParameterValue('FORMULA', self.builder.expressionText()) self.alg.setOutputValue('OUTPUT_LAYER', self.leOutputFile.text().strip() or None) msg = self.alg.checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return False return True
def activateAlgorithm(self): if self.model.activateAlgorithm(self.element.name): self.model.updateModelerView() else: QMessageBox.warning(None, 'Could not activate Algorithm', 'The selected algorithm depends on other currently non-active algorithms.\n' 'Activate them them before trying to activate it.')
def __signal_checkBoxEnableMap_stateChanged(self, state): enable = False if state == Qt.Unchecked: self.__marker.reset() else: if self.__canvas.layerCount() == 0: QMessageBox.warning(self, QApplication.translate( "OpenLayersOverviewWidget", "OpenLayers Overview"), QApplication.translate( "OpenLayersOverviewWidget", "At least one layer in map canvas required")) self.checkBoxEnableMap.setCheckState(Qt.Unchecked) else: enable = True if not self.__initLayerOL: self.__initLayerOL = True self.__setWebViewMap(0) else: self.__refreshMapOL() # GUI if enable: self.lbStatusRead.setVisible(False) self.webViewMap.setVisible(True) else: self.lbStatusRead.setText("") self.lbStatusRead.setVisible(True) self.webViewMap.setVisible(False) self.webViewMap.setEnabled(enable) self.comboBoxTypeMap.setEnabled(enable) self.pbRefresh.setEnabled(enable) self.pbAddRaster.setEnabled(enable) self.pbCopyKml.setEnabled(enable) self.pbSaveImg.setEnabled(enable) self.checkBoxHideCross.setEnabled(enable)
def accept(self): try: self.setParamValues() msg = self.alg._checkParameterValuesBeforeExecuting() if msg: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return description = algAsDict(self.alg) description["name"] = self.settingsPanel.txtName.text().strip() description["group"] = self.settingsPanel.txtGroup.text().strip() if not (description["name"] and description["group"]): self.tabWidget.setCurrentIndex(self.tabWidget.count() - 1) return validChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:' filename = ''.join(c for c in description["name"] if c in validChars).lower() + ".json" filepath = os.path.join(preconfiguredAlgorithmsFolder(), filename) with open(filepath, "w") as f: json.dump(description, f) algList.reloadProvider('preconfigured') except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox.accepted.connect(lambda: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) self.lblProgress.setText( self.tr('<b>Missing parameter value: %s</b>') % e.parameter.description) return except: QMessageBox.critical(self, self.tr('Unable to execute algorithm'), self.tr('Wrong or missing parameter values')) self.close()
def remove(self): item = self.lessonsTree.currentItem() if hasattr(item, "lesson"): reply = QMessageBox.question(None, "Confirmation", "Are you sure you want to uninstall this lesson?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: _removeLesson(item.lesson) item = self.lessonsTree.currentItem() parent = item.parent() parent.takeChild(parent.indexOfChild(item)) if parent.childCount() == 0: self.lessonsTree.takeTopLevelItem(self.lessonsTree.indexOfTopLevelItem(parent)) item.lesson.uninstall() else: reply = QMessageBox.question(None, "Confirmation", "Are you sure you want to uninstall this group of lessons?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: for i in range(item.childCount()): child = item.child(i) _removeLesson(child.lesson) child.lesson.uninstall() self.lessonsTree.takeTopLevelItem(self.lessonsTree.indexOfTopLevelItem(item))
def wkblify_raster(self, options, infile, i, previous_gt = None): """Writes given raster dataset using GDAL features into HEX-encoded of WKB for WKT Raster output.""" # Open source raster file ds = gdal.Open(infile, gdalc.GA_ReadOnly); if ds is None: QMessageBox.critical(None,'Error:','Cannot open input file: ' + str(infile)) # By default, translate all raster bands # Calculate range for single-band request if options['band'] is not None and options['band'] > 0: band_range = ( options['band'], options['band'] + 1 ) else: band_range = ( 1, ds.RasterCount + 1 ) # Compare this px size with previous one current_gt = self.get_gdal_geotransform(ds) if previous_gt is not None: if previous_gt[1] != current_gt[1] or previous_gt[5] != current_gt[5]: QMessageBox.critical(None,'Error:', 'Cannot load raster with different pixel size in the same raster table') # Generate requested overview level (base raster if level = 1) summary = self.wkblify_raster_level(options, ds, options['overview_level'], band_range, infile, i) SUMMARY.append( summary ) # Cleanup ds = None return current_gt
def saveMessages(self): """ Saves each KLIC message using pickle in textfile in a folder KLIC next to Quantum GIS projectfile. Save also reference to this pickled object in project file itself. """ l_project = QgsProject.instance() l_project_file = str(l_project.fileName()) l_title = self.tr("Opslaan in project") if l_project_file == "": l_msg = self.tr("Nog niet opgeslagen als project!\nKies Bestand - Project opslaan...") QMessageBox.warning(self, l_title, l_msg) else: # save the project setting 'b4udignl' 'wv_docs_file' in project. # first it is added to the project object l_wvs_file = l_project_file.replace(".qgs", "_wv_docs.txt") l_wvs_file_name = os.path.basename(l_wvs_file) # write project setting l_project.writeEntry('b4udignl', 'wv_docs_file', l_wvs_file_name) l_file = open(l_wvs_file, 'w') l_wv_docs = self.docsToPickle() # use pickle to write a textfile holding object instance # that can be recreated. pickle.dump(l_wv_docs, l_file) # save the project immediately, this should be done otherwise # the project setting 'wv_docs_file' could be missing when # user decides upon leaving the project to Discard the changes. # Adding the project setting was considered a project change. l_action = self.__iface.actionSaveProject() # activate(0) triggers the action save project! l_action.activate(0) # inform the user that changes have been included in project. l_msg = self.tr("KLIC berichten opgeslagen in project") QMessageBox.warning(self, l_title, l_msg)
def calculateKappa(self): currentLayer = self.iface.mapCanvas().currentLayer() if currentLayer: d = CalculateKappaAndConvergenceDialog(self.iface) d.exec_() else: QMessageBox.warning(self.iface.mainWindow(), self.tr("Warning!"), self.tr("Please, open a layer and select a line or polygon feature."))
def exportTxt(self): delimiter = self.__getDelimiter() decimalDelimiter = self.__getDecimalDelimiter() if delimiter == decimalDelimiter: msg = QApplication.translate("code", "Gleiches Dezimal- und Spaltentrennzeichen gewählt!") QMessageBox.warning(self.iface.mainWindow(), "VoGIS-Profiltool", msg) return u = Util(self.iface) caption = QApplication.translate("code", "Textdatei exportieren") fileName, file_ext = u.getFileName(caption, [["txt", "txt"]], self.filePath) if fileName == "": return fInfo = QFileInfo(fileName) self.filePath = fInfo.path() QgsSettings().setValue("vogisprofiltoolmain/savepath", self.filePath) hekto = (self.ui.IDC_chkHekto.checkState() == Qt.Checked) attribs = (self.ui.IDC_chkLineAttributes.checkState() == Qt.Checked) txt = open(fileName, "w") txt.write(self.profiles[0].writeHeader(self.settings.mapData.rasters.selectedRasters(), hekto, attribs, delimiter)) for p in self.profiles: #txt.write("=====Profil {0}======{1}".format(p.id, os.linesep)) #txt.write("Segments:{0}{1}".format(len(p.segments), os.linesep)) #for s in p.segments: # txt.write("Vertices:{0}{1}".format(len(s.vertices), os.linesep)) txt.write(p.toString(hekto, attribs, delimiter, decimalDelimiter )) txt.close()
def saveScript(self, saveAs): newPath = None if self.filePath is None or saveAs: scriptDir = ScriptUtils.scriptsFolders()[0] newPath, _ = QFileDialog.getSaveFileName(self, self.tr("Save script"), scriptDir, self.tr("Processing scripts (*.py *.PY)")) if newPath: if not newPath.lower().endswith(".py"): newPath += ".py" self.filePath = newPath if self.filePath: text = self.editor.text() try: with codecs.open(self.filePath, "w", encoding="utf-8") as f: f.write(text) except IOError as e: QMessageBox.warning(self, self.tr("I/O error"), self.tr("Unable to save edits:\n{}").format(str(e)) ) return self.setHasChanged(False) QgsApplication.processingRegistry().providerById("script").refreshAlgorithms()
def addToLayout(self): mgr = QgsProject.instance().layoutManager() layout = None layouts = mgr.layouts() if len(layouts) == 0: QMessageBox.warning(self, QApplication.translate("code", "Keine Layouts"), QApplication.translate("code", "Zuerst ein Layout erstellen")) return elif len(layouts) == 1: layout = layouts[0] else: d = VoGISProfilToolLayoutsDialog(self, layouts) result = d.exec_() if result == QDialog.Accepted: layout = mgr.layoutByName(d.ui.cmbLayouts.currentText()) else: return u = Util(self.iface) caption = QApplication.translate("code", "PNG Datei") file_format = [] file_format.append(["PNG files", "png"]) fileName, fileExt = u.getFileName(caption, file_format, QgsProject.instance().homePath()) if fileName == "": return fInfo = QFileInfo(fileName) self.filePath = fInfo.path() figure = self.subplot.figure figure.savefig(fileName, format="png") image = QgsLayoutItemPicture(layout) image.setPicturePath(fileName) image.attemptResize(QgsLayoutSize(200, 200)) layout.addLayoutItem(image)
def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values'))
def show_api_error(self, result): if 'error' in result: QMessageBox.critical(None, "QGIS Cloud Error", "%s" % result['error']) self.status_bar.showMessage(u"Error") return True else: return False
def test(self): if self.widget is not None and self.widget.isVisible(): QMessageBox.warning(self.iface.mainWindow(), "Tester plugin", "A test cycle is currently being run") return dlg = TestSelector() dlg.exec_() if dlg.tests: settings = {} for test in dlg.tests: settings.update(test.settings) settings.update(self.lastSettings) if settings: settingsDlg = SettingsWindow(settings) settingsDlg.exec_() if not settingsDlg.settings: return self.lastSettings = settingsDlg.settings for key, value in list(settingsDlg.settings.items()): os.environ[key] = value self.widget = TesterWidget() self.widget.testingFinished.connect(self.testingFinished) self.iface.addDockWidget(Qt.TopDockWidgetArea, self.widget) self.widget.show() self.widget.setTests(dlg.tests) self.widget.startTesting()
def copy_layer_settings(self, source_layer, target_layer): # copy filter if target_layer.type() == QgsVectorLayer: target_layer.setSubsetString(source_layer.subsetString()) # copy symbology error = "" doc = QDomDocument() node = doc.createElement("symbology") doc.appendChild(node) source_layer.writeSymbology(node, doc, error, QgsReadWriteContext()) if not error: target_layer.readSymbology(node, error, QgsReadWriteContext()) if error: QMessageBox.warning(None, "Could not copy symbology", error) # copy scale based visibility try: target_layer.setScaleBasedVisibility(source_layer.hasScaleBasedVisibility()) except: # Fall back to the deprecated function target_layer.toggleScaleBasedVisibility(source_layer.hasScaleBasedVisibility()) target_layer.setMinimumScale(source_layer.minimumScale()) target_layer.setMaximumScale(source_layer.maximumScale()) #copy CRS target_layer.setCrs(source_layer.crs(), False)
def createTest(text): definition = {} alg_id, parameters = splitAlgIdAndParameters(text) alg = QgsApplication.processingRegistry().createAlgorithmById(alg_id) definition['name'] = 'Test ({})'.format(alg_id) definition['algorithm'] = alg_id params = {} results = {} i = 0 for param in alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden or param.isDestination(): continue if not param.name() in parameters: continue i += 1 token = parameters[param.name()] # Handle empty parameters that are optionals if param.flags() & QgsProcessingParameterDefinition.FlagOptional and token is None: continue if isinstance(param, (QgsProcessingParameterVectorLayer, QgsProcessingParameterFeatureSource)): schema, filepath = extractSchemaPath(token) p = { 'type': 'vector', 'name': filepath } if not schema: p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]' params[param.name()] = p elif isinstance(param, QgsProcessingParameterRasterLayer): schema, filepath = extractSchemaPath(token) p = { 'type': 'raster', 'name': filepath } if not schema: p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]' params[param.name()] = p elif isinstance(param, QgsProcessingParameterMultipleLayers): multiparams = token newparam = [] # Handle datatype detection dataType = param.layerType() if dataType in [QgsProcessing.TypeVectorAnyGeometry, QgsProcessing.TypeVectorPoint, QgsProcessing.TypeVectorLine, QgsProcessing.TypeVectorPolygon, QgsProcessing.TypeVector]: dataType = 'vector' else: dataType = 'raster' schema = None for mp in multiparams: schema, filepath = extractSchemaPath(mp) newparam.append({ 'type': dataType, 'name': filepath }) p = { 'type': 'multi', 'params': newparam } if not schema: p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]' params[param.name()] = p elif isinstance(param, QgsProcessingParameterFile): schema, filepath = extractSchemaPath(token) p = { 'type': 'file', 'name': filepath } if not schema: p['location'] = '[The source data is not in the testdata directory. Please use data in the processing/tests/testdata folder.]' params[param.name()] = p elif isinstance(param, QgsProcessingParameterString): params[param.name()] = token elif isinstance(param, QgsProcessingParameterBoolean): params[param.name()] = token elif isinstance(param, (QgsProcessingParameterNumber, QgsProcessingParameterDistance)): if param.dataType() == QgsProcessingParameterNumber.Integer: params[param.name()] = int(token) else: params[param.name()] = float(token) elif isinstance(param, QgsProcessingParameterEnum): if isinstance(token, list): params[param.name()] = [int(t) for t in token] else: params[param.name()] = int(token) elif isinstance(param, QgsProcessingParameterBand): params[param.name()] = int(token) elif token: if token[0] == '"': token = token[1:] if token[-1] == '"': token = token[:-1] params[param.name()] = token definition['params'] = params for i, out in enumerate([out for out in alg.destinationParameterDefinitions() if not out.flags() & QgsProcessingParameterDefinition.FlagHidden]): if not out.name() in parameters: continue token = parameters[out.name()] if isinstance(out, QgsProcessingParameterRasterDestination): if token is None: QMessageBox.warning(None, tr('Error'), tr('Seems some outputs are temporary ' 'files. To create test you need to ' 'redirect all algorithm outputs to ' 'files')) return dataset = gdal.Open(token, GA_ReadOnly) if dataset is None: QMessageBox.warning(None, tr('Error'), tr('Seems some outputs are temporary ' 'files. To create test you need to ' 'redirect all algorithm outputs to ' 'files')) return dataArray = nan_to_num(dataset.ReadAsArray(0)) strhash = hashlib.sha224(dataArray.data).hexdigest() results[out.name()] = { 'type': 'rasterhash', 'hash': strhash } elif isinstance(out, (QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink)): schema, filepath = extractSchemaPath(token) results[out.name()] = { 'type': 'vector', 'name': filepath } if not schema: results[out.name()]['location'] = '[The expected result data is not in the testdata directory. Please write it to processing/tests/testdata/expected. Prefer gml files.]' elif isinstance(out, QgsProcessingParameterFileDestination): schema, filepath = extractSchemaPath(token) results[out.name()] = { 'type': 'file', 'name': filepath } if not schema: results[out.name()]['location'] = '[The expected result file is not in the testdata directory. Please redirect the output to processing/tests/testdata/expected.]' definition['results'] = results dlg = ShowTestDialog(yaml.dump([definition], default_flow_style=False)) dlg.exec_()
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() default = self.defaultTextBox.text() if not default: default = None self.param = QgsProcessingParameterField(name, description, defaultValue=default, parentLayerParameterName=parent, type=datatype, allowMultiple=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 showHelp(self): helpText = u"""In this dialog you can set up versioning support for a table. The table will be modified so that all changes will be recorded: there will be a column with start time and end time. Every row will have its start time, end time is assigned when the feature gets deleted. When a row is modified, the original data is marked with end time and new row is created. With this system, it's possible to get back to state of the table any time in history. When selecting rows from the table, you will always have to specify at what time do you want the rows.""" QMessageBox.information(self, "Help", helpText)
def accept(self): description = 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 == parameters.PARAMETER_BOOLEAN or isinstance(self.param, QgsProcessingParameterBoolean)): self.param = QgsProcessingParameterBoolean(name, description, self.state.isChecked()) elif (self.paramType == parameters.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() default = self.defaultTextBox.text() if not default: default = None self.param = QgsProcessingParameterField( name, description, defaultValue=default, parentLayerParameterName=parent, type=datatype, allowMultiple=self.multipleCheck.isChecked()) elif (self.paramType == parameters.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 == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.param = QgsProcessingParameterMapLayer(name, description) elif (self.paramType == parameters.PARAMETER_RASTER or isinstance(self.param, QgsProcessingParameterRasterLayer)): self.param = QgsProcessingParameterRasterLayer(name, description) elif (self.paramType == parameters.PARAMETER_TABLE or isinstance(self.param, QgsProcessingParameterVectorLayer)): self.param = QgsProcessingParameterVectorLayer( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_VECTOR or isinstance(self.param, QgsProcessingParameterFeatureSource)): self.param = QgsProcessingParameterFeatureSource( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.param = QgsProcessingParameterMultipleLayers( name, description, self.datatypeCombo.currentData()) elif (self.paramType == parameters.PARAMETER_DISTANCE or isinstance(self.param, QgsProcessingParameterDistance)): self.param = QgsProcessingParameterDistance( name, description, self.defaultTextBox.text()) try: 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 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() if parent: self.param.setParentParameterName(parent) elif (self.paramType == parameters.PARAMETER_NUMBER or isinstance(self.param, QgsProcessingParameterNumber)): self.param = QgsProcessingParameterNumber( name, description, QgsProcessingParameterNumber.Double, self.defaultTextBox.text()) try: 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 == parameters.PARAMETER_EXPRESSION or isinstance(self.param, QgsProcessingParameterExpression)): parent = self.parentCombo.currentData() self.param = QgsProcessingParameterExpression( name, description, str(self.defaultEdit.expression()), parent) elif (self.paramType == parameters.PARAMETER_STRING or isinstance(self.param, QgsProcessingParameterString)): self.param = QgsProcessingParameterString( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_EXTENT or isinstance(self.param, QgsProcessingParameterExtent)): self.param = QgsProcessingParameterExtent(name, description) elif (self.paramType == parameters.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 == parameters.PARAMETER_POINT or isinstance(self.param, QgsProcessingParameterPoint)): self.param = QgsProcessingParameterPoint( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_CRS or isinstance(self.param, QgsProcessingParameterCrs)): self.param = QgsProcessingParameterCrs( name, description, self.selector.crs().authid()) elif (self.paramType == parameters.PARAMETER_ENUM or isinstance(self.param, QgsProcessingParameterEnum)): self.param = QgsProcessingParameterEnum( name, description, self.widget.options(), self.widget.allowMultiple(), self.widget.defaultOptions()) elif (self.paramType == parameters.PARAMETER_MATRIX or isinstance(self.param, QgsProcessingParameterMatrix)): self.param = QgsProcessingParameterMatrix( name, description, hasFixedNumberRows=self.widget.fixedRows(), headers=self.widget.headers(), defaultValue=self.widget.value()) # Destination parameter elif (isinstance(self.param, QgsProcessingParameterFeatureSink)): self.param = QgsProcessingParameterFeatureSink( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterFileDestination)): self.param = QgsProcessingParameterFileDestination( name=name, description=self.param.description(), fileFilter=self.param.fileFilter(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterFolderDestination)): self.param = QgsProcessingParameterFolderDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterRasterDestination)): self.param = QgsProcessingParameterRasterDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterVectorDestination)): self.param = QgsProcessingParameterVectorDestination( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.getValue()) else: if self.paramType: typeId = self.paramType else: typeId = self.param.type() paramTypeDef = QgsApplication.instance().processingRegistry( ).parameterType(typeId) if not paramTypeDef: msg = self.tr( 'The parameter `{}` is not registered, are you missing a required plugin?' .format(typeId)) raise UndefinedParameterException(msg) self.param = paramTypeDef.create(name) self.param.setDescription(description) self.param.setMetadata(paramTypeDef.metadata()) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagOptional) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self)
def msgInfo(self, txt): QMessageBox.information(self, 'Informació', txt)
def show_warn(self, msg): QMessageBox.warning(self.iface.mainWindow(), self.context, msg)
def show_messagebox(self, **kwargs): """ Shows a message box with detail information """ msg = kwargs['message'] if 'message' in kwargs else 'No message found' title = kwargs['title'] if 'title' in kwargs else 'New message' inf_text = kwargs['inf_text'] if 'inf_text' in kwargs else 'Info text' # color = "black" # bold = '' # if 'styleSheet' in kwargs: # color = kwargs['styleSheet']['color'] if 'color' in kwargs['styleSheet'] else "black" # if 'bold' in kwargs['styleSheet']: # bold = 'b' if kwargs['styleSheet']['bold'] else '' # else: # bold = '' # msg = f'<font color="{color}"><{bold}>{msg}</font>' msg_box = QMessageBox() msg_box.setText(msg) if title: title = self.controller.tr(title) msg_box.setWindowTitle(title) if inf_text: inf_text = self.controller.tr(inf_text) msg_box.setInformativeText(inf_text) msg_box.setWindowFlags(Qt.WindowStaysOnTopHint) msg_box.setStandardButtons(QMessageBox.Ok) msg_box.setDefaultButton(QMessageBox.Ok) msg_box.open()
def okPressed(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 name in self.alg.inputs: name = safeName.lower() + str(i) else: name = self.param.name if (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or isinstance(self.param, ParameterBoolean)): self.param = ParameterBoolean(name, description, self.state.isChecked()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or isinstance(self.param, ParameterTableField)): 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 = ParameterTableField(name, description, parent, datatype, multiple=self.multipleCheck.isChecked()) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or isinstance(self.param, ParameterRaster)): self.param = ParameterRaster( name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or isinstance(self.param, ParameterTable)): self.param = ParameterTable( name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or isinstance(self.param, ParameterVector)): self.param = ParameterVector( name, description, [self.shapetypeCombo.currentIndex() - 1]) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or isinstance(self.param, ParameterMultipleInput)): self.param = ParameterMultipleInput( name, description, self.datatypeCombo.currentIndex() - 1) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or isinstance(self.param, ParameterNumber)): try: vmin = self.minTextBox.text().strip() if vmin == '': vmin = None else: vmin = float(vmin) vmax = self.maxTextBox.text().strip() if vmax == '': vmax = None else: vmax = float(vmax) self.param = ParameterNumber(name, description, vmin, vmax, str(self.defaultTextBox.text())) 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, ParameterExpression)): parent = self.parentCombo.currentData() self.param = ParameterExpression(name, description, default=str(self.defaultEdit.expression()), parent_layer=parent) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or isinstance(self.param, ParameterString)): self.param = ParameterString(name, description, str(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or isinstance(self.param, ParameterExtent)): self.param = ParameterExtent(name, description) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or isinstance(self.param, ParameterFile)): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = ParameterFile(name, description, isFolder=isFolder) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or isinstance(self.param, ParameterPoint)): self.param = ParameterPoint(name, description, str(self.defaultTextBox.text())) elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or isinstance(self.param, ParameterCrs)): self.param = ParameterCrs(name, description, default=self.selector.crs().authid()) self.param.optional = not self.requiredCheck.isChecked() self.close()
def accept(self): feedback = self.createFeedback() context = dataobjects.createContext(feedback) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: parameters = self.getParameterValues() if checkCRS and not self.algorithm().validateInputCrs( parameters, context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Parameters do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.algorithm().checkParameterValues( parameters, context) if msg: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.runButton().setEnabled(False) self.cancelButton().setEnabled(False) buttons = self.mainWidget().iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.clearProgress() self.setProgressText( QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…')) self.setInfo(QCoreApplication.translate( 'AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format( self.algorithm().displayName()), escapeHtml=False) feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition( k).valueAsPythonString(v, context)) feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') feedback.pushInfo('') start_time = time.time() if self.iterateParam: # Make sure the Log tab is visible before executing the algorithm try: self.showLog() self.repaint() except: pass self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.algorithm(), parameters, self.iterateParam, context, feedback): feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) self.cancelButton().setEnabled(False) self.finish(True, parameters, context, feedback) else: self.cancelButton().setEnabled(False) self.resetGui() else: command = self.algorithm().asPythonCommand(parameters, context) if command: ProcessingLog.addToLog(command) self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) feedback.pushInfo(self.tr('Results:')) feedback.pushCommandInfo(pformat(results)) else: feedback.reportError( self.tr('Execution failed after {0:0.2f} seconds'). format(time.time() - start_time)) feedback.pushInfo('') if self.feedback_dialog is not None: self.feedback_dialog.close() self.feedback_dialog.deleteLater() self.feedback_dialog = None self.cancelButton().setEnabled(False) self.finish(ok, results, context, feedback) if not (self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading): # Make sure the Log tab is visible before executing the algorithm self.showLog() task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, context, feedback) task.executed.connect(on_complete) self.setCurrentTask(task) else: self.feedback_dialog = self.createProgressDialog() self.feedback_dialog.show() ok, results = execute(self.algorithm(), parameters, context, feedback) on_complete(ok, results) except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox().accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage( "", self.tr("Wrong or missing parameter value: {0}").format( e.parameter.description()), level=Qgis.Warning, duration=5)
def initGui(self): QMessageBox.warning( self.iface.mainWindow(), 'WfsOutputExtension plugin', 'WfsOutputExtension is plugin for QGIS Server. There is nothing in QGIS Desktop.', )
def run(self): """Run method that performs all the real work""" # Create the dialog with elements (after translation) and keep reference # Only create GUI ONCE in callback, so that it will only load when the plugin is started if self.first_start == True: self.first_start = False self.dlg = MappingEcosystemServicesDialog() self.dlg.helpButton.pressed.connect(self.helpAction) self.dlg.outputFolderButton.pressed.connect(self.selectFolder) self.dlg.sourceDeleteButton.clicked.connect( self.sourceButtonDelete) self.dlg.targetDeleteButton.clicked.connect( self.targetButtonDelete) self.dlg.maxDistanceSpinBox.valueChanged.connect(self.checkCRS) self.dlg.studyAreaLayerQbox.activated.connect(self.checkCRSWarning) self.dlg.landUseLayerQbox.activated.connect(self.checkCRSWarning) # self.dlg.landUseFieldQbox.activated.connect(self.checkCRS) self.dlg.searchFolder.textChanged.connect(self.checkCRS) self.dlg.outputRasterSizeBox.valueChanged.connect(self.checkCRS) self.dlg.target.itemChanged.connect(self.checkCRS) self.dlg.source.itemChanged.connect(self.checkSourceValue) # show the dialog self.dlg.show() self.dlg.formulaQBox.clear() self.dlg.formulaQBox.addItems(['Linear', 'Gaussian']) # self.dlg.searchFolder.clear() # connect check OK function ############## Load layers ###################### # Fetch Study area layers = self.getLayers() # only vector layers # https://qgis.org/pyqgis/master/core/QgsMapLayerType.html#qgis.core.QgsMapLayerType # Clear the contents of the comboBox from previous runs self.dlg.studyAreaLayerQbox.clear() # Populate the comboBox with names of all vector layers self.dlg.studyAreaLayerQbox.addItem('') self.dlg.studyAreaLayerQbox.addItems( [layer.name() for layer in layers]) # Fetch Land Use self.dlg.landUseLayerQbox.clear() self.dlg.landUseFieldQbox.clear() self.dlg.origin.clear() self.dlg.target.setRowCount(0) self.dlg.source.setRowCount(0) # Populate the comboBox with names of all vector layers self.dlg.landUseLayerQbox.addItem('') self.dlg.landUseLayerQbox.addItems([layer.name() for layer in layers]) self.dlg.landUseLayerQbox.currentIndexChanged.connect( self.loadLandUseFields) self.dlg.landUseFieldQbox.currentIndexChanged.connect( self.loadLandUseTableData) ############################## self.dlg.source.setColumnCount(2) self.dlg.source.setHorizontalHeaderLabels(['Land use', 'Value']) # self.dlg.source.model().rowsAboutToBeInserted.connect(self.sourceRowsAdded) buttonOK = self.dlg.button_box.buttons()[0] buttonOK.setEnabled(False) ##################################### # current timestamp usefull for output files self.timestamp = str(datetime.now().strftime("%d%m%Y_%H%M%S")) # Run the dialog event loop result = self.dlg.exec_() ######################################################## # See if OK was pressed if result: outputFolder = self.dlg.searchFolder.displayText() if outputFolder == '': QMessageBox.information( None, "Warning!", "No datasets folder selected. Please select a folder.") iface.messageBar().clearWidgets() return studyAreaLayer = self.getSelectedStudyAreaLayer() landUseLayer = self.getSelectedLandUseLayer() currentCRSID = 4326 try: currentCRSID = landUseLayer.crs().postgisSrid() except: try: currentCRSID = QgsProject.instance().crs().postgisSrid() except: currentCRSID = 4326 # print(landUseLayer.source()) context = dataobjects.createContext() context.setInvalidGeometryCheck(QgsFeatureRequest.GeometryNoCheck) formulaType = self.dlg.formulaQBox.currentText() analysisType = self.dlg.analysisTypeBox.currentText() # progressMessageBar.setText('Extracting polygons ...') # progress.setValue(10) outputFile = "ogr:dbname='" + \ os.path.join(outputFolder, 'output_result_'+analysisType+'_'+formulaType+'_') + \ self.timestamp+".gpkg' table=land_use (geom) sql=" # extract poligons that intersect area of interest processing.run( "qgis:extractbylocation", { 'INPUT': landUseLayer, 'INTERSECT': studyAreaLayer, 'OUTPUT': outputFile, 'PREDICATE': [0] }) outputFile = os.path.join(outputFolder, 'output_result_'+analysisType+'_'+formulaType+'_') + \ self.timestamp+".gpkg" self.saveLayerIntoPkg(studyAreaLayer, outputFile, 'study_area') srcDataSource = ogr.Open( os.path.join( outputFolder, 'output_result_' + analysisType + '_' + formulaType + '_') + self.timestamp + '.gpkg', 1) # progressMessageBar.setText('Computing values ...') # progress.setValue(20) sourceItems = self.getSourceItems().get('items') sourceValues = self.getSourceItems().get('values') if analysisType == 'Boundaries': if formulaType == 'Linear': sql = ''' with s as ( select *, case {landUseField} {caseStatment} end as value from {landUseLayer} where {landUseField} in ({sourceItems}) ), t as ( select * from {landUseLayer} where {landUseField} in ({targetItems}) ) SELECT AsWKT(st_ShortestLine(s.geom,t.geom)) as geomText ,t.fid as tfid,s.fid as sfid,t.{landUseField}, st_distance(s.geom,t.geom) as distance, CASE WHEN st_distance(s.geom,t.geom) = 0 then s.value WHEN st_distance(s.geom,t.geom)>0 then (1-(st_distance(s.geom,t.geom)/{maxDistance}))*s.value END as computed FROM s,t where PtDistWithin(s.geom,t.geom,{maxDistance}) '''.format( landUseLayer="land_use", studyArea="study_area", landUseField=self.landUseSelectedField.name(), targetItems=', '.join([ '"' + str(x) + '"' for x in self.getTargetItems() ]), sourceItems=', '.join( ['"' + str(x) + '"' for x in sourceItems]), # sourceValues=', '.join( # [str(x) for x in sourceValues]), caseStatment=' '.join([ 'WHEN "' + x + '" THEN ' + str(y) for x, y in [[sourceItems[i], sourceValues[i]] for i in range(0, len(sourceItems))] ]), maxDistance=self.dlg.maxDistanceSpinBox.value(), currentCRSID=currentCRSID) elif formulaType == 'Gaussian': sql = ''' with s as ( select *, case {landUseField} {caseStatment} end as value from {landUseLayer} where {landUseField} in ({sourceItems}) ), t as ( select * from {landUseLayer} where {landUseField} in ({targetItems}) ) SELECT AsWKT(st_ShortestLine(s.geom,t.geom)) as geomText ,t.fid as tfid,s.fid as sfid,t.{landUseField}, st_distance(s.geom,t.geom) as distance, s.value*((power(2.718281828459045235360287471352662497757247093699959574966,(((st_distance(s.geom,t.geom)/{maxDistance}) * (st_distance(s.geom,t.geom)/{maxDistance}) * -4) + 0.92)))/sqrt(6.283185307179586476925286766559005768394338798750211641949)) as computed FROM s,t where PtDistWithin(s.geom,t.geom,{maxDistance}) '''.format( landUseLayer="land_use", studyArea="study_area", landUseField=self.landUseSelectedField.name(), targetItems=', '.join([ '"' + str(x) + '"' for x in self.getTargetItems() ]), sourceItems=', '.join( ['"' + str(x) + '"' for x in sourceItems]), # sourceValues=', '.join( # [str(x) for x in sourceValues]), caseStatment=' '.join([ 'WHEN "' + x + '" THEN ' + str(y) for x, y in [[sourceItems[i], sourceValues[i]] for i in range(0, len(sourceItems))] ]), maxDistance=self.dlg.maxDistanceSpinBox.value(), currentCRSID=currentCRSID) elif analysisType == 'Bounding boxes': if formulaType == 'Linear': sql = ''' with s as ( select *, case {landUseField} {caseStatment} end as value, ST_Envelope(geom) as bbox from {landUseLayer} where {landUseField} in ({sourceItems}) ), t as ( select *, ST_Envelope(geom) as bbox from {landUseLayer} where {landUseField} in ({targetItems}) ) SELECT AsWKT(st_ShortestLine(s.bbox,t.bbox)) as geomText,AsWKT(s.bbox) as sbbox,AsWKT(t.bbox) as tbbox, t.fid as tfid,s.fid as sfid,t.{landUseField}, st_distance(s.bbox,t.bbox) as distance, CASE WHEN st_distance(s.bbox,t.bbox) = 0 then s.value WHEN st_distance(s.bbox,t.bbox)>0 then (1-(st_distance(s.bbox,t.bbox)/{maxDistance}))*s.value END as computed FROM s,t where PtDistWithin(s.bbox,t.bbox,{maxDistance}) '''.format( landUseLayer="land_use", studyArea="study_area", landUseField=self.landUseSelectedField.name(), targetItems=', '.join([ '"' + str(x) + '"' for x in self.getTargetItems() ]), sourceItems=', '.join( ['"' + str(x) + '"' for x in sourceItems]), # sourceValues=', '.join( # [str(x) for x in sourceValues]), caseStatment=' '.join([ 'WHEN "' + x + '" THEN ' + str(y) for x, y in [[sourceItems[i], sourceValues[i]] for i in range(0, len(sourceItems))] ]), maxDistance=self.dlg.maxDistanceSpinBox.value(), currentCRSID=currentCRSID) elif formulaType == 'Gaussian': sql = ''' with s as ( select *, case {landUseField} {caseStatment} end as value, ST_Envelope(geom) as bbox from {landUseLayer} where {landUseField} in ({sourceItems}) ), t as ( select *, ST_Envelope(geom) as bbox from {landUseLayer} where {landUseField} in ({targetItems}) ) SELECT AsWKT(st_ShortestLine(s.bbox,t.bbox)) as geomText,AsWKT(s.bbox) as sbbox,AsWKT(t.bbox) as tbbox,t.fid as tfid,s.fid as sfid,t.{landUseField}, st_distance(s.bbox,t.bbox) as distance, s.value*((power(2.718281828459045235360287471352662497757247093699959574966,(((st_distance(s.bbox,t.bbox)/{maxDistance}) * (st_distance(s.bbox,t.bbox)/{maxDistance}) * -4) + 0.92)))/sqrt(6.283185307179586476925286766559005768394338798750211641949)) as computed FROM s,t where PtDistWithin(s.bbox,t.bbox,{maxDistance}) '''.format( landUseLayer="land_use", studyArea="study_area", landUseField=self.landUseSelectedField.name(), targetItems=', '.join([ '"' + str(x) + '"' for x in self.getTargetItems() ]), sourceItems=', '.join( ['"' + str(x) + '"' for x in sourceItems]), # sourceValues=', '.join( # [str(x) for x in sourceValues]), caseStatment=' '.join([ 'WHEN "' + x + '" THEN ' + str(y) for x, y in [[sourceItems[i], sourceValues[i]] for i in range(0, len(sourceItems))] ]), maxDistance=self.dlg.maxDistanceSpinBox.value(), currentCRSID=currentCRSID) ResultSet = srcDataSource.ExecuteSQL(sql, dialect='SQLite') self.log('saving raw data') self.saveLayerIntoOgrPkg(ResultSet, srcDataSource, 'raw_data') ResultSet = None # progressMessageBar.setText('Extracting distance lines ...') # progress.setValue(80) self.log('Extracting lines') sql = ''' SELECT ST_GeomFromText(a.geomText,{currentCRSID}) as geom, a.tfid as tfid, a.distance as distance, a.geomText, a.sfid, a.{landUseField}, a.computed as computed_value FROM {rawData} as a where a.distance>0 '''.format(rawData="raw_data", currentCRSID=currentCRSID, landUseField=self.landUseSelectedField.name()) ResultSet = srcDataSource.ExecuteSQL(sql, dialect='SQLite') self.saveLayerIntoOgrPkg(ResultSet, srcDataSource, 'distance_lines') ResultSet = None self.log('Joinning poligons lines') # progressMessageBar.setText( # 'Agregating polygon computed values ...') # progress.setValue(80) sql = ''' select t.geom as geom, t.fid, sum(r.computed) as computed_value from {rawData} as r, {landUseLayer} as t where r.tfid=t.fid group by t.fid '''.format(rawData="raw_data", landUseLayer="land_use") ResultSet = srcDataSource.ExecuteSQL(sql, dialect='SQLite') self.saveLayerIntoOgrPkg(ResultSet, srcDataSource, 'computed_poligons') rasterResol = self.dlg.outputRasterSizeBox.value() # Prepare for Rasterize # progressMessageBar.setText('Rasterizing results') # progress.setValue(95) pixelWidth = pixelHeight = rasterResol x_min, x_max, y_min, y_max = ResultSet.GetExtent() cols = int((x_max - x_min) / pixelHeight) rows = int((y_max - y_min) / pixelWidth) rasterPath = os.path.join( outputFolder, self.timestamp + '_' + analysisType + '_' + formulaType + '_computed.tif') target_ds = gdal.GetDriverByName('GTiff').Create( rasterPath, cols, rows, 1, gdal.GDT_Float32) target_ds.SetGeoTransform( (x_min, pixelWidth, 0, y_min, 0, pixelHeight)) band = target_ds.GetRasterBand(1) band.FlushCache() band.SetNoDataValue(0) gdal.RasterizeLayer( target_ds, [1], ResultSet, options=['ATTRIBUTE=computed_value', 'noData=0']) target_dsSRS = osr.SpatialReference() target_dsSRS.ImportFromEPSG(currentCRSID) target_ds.SetProjection(target_dsSRS.ExportToWkt()) band.FlushCache() band = None target_ds = None self.log('Load datasets') path_to_gpkg = os.path.join( outputFolder, 'output_result_' + analysisType + '_' + formulaType + '_') + self.timestamp + '.gpkg' gpkg_distance_layer = path_to_gpkg + "|layername=distance_lines" gpkg_polygons_layer = path_to_gpkg + "|layername=computed_poligons" vlayer = iface.addVectorLayer(gpkg_polygons_layer, "Polygons", "ogr") if not vlayer: self.log("Layer Polygons failed to load!") vlayer = iface.addVectorLayer(gpkg_distance_layer, "Distance lines", "ogr") if not vlayer: self.log("Layer Distance Lines failed to load!") vlayer = None iface.addRasterLayer(rasterPath, "Computed Values") iface.messageBar().clearWidgets() self.log('Finalized')
def show_info(self, msg): QMessageBox.information(self.iface.mainWindow(), self.context, msg)
def charge_layer_sqlite(self, sito, area, us): cfg_rel_path = os.path.join(os.sep, 'HFF_DB_folder', 'config.cfg') file_path = '{}{}'.format(self.HOME, cfg_rel_path) conf = open(file_path, "r") con_sett = conf.read() conf.close() settings = Settings(con_sett) settings.set_configuration() sqliteDB_path = os.path.join(os.sep, 'HFF_DB_folder', settings.DATABASE) db_file_path = '{}{}'.format(self.HOME, sqliteDB_path) uri = QgsDataSourceUri() uri.setDatabase(db_file_path) #srs = QgsCoordinateReferenceSystem(self.SRS, QgsCoordinateReferenceSystem.PostgisCrsId) gidstr = "scavo_s = '%s' and area_s = '%s' and us_s = '%d'" % ( sito, area, us) #uri = QgsDataSourceUri() #uri.setDatabase(db_file_path) uri.setDataSource('', 'hff_system__us_view', 'the_geom', gidstr, "ROWID") self.layerUS = QgsVectorLayer(uri.uri(), 'hff_system__us_view', 'spatialite') if self.layerUS.isValid(): #self.layerUS.setCrs(srs) self.USLayerId = self.layerUS.id() # self.mapLayerRegistry.append(USLayerId) style_path = '{}{}'.format(self.LAYER_STYLE_PATH_SPATIALITE, 'us_view.qml') self.layerUS.loadNamedStyle(style_path) self.iface.mapCanvas().setExtent(self.layerUS.extent()) QgsProject.instance().addMapLayer(self.layerUS, True) else: QMessageBox.warning(None, "Errore", "Non Valido", QMessageBox.Ok) return 0 # QMessageBox.warning(self, "Messaggio", "Geometria inesistente", QMessageBox.Ok) gidstr = "sito_q = '%s' and area_q = '%s' and us_q = '%d'" % (sito, area, us) uri.setDataSource('', 'hff_system__quote_view', 'the_geom', gidstr, "ROWID") self.layerQuote = QgsVectorLayer(uri.uri(), 'hff_system__quote_view', 'spatialite') if self.layerQuote.isValid(): #self.layerQuote.setCrs(srs) self.QuoteLayerId = self.layerQuote.id() # self.mapLayerRegistry.append(QuoteLayerId) style_path = '{}{}'.format(self.LAYER_STYLE_PATH_SPATIALITE, 'stile_quote.qml') self.layerQuote.loadNamedStyle(style_path) QgsProject.instance().addMapLayer(self.layerQuote, True)
def setWarning(self, msg): QMessageBox.warning(None, 'Could not complete GeoGig command', msg, QMessageBox.Ok)
def __init__(self, conn, cursor, raster, max_size, progress_label): QObject.__init__(self) self.cursor = cursor self.conn = conn self.progress_label = progress_label self.messages = "" opts = {} opts['version'] = g_rt_version opts['endian'] = NDR opts['column'] = 'rast' opts['create_table'] = 1 opts['drop_table'] = 1 opts['overview_level'] = 1 opts['block_size'] = 'auto' opts['band'] = None opts['register'] = None # Create PostGIS Raster Tool Functions raster_tools_file = "%s/raster_tools.sql" % os.path.dirname(__file__) with open(raster_tools_file) as f: sql = f.read().encode('ascii', errors='ignore') f.close() self.cursor.execute(sql) self.conn.commit() i = 0 # Burn all specified input raster files into single WKTRaster table gt = None layer_info = raster opts['srid'] = layer_info['layer'].dataProvider().crs().postgisSrid() infile = layer_info['data_source'] file_info = QFileInfo(infile) file_size = file_info.size() size = DbConnections().db_size() file_size /= 1024 * 1024 size = size + file_size if size > float(max_size): QMessageBox.warning( None, self.tr("Database full"), self. tr("Upload would exceeded the maximum database size for your current QGIS Cloud plan. Please free up some space or upgrade your QGIS Cloud plan." )) return False opts['schema_table'] = "\"%s\".\"%s\"" % (layer_info['schema_name'], layer_info['table_name']) opts['table'] = layer_info['table_name'] opts['schema'] = layer_info['schema_name'] self.progress_label.setText( self.tr("Creating table '{table}'...").format( table=opts['schema_table'].replace('"', ''))) QApplication.processEvents() self.cursor.execute( self.make_sql_drop_raster_table(opts['schema_table'])) self.conn.commit() self.cursor.execute( self.make_sql_create_table(opts, opts['schema_table'])) self.conn.commit() gt = self.wkblify_raster(opts, infile.replace('\\', '/'), i, gt) i += 1 self.cursor.execute( self.make_sql_create_gist(opts['schema_table'], opts['column'])) self.conn.commit() # create raster overviews for level in [4, 8, 16, 32]: sql = 'drop table if exists "%s"."o_%d_%s"' % ( opts['schema'], level, opts['table']) self.cursor.execute(sql) self.conn.commit() sql = "select st_createoverview_qgiscloud('%s'::text, '%s'::name, %d)" % ( opts['schema_table'].replace('"', ''), opts['column'], level) self.progress_label.setText( self.tr( "Creating overview-level {level} for table '{table}'..."). format(level=level, table=opts['schema_table'].replace('"', ''))) QApplication.processEvents() self.cursor.execute(sql) self.conn.commit() index_table = opts['schema'] + '.o_' + str( level) + '_' + opts['table'] self.cursor.execute( self.make_sql_create_gist(index_table, opts['column'])) self.conn.commit() self.progress_label.setText( self.tr("Registering raster columns of table '%s'..." % (opts['schema_table'].replace('"', '')))) QApplication.processEvents() self.cursor.execute(self.make_sql_addrastercolumn(opts)) self.conn.commit()
def on_pushButton_search_go_pressed(self): if self.BROWSE_STATUS != "f": QMessageBox.warning( self, "ATTENZIONE", "Per eseguire una nuova ricerca clicca sul pulsante 'new search' ", QMessageBox.Ok) else: search_dict = { self.TABLE_FIELDS[0]: "'" + str(self.comboBox_nome_tabella.currentText()) + "'", # 1 - Nome tabella self.TABLE_FIELDS[1]: "'" + str(self.comboBox_sigla.currentText()) + "'", # 2 - sigla self.TABLE_FIELDS[2]: "'" + str(self.comboBox_sigla_estesa.currentText()) + "'", # 3 - sigla estesa self.TABLE_FIELDS[4]: "'" + str(self.comboBox_tipologia_sigla.currentText()) + "'" # 3 - tipologia sigla } u = Utility() search_dict = u.remove_empty_items_fr_dict(search_dict) if not bool(search_dict): QMessageBox.warning( self, "ATTENZIONE", "Non e' stata impostata alcuna ricerca!!!", QMessageBox.Ok) else: res = self.DB_MANAGER.query_bool(search_dict, self.MAPPER_TABLE_CLASS) if not bool(res): QMessageBox.warning(self, "ATTENZIONE", "Non e' stato trovato alcun record!", QMessageBox.Ok) self.set_rec_counter(len(self.DATA_LIST), self.REC_CORR + 1) self.DATA_LIST_REC_TEMP = self.DATA_LIST_REC_CORR = self.DATA_LIST[ 0] self.fill_fields(self.REC_CORR) self.BROWSE_STATUS = "b" self.label_status.setText( self.STATUS_ITEMS[self.BROWSE_STATUS]) self.setComboBoxEditable(["self.comboBox_sigla"], 1) self.setComboBoxEditable(["self.comboBox_sigla_estesa"], 1) self.setComboBoxEditable(["self.comboBox_tipologia_sigla"], 1) self.setComboBoxEditable(["self.comboBox_nome_tabella"], 1) self.setComboBoxEnable(["self.comboBox_sigla"], "False") self.setComboBoxEnable(["self.comboBox_sigla_estesa"], "False") self.setComboBoxEnable(["self.comboBox_tipologia_sigla"], "False") self.setComboBoxEnable(["self.comboBox_nome_tabella"], "False") self.setComboBoxEnable(["self.textEdit_descrizione_sigla"], "True") else: self.DATA_LIST = [] for i in res: self.DATA_LIST.append(i) self.REC_TOT, self.REC_CORR = len(self.DATA_LIST), 0 self.DATA_LIST_REC_TEMP = self.DATA_LIST_REC_CORR = self.DATA_LIST[ 0] self.fill_fields() self.BROWSE_STATUS = "b" self.label_status.setText( self.STATUS_ITEMS[self.BROWSE_STATUS]) self.set_rec_counter(len(self.DATA_LIST), self.REC_CORR + 1) if self.REC_TOT == 1: strings = ("E' stato trovato", self.REC_TOT, "record") else: strings = ("Sono stati trovati", self.REC_TOT, "records") self.setComboBoxEditable(["self.comboBox_sigla"], 1) self.setComboBoxEditable( ["self.comboBox_sigla_estesa"], 1) self.setComboBoxEditable( ["self.comboBox_tipologia_sigla"], 1) self.setComboBoxEditable( ["self.comboBox_nome_tabella"], 1) self.setComboBoxEnable(["self.comboBox_sigla"], "False") self.setComboBoxEnable(["self.comboBox_sigla_estesa"], "False") self.setComboBoxEnable( ["self.comboBox_tipologia_sigla"], "False") self.setComboBoxEnable(["self.comboBox_nome_tabella"], "False") self.setComboBoxEnable( ["self.textEdit_descrizione_sigla"], "True") QMessageBox.warning(self, "Messaggio", "%s %d %s" % strings, QMessageBox.Ok) self.enable_button_search(1)
def about(self): infoString = "Written by Richard Duivenvoorde\nEmail - [email protected]\n" infoString += "Company - Zuidt - http://www.zuidt.nl\n" infoString += "Source: https://github.com/rduivenvoorde/pdokservicesplugin" QMessageBox.information(self.iface.mainWindow(), "Pdok Services Plugin About", infoString)
def loadService(self): if self.currentLayer == None: return servicetype = self.currentLayer['type'] url = self.currentLayer['url'] # some services have an url with query parameters in it, we have to urlencode those: location,query = urllib.parse.splitquery(url) url = location # RD: 20200820: lijkt of het quoten van de query problemen geeft bij WFS, is/was dit nodig??? #if query != None and query != '': # url +=('?'+urllib.parse.quote_plus(query)) title = self.currentLayer['title'] if 'style' in self.currentLayer: style = self.currentLayer['style'] title = title + ' [' + style + ']' else: style = '' # == default for this service layers = self.currentLayer['layers'] # mmm, tricky: we take the first one while we can actually want png/gif or jpeg if servicetype == "wms": imgformat = self.currentLayer['imgformats'].split(',')[0] if self.dlg.ui.comboSelectProj.currentIndex() == -1: crs = 'EPSG:28992' else: crs = self.dlg.ui.comboSelectProj.currentText() if Qgis.QGIS_VERSION_INT < 10900: # qgis <= 1.8 uri = url self.iface.addRasterLayer( uri, # service uri title, # name for layer (as seen in QGIS) "wms", # dataprovider key [layers], # array of layername(s) for provider (id's) [""], # array of stylename(s) NOTE: ignoring styles here!!! imgformat, # image format searchstring crs) # crs code searchstring else: # qgis > 1.8 uri = "crs="+crs+"&layers="+layers+"&styles="+style+"&format="+imgformat+"&url="+url; self.iface.addRasterLayer(uri, title, "wms") elif servicetype == "wmts": if Qgis.QGIS_VERSION_INT < 10900: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ("Sorry, dit type layer: '"+servicetype.upper()+"' \nkan niet worden geladen in deze versie van QGIS.\nMisschien kunt u QGIS 2.0 installeren (die kan het WEL)?\nOf is de laag niet ook beschikbaar als wms of wfs?"), QMessageBox.Ok, QMessageBox.Ok) return if self.dlg.ui.comboSelectProj.currentIndex() == -1: tilematrixset = 'EPSG:28992' else: tilematrixset = self.dlg.ui.comboSelectProj.currentText() imgformat = self.currentLayer['imgformats'].split(',')[0] # special case for luchtfoto #if layers=="luchtfoto": # # tileMatrixSet=nltilingschema&crs=EPSG:28992&layers=luchtfoto&styles=&format=image/jpeg&url=http://geodata1.nationaalgeoregister.nl/luchtfoto/wmts/1.0.0/WMTSCapabilities.xml # # {u'layers': u'luchtfoto', u'imgformats': u'image/jpeg', u'title': u'PDOK-achtergrond luchtfoto', u'url': u'http://geodata1.nationaalgeoregister.nl/luchtfoto/wms', u'abstract': u'', u'tilematrixsets': u'nltilingschema', u'type': u'wmts'} # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url #else: # uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=&format="+imgformat+"&url="+url; #uri = "tileMatrixSet="+tilematrixsets+"&crs=EPSG:28992&layers="+layers+"&styles=default&format="+imgformat+"&url="+url; if tilematrixset.startswith('EPSG:'): crs=tilematrixset i = crs.find(':', 5) if i > -1: crs=crs[:i] elif tilematrixset.startswith('OGC:1.0'): crs='EPSG:3857' uri = "tileMatrixSet="+tilematrixset+"&crs="+crs+"&layers="+layers+"&styles=default&format="+imgformat+"&url="+url; #print "############ PDOK URI #################" #print uri self.iface.addRasterLayer(uri, title, "wms") elif servicetype == "wfs": location, query = urllib.parse.splitquery(url) #uri = location+"?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetFeature&TYPENAME="+layers+"&SRSNAME=EPSG:28992" #uri = location + "?SERVICE=WFS&REQUEST=GetFeature&TYPENAME=" + layers + "&SRSNAME=EPSG:28992" # adding a bbox paramater forces QGIS to NOT cache features but retrieve new features all the time # QGIS will update the BBOX to the right value #uri += "&BBOX=-10000,310000,290000,650000" uri = " pagingEnabled='true' restrictToRequestBBOX='1' srsname='EPSG:28992' typename='"+layers+"' url='"+url+"' version='2.0.0' " self.iface.addVectorLayer(uri, title, "WFS") elif servicetype == "wcs": # cache=AlwaysCache&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs uri = '' # cache=AlwaysCache # cache=PreferNetwork # cache=AlwaysNetwork # cache=AlwaysNetwork&crs=EPSG:28992&format=GeoTIFF&identifier=ahn25m:ahn25m&url=http://geodata.nationaalgeoregister.nl/ahn25m/wcs #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=image/tiff&version=1.1.1&identifier="+layers+"&url="+url # working for ahn1 ahn2 and ahn3: GEOTIFF_FLOAT32 format = 'GEOTIFF_FLOAT32' # working for ahn25m is only image/tiff if layers=='ahn25m': format = 'image/tiff' # we handcrated some wcs layers with 2 different image formats: tiff (RGB) and tiff (float32): if 'imgformats' in self.currentLayer: format = self.currentLayer['imgformats'].split(',')[0] uri = "cache=AlwaysNetwork&crs=EPSG:28992&format="+format+"&identifier=" + layers + "&url=" + url #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format="+format+"&version=1.1.2&identifier=" + layers + "&url=" + url #uri = "cache=AlwaysNetwork&crs=EPSG:28992&format=image/tiff&version=1.1.2&identifier=" + layers + "&url=" + url self.iface.addRasterLayer(uri, title, "wcs") else: QMessageBox.warning(self.iface.mainWindow(), "PDOK plugin", ("Sorry, dit type layer: '"+servicetype.upper()+"' \nkan niet worden geladen door de plugin of door QGIS.\nIs het niet beschikbaar als wms, wmts of wfs?"), QMessageBox.Ok, QMessageBox.Ok) return
def accept(self): # sanity checks if self.editOutputFile.text() == "": QMessageBox.information(self, self.tr("Export to file"), self.tr("Output file name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = int(self.editSourceSrid.text()) except ValueError: QMessageBox.information( self, self.tr("Export to file"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = int(self.editTargetSrid.text()) except ValueError: QMessageBox.information( self, self.tr("Export to file"), self.tr("Invalid target srid: must be an integer")) return with OverrideCursor(Qt.WaitCursor): # store current input layer crs, so I can restore it later prevInCrs = self.inLayer.crs() try: uri = self.editOutputFile.text() providerName = "ogr" options = {} # set the OGR driver will be used driverName = self.cboFileFormat.currentData() options['driverName'] = driverName # set the output file encoding if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked( ): enc = self.cboEncoding.currentText() options['fileEncoding'] = enc if self.chkDropTable.isChecked(): options['overwrite'] = True outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled( ) and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) # update input layer crs if self.chkSourceSrid.isEnabled( ) and self.chkSourceSrid.isChecked(): sourceSrid = int(self.editSourceSrid.text()) inCrs = QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) # do the export! ret, errMsg = QgsVectorLayerExporter.exportLayer( self.inLayer, uri, providerName, outCrs, False, options) except Exception as e: ret = -1 errMsg = str(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) if ret != 0: QMessageBox.warning(self, self.tr("Export to file"), self.tr("Error {0}\n{1}").format(ret, errMsg)) return # create spatial index # if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): # self.db.connector.createSpatialIndex( (schema, table), geom ) QMessageBox.information(self, self.tr("Export to file"), self.tr("Export finished.")) return QDialog.accept(self)
def convert(self): """ Convert the project to a portable project. :param offline_editing: The offline editing instance :param export_folder: The folder to export to """ project = QgsProject.instance() original_project = project original_project_path = project.fileName() project_filename, _ = os.path.splitext(os.path.basename(original_project_path)) # Write a backup of the current project to a temporary file project_backup_folder = tempfile.mkdtemp() backup_project_path = os.path.join(project_backup_folder, project_filename + '.qgs') QgsProject.instance().write(backup_project_path) try: if not os.path.exists(self.export_folder): os.makedirs(self.export_folder) QApplication.setOverrideCursor(Qt.WaitCursor) self.__offline_layers = list() self.__layers = list(project.mapLayers().values()) original_layer_info = {} for layer in self.__layers: original_layer_info[layer.id()] = (layer.source(), layer.name()) self.total_progress_updated.emit(0, 1, self.trUtf8('Creating base map…')) # Create the base map before layers are removed if self.project_configuration.create_base_map: if 'processing' not in qgis.utils.plugins: QMessageBox.warning(None, self.tr('QFieldSync requires processing'), self.tr('Creating a basemap with QFieldSync requires the processing plugin to be enabled. Processing is not enabled on your system. Please go to Plugins > Manage and Install Plugins and enable processing.')) return if self.project_configuration.base_map_type == ProjectProperties.BaseMapType.SINGLE_LAYER: self.createBaseMapLayer(None, self.project_configuration.base_map_layer, self.project_configuration.base_map_tile_size, self.project_configuration.base_map_mupp) else: self.createBaseMapLayer(self.project_configuration.base_map_theme, None, self.project_configuration.base_map_tile_size, self.project_configuration.base_map_mupp) # Loop through all layers and copy/remove/offline them pathResolver = QgsProject.instance().pathResolver() copied_files = list() for current_layer_index, layer in enumerate(self.__layers): self.total_progress_updated.emit(current_layer_index - len(self.__offline_layers), len(self.__layers), self.trUtf8('Copying layers…')) layer_source = LayerSource(layer) if not layer_source.is_supported: project.removeMapLayer(layer) continue if layer.dataProvider() is not None: md = QgsProviderRegistry.instance().providerMetadata(layer.dataProvider().name()) if md is not None: decoded = md.decodeUri(layer.source()) if "path" in decoded: path = pathResolver.writePath(decoded["path"]) if path.startswith("localized:"): # Layer stored in localized data path, skip continue if layer_source.action == SyncAction.OFFLINE: if self.project_configuration.offline_copy_only_aoi: layer.selectByRect(self.extent) self.__offline_layers.append(layer) elif layer_source.action == SyncAction.NO_ACTION: copied_files = layer_source.copy(self.export_folder, copied_files) elif layer_source.action == SyncAction.KEEP_EXISTENT: layer_source.copy(self.export_folder, copied_files, True) elif layer_source.action == SyncAction.REMOVE: project.removeMapLayer(layer) project_path = os.path.join(self.export_folder, project_filename + "_qfield.qgs") # save the original project path ProjectConfiguration(project).original_project_path = original_project_path # save the offline project twice so that the offline plugin can "know" that it's a relative path QgsProject.instance().write(project_path) # export the DCIM folder copy_images(os.path.join(os.path.dirname(original_project_path), "DCIM"), os.path.join(os.path.dirname(project_path), "DCIM")) try: # Run the offline plugin for gpkg gpkg_filename = "data.gpkg" if self.__offline_layers: offline_layer_ids = [l.id() for l in self.__offline_layers] if not self.offline_editing.convertToOfflineProject(self.export_folder, gpkg_filename, offline_layer_ids, self.project_configuration.offline_copy_only_aoi, self.offline_editing.GPKG): raise Exception(self.tr("Error trying to convert layers to offline layers")) except AttributeError: # Run the offline plugin for spatialite spatialite_filename = "data.sqlite" if self.__offline_layers: offline_layer_ids = [l.id() for l in self.__offline_layers] if not self.offline_editing.convertToOfflineProject(self.export_folder, spatialite_filename, offline_layer_ids, self.project_configuration.offline_copy_only_aoi): raise Exception(self.tr("Error trying to convert layers to offline layers")) # Disable project options that could create problems on a portable # project with offline layers if self.__offline_layers: QgsProject.instance().setEvaluateDefaultValues(False) QgsProject.instance().setAutoTransaction(False) # check if value relations point to offline layers and adjust if necessary for layer in project.mapLayers().values(): if layer.type() == QgsMapLayer.VectorLayer: for field in layer.fields(): ews = field.editorWidgetSetup() if ews.type() == 'ValueRelation': widget_config = ews.config() online_layer_id = widget_config['Layer'] if project.mapLayer(online_layer_id): continue layer_id = None loose_layer_id = None for offline_layer in project.mapLayers().values(): if offline_layer.customProperty('remoteSource') == original_layer_info[online_layer_id][0]: # First try strict matching: the offline layer should have a "remoteSource" property layer_id = offline_layer.id() break elif offline_layer.name().startswith(original_layer_info[online_layer_id][1] + ' '): # If that did not work, go with loose matching # The offline layer should start with the online layer name + a translated version of " (offline)" loose_layer_id = offline_layer.id() widget_config['Layer'] = layer_id or loose_layer_id offline_ews = QgsEditorWidgetSetup(ews.type(), widget_config) layer.setEditorWidgetSetup(layer.fields().indexOf(field.name()), offline_ews) # Now we have a project state which can be saved as offline project QgsProject.instance().write(project_path) finally: # We need to let the app handle events before loading the next project or QGIS will crash with rasters QCoreApplication.processEvents() QgsProject.instance().clear() QCoreApplication.processEvents() QgsProject.instance().read(backup_project_path) QgsProject.instance().setFileName(original_project_path) QApplication.restoreOverrideCursor() self.offline_editing.layerProgressUpdated.disconnect(self.on_offline_editing_next_layer) self.offline_editing.progressModeSet.disconnect(self.on_offline_editing_max_changed) self.offline_editing.progressUpdated.disconnect(self.offline_editing_task_progress) self.total_progress_updated.emit(100, 100, self.tr('Finished'))
def veureInfo(self): if self.info is not None: box = QMessageBox(self) box.setWindowTitle('Info del mapa simbòlic') txt = '<table width="600">' params = self.info.split('\n') for param in params: linea = param.strip() if linea.endswith(':'): linea += ' ---' txt += '<tr><td><nobr>· {}</nobr></td></tr>'.format(linea) txt += '</table>' box.setTextFormat(Qt.RichText) box.setText("Paràmetres d'agregació de dades:") box.setInformativeText(txt) box.setIcon(QMessageBox.Information) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) box.exec()
try: import visvis except Exception as e: missing_libraries.append(str(e)) install_libraries = [] for l in missing_libraries: p = re.findall(r"'(.*?)'", l) install_libraries.append(p[0]) if install_libraries: from qgis.PyQt.QtWidgets import QMessageBox res = QMessageBox.warning( None, 'PyArchInit', "Some of the required packages are missing from your machine:\n{}\n\n" "Do you want install the missing packages?".format( ',\n'.join(missing_libraries)), QMessageBox.Ok | QMessageBox.Cancel) if res == QMessageBox.Ok: import subprocess try: cmd = 'python3' subprocess.call( [ cmd, '{}'.format( os.path.join(os.path.dirname(__file__), 'scripts', 'modules_installer.py')), ','.join(install_libraries) ], shell=True if Pyarchinit_OS_Utility.isWindows() else False)
def msgAvis(self, txt): QMessageBox.warning(self, 'Avís', txt)
def msgError(self, txt): QMessageBox.critical(self, 'Error', txt)
def __init__(self): """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """ QObject.__init__( self) # initialize QObject in order to to use self.tr() repositories.load() plugins.getAllInstalled() if repositories.checkingOnStart() and repositories.timeForChecking( ) and repositories.allEnabled(): # start fetching repositories self.statusLabel = QLabel( self.tr("Looking for new plugins...") + " ", iface.mainWindow().statusBar()) iface.mainWindow().statusBar().insertPermanentWidget( 0, self.statusLabel) self.statusLabel.linkActivated.connect( self.showPluginManagerWhenReady) repositories.checkingDone.connect(self.checkingDone) for key in repositories.allEnabled(): repositories.requestFetching(key) else: # no fetching at start, so mark all enabled repositories as requesting to be fetched. for key in repositories.allEnabled(): repositories.setRepositoryData(key, "state", 3) # look for obsolete plugins (the user-installed one is newer than core one) for key in plugins.obsoletePlugins: plugin = plugins.localCache[key] msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setWindowTitle(self.tr("QGIS Python Plugin Installer")) msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole) msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole) msg.setText("%s <b>%s</b><br/><br/>%s" % ( self.tr("Obsolete plugin:"), plugin["name"], self. tr("QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?" ))) msg.exec_() if not msg.result(): # uninstall, update utils and reload if enabled self.uninstallPlugin(key, quiet=True) updateAvailablePlugins() settings = QSettings() if settings.value("/PythonPlugins/" + key, False, type=bool): settings.setValue("/PythonPlugins/watchDog/" + key, True) loadPlugin(key) startPlugin(key) settings.remove("/PythonPlugins/watchDog/" + key)
def msgContinuarProces(self, txt): QApplication.instance().restoreOverrideCursor() res = QMessageBox.question(self, 'Atenció', txt + "\n\nVol continuar?") QApplication.instance().setOverrideCursor(Qt.WaitCursor) return res == QMessageBox.Yes
def error(self, text): QMessageBox.critical(self, "Error", text) QgsMessageLog.logMessage(text, self.tr('Processing'), Qgis.Critical)
def clearTable(self, removeAll=False): res = QMessageBox.question( self, self.tr('Clear?'), self.tr('Are you sure you want to clear table?')) if res == QMessageBox.Yes: self.tblView.model().clear()
def installPlugin(self, key, quiet=False): """ Install given plugin """ error = False infoString = ('', '') plugin = plugins.all()[key] previousStatus = plugin["status"] if not plugin: return if plugin["status"] == "newer" and not plugin[ "error"]: # ask for confirmation if user downgrades an usable plugin if QMessageBox.warning( iface.mainWindow(), self.tr("QGIS Python Plugin Installer"), self. tr("Are you sure you want to downgrade the plugin to the latest available version? The installed one is newer!" ), QMessageBox.Yes, QMessageBox.No) == QMessageBox.No: return dlg = QgsPluginInstallerInstallingDialog(iface.mainWindow(), plugin) dlg.exec_() if dlg.result(): error = True infoString = (self.tr("Plugin installation failed"), dlg.result()) elif not QDir(qgis.utils.home_plugin_path + "/" + key).exists(): error = True infoString = ( self.tr("Plugin has disappeared"), self. tr("The plugin seems to have been installed but I don't know where. Probably the plugin package contained a wrong named directory.\nPlease search the list of installed plugins. I'm nearly sure you'll find the plugin there, but I just can't determine which of them it is. It also means that I won't be able to determine if this plugin is installed and inform you about available updates. However the plugin may work. Please contact the plugin author and submit this issue." )) QApplication.setOverrideCursor(Qt.WaitCursor) plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() QApplication.restoreOverrideCursor() else: QApplication.setOverrideCursor(Qt.WaitCursor) # update the list of plugins in plugin handling routines updateAvailablePlugins() # try to load the plugin loadPlugin(plugin["id"]) plugins.getAllInstalled(testLoad=True) plugins.rebuild() plugin = plugins.all()[key] if not plugin["error"]: if previousStatus in ["not installed", "new"]: infoString = (self.tr("Plugin installed successfully"), "") if startPlugin(plugin["id"]): settings = QSettings() settings.setValue("/PythonPlugins/" + plugin["id"], True) else: settings = QSettings() if settings.value( "/PythonPlugins/" + key, False, type=bool ): # plugin will be reloaded on the fly only if currently loaded reloadPlugin( key) # unloadPlugin + loadPlugin + startPlugin infoString = ( self.tr("Plugin reinstalled successfully"), "") else: unloadPlugin( key ) # Just for a case. Will exit quietly if really not loaded loadPlugin(key) infoString = ( self.tr("Plugin reinstalled successfully"), self. tr("Python plugin reinstalled.\nYou need to restart QGIS in order to reload it." )) if quiet: infoString = (None, None) QApplication.restoreOverrideCursor() else: QApplication.restoreOverrideCursor() if plugin["error"] == "incompatible": message = self.tr( "The plugin is not compatible with this version of QGIS. It's designed for QGIS versions:" ) message += " <b>" + plugin["error_details"] + "</b>" elif plugin["error"] == "dependent": message = self.tr( "The plugin depends on some components missing on your system. You need to install the following Python module in order to enable it:" ) message += "<b> " + plugin["error_details"] + "</b>" else: message = self.tr("The plugin is broken. Python said:") message += "<br><b>" + plugin["error_details"] + "</b>" dlg = QgsPluginInstallerPluginErrorDialog( iface.mainWindow(), message) dlg.exec_() if dlg.result(): # revert installation pluginDir = qgis.utils.home_plugin_path + "/" + plugin["id"] result = removeDir(pluginDir) if QDir(pluginDir).exists(): error = True infoString = (self.tr("Plugin uninstall failed"), result) try: exec("sys.path_importer_cache.clear()") exec("import %s" % plugin["id"]) exec("reload (%s)" % plugin["id"]) except: pass else: try: exec("del sys.modules[%s]" % plugin["id"]) except: pass plugins.getAllInstalled() plugins.rebuild() self.exportPluginsToManager() if infoString[0]: level = error and QgsMessageBar.CRITICAL or QgsMessageBar.INFO msg = "<b>%s:</b>%s" % (infoString[0], infoString[1]) iface.pluginManagerInterface().pushMessage(msg, level)
def showWarning(msg): QMessageBox.information(iface.mainWindow(), 'Warning', msg)