def display_information_message_bar( title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8): """ Display an information message bar. :param title: The title of the message bar. :type title: str :param message: The message inside the message bar. :type message: str :param more_details: The message inside the 'Show details' button. :type more_details: str :param button_text: The text of the button if 'more_details' is not empty. :type button_text: str :param duration: The duration for the display, default is 8 seconds. :type duration: int """ widget = iface.messageBar().createMessage(title, message) if more_details: button = QPushButton(widget) button.setText(button_text) button.pressed.connect( lambda: display_information_message_box( title=title, message=more_details)) widget.layout().addWidget(button) iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, duration)
def updateStyle(): url = getTrackingInfo(layer) catalog = Catalog(url) wrapper = CatalogWrapper(catalog) wrapper.publishStyle(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer()
def applyProfile(profile, defaultProfile): if profile.menus is None: applyMenus(defaultProfile) if profile.buttons is None: applyButtons(defaultProfile) if profile.panels is None: applyPanels(defaultProfile) if profile.plugins is None: applyPlugins(defaultProfile) pluginErrors = applyPlugins(profile) applyMenus(profile) applyButtons(profile) applyPanels(profile) rearrangeToolbars(profile.name) if pluginErrors: widget = iface.messageBar().createMessage("Error", tr('Profile {} has been applied with errors'.format(profile.name))) showButton = QPushButton(widget) showButton.setText("View more") def showMore(): dlg = QgsMessageOutput.createMessageOutput() dlg.setTitle('Profile errors') dlg.setMessage("<br><br>".join(pluginErrors), QgsMessageOutput.MessageHtml) dlg.showMessage() showButton.pressed.connect(showMore) widget.layout().addWidget(showButton) iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING, duration = 5) else: iface.messageBar().pushMessage(tr('Profiles'), tr('Profile {} has been correctly applied'.format(profile.name)), level=QgsMessageBar.INFO, duration=5)
def prepareAlgorithm(self, alg): algInstance = alg.algorithm() for param in algInstance.parameterDefinitions(): if not param.flags() & QgsProcessingParameterDefinition.FlagHidden: if param.name() in alg.params: value = self.resolveValue(alg.params[param.name()], param) else: if iface is not None: iface.messageBar().pushMessage(self.tr("Warning"), self.tr("Parameter {0} in algorithm {1} in the model is run with default value! Edit the model to make sure that this is correct.").format(param.name(), alg.displayName()), QgsMessageBar.WARNING, 4) value = param.defaultValue() # note to self - these are parameters, not outputs for out in algInstance.outputDefinitions(): if not out.flags() & QgsProcessingParameterDefinition.FlagHidden: if out.name() in alg.outputs: name = self.getSafeNameForOutput(alg.childId(), out.name()) modelOut = self.getOutputFromName(name) if modelOut: out.value = modelOut.value else: out.value = None return algInstance
def get_layers(self, resource=None): """Prefix the layer name with ws name""" lyrs = super().get_layers(resource) # Start patch: layers = {} result = [] for l in lyrs: try: layers[l.name].append(l) except KeyError: layers[l.name] = [l] # Prefix all names noAscii = False for name, ls in list(layers.items()): try: if len(ls) == 1: l = ls[0] l.name = self.get_namespaced_name(l.name) result.append(l) else: i = 0 res = self._get_res(ls[0].name) for l in ls: l.name = "%s:%s" % (res[i].workspace.name, l.name) i += 1 result.append(l) except UnicodeDecodeError: noAscii = True if noAscii: iface.messageBar().pushMessage("Warning", "Some layers contain non-ascii characters and could not be loaded", level = QgsMessageBar.WARNING, duration = 10) return result
def useLayerExtent(self): CANVAS_KEY = "Use canvas extent" extentsDict = {} extentsDict[CANVAS_KEY] = { "extent": iface.mapCanvas().extent(), "authid": iface.mapCanvas().mapSettings().destinationCrs().authid(), } extents = [CANVAS_KEY] layers = dataobjects.getAllLayers() for layer in layers: authid = layer.crs().authid() if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) and authid is not None: layerName = u"{} [{}]".format(layer.name(), authid) else: layerName = layer.name() extents.append(layerName) extentsDict[layerName] = {"extent": layer.extent(), "authid": authid} (item, ok) = QInputDialog.getItem(self, self.tr("Select extent"), self.tr("Use extent from"), extents, False) if ok: self.setValueFromRect(extentsDict[item]["extent"]) if extentsDict[item]["authid"] != iface.mapCanvas().mapSettings().destinationCrs().authid(): iface.messageBar().pushMessage( self.tr("Warning"), self.tr( "The projection of the chosen layer is not the same as canvas projection! The selected extent might not be what was intended." ), QgsMessageBar.WARNING, 8, )
def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) mgrsCoord = self.toMgrs(pt) if mgrsCoord: clipboard = QApplication.clipboard() clipboard.setText(mgrsCoord) iface.messageBar().pushMessage("", "Coordinate %s copied to clipboard" % mgrsCoord, level=QgsMessageBar.INFO, duration=3)
def loadConfiguration(self): ''' Function to load last conf get from settings ''' if not self.project: return # from th eproject, get JSON filename to load currentVehicleClassesJson = self.project.value('/FleetComposition/fleetComposition', self.gui.defaultVehicleClassesFileName) # check if json is relative path or absolute if not os.path.isabs(currentVehicleClassesJson): currentVehicleClassesJson = os.path.join(self.projectPath, currentVehicleClassesJson) # load json conf try: with open(currentVehicleClassesJson) as confFile: # loaded in and OrderedDict to allow maintaining the order of classes # contained in the json file. This will be reflected in the order # shown in the sunburst visualization/editor self.vehicleClassesDict = json.load(confFile, object_pairs_hook=collections.OrderedDict) self.configurationLoaded.emit(True) except Exception as ex: self.vehicleClassesDict = None QgsMessageLog.logMessage(traceback.format_exc(), 'QTraffic', QgsMessageLog.CRITICAL) iface.messageBar().pushMessage(self.tr("Error loading Conf JSON file. Please check the log"), QgsMessageBar.CRITICAL) return
def OeQ_pop_status(): global OeQ_StatusWidget if bool(OeQ_StatusWidget): try: iface.messageBar().popWidget(OeQ_StatusWidget) except: pass
def prepareAlgorithm(self, alg): algInstance = alg.algorithm for param in algInstance.parameterDefinitions(): if not param.flags() & QgsProcessingParameterDefinition.FlagHidden: if param.name() in alg.params: value = self.resolveValue(alg.params[param.name()], param) else: if iface is not None: iface.messageBar().pushMessage(self.tr("Warning"), self.tr("Parameter {0} in algorithm {1} in the model is run with default value! Edit the model to make sure that this is correct.").format(param.name(), alg.displayName()), QgsMessageBar.WARNING, 4) value = param.defaultValue() # We allow unexistent filepaths, since that allows # algorithms to skip some conversion routines # TODO #if not param.checkValueIsAcceptable(value) and not isinstance(param, # ParameterDataObject): # raise GeoAlgorithmExecutionException( # self.tr('Wrong value {0} for {1} {2}', 'ModelerAlgorithm').format( # value, param.__class__.__name__, param.name() # ) # ) for out in algInstance.outputs: if not out.flags() & QgsProcessingParameterDefinition.FlagHidden: if out.name() in alg.outputs: name = self.getSafeNameForOutput(alg.modeler_name, out.name()) modelOut = self.getOutputFromName(name) if modelOut: out.value = modelOut.value else: out.value = None return algInstance
def exportVectorLayer(layer): '''accepts a QgsVectorLayer or a string with a filepath''' settings = QtCore.QSettings() systemEncoding = settings.value( "/UI/encoding", "System" ) if isinstance(layer, QgsMapLayer): filename = unicode(layer.source()) destFilename = unicode(layer.name()) else: filename = unicode(layer) destFilename = unicode(os.path.splitext(os.path.basename(filename))[0]) if (not filename.lower().endswith("shp")): if not isinstance(layer, QgsMapLayer): layer = QgsVectorLayer(filename, "layer", "ogr") if not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer: raise Exception ("Error reading file {} or it is not a valid vector layer file".format(filename)) output = utils.tempFilenameInTempFolder(destFilename + ".shp") provider = layer.dataProvider() writer = QgsVectorFileWriter(output, systemEncoding, layer.pendingFields(), provider.geometryType(), layer.crs() ) for feat in layer.getFeatures(): writer.addFeature(feat) del writer iface.messageBar().pushMessage("Warning", "Layer had to be exported to shapefile for importing. Data might be lost.", level = QgsMessageBar.WARNING, duration = 5) return output else: return filename
def mergeInto(self, mergeInto, branch): conflicts = self.repo.merge(branch, mergeInto) if conflicts: ret = QMessageBox.warning(iface.mainWindow(), "Conflict(s) found while syncing", "There are conflicts between local and remote changes.\n" "Do you want to continue and fix them?", QMessageBox.Yes | QMessageBox.No) if ret == QMessageBox.No: self.repo.closeTransaction(conflicts[0].transactionId) return dlg = ConflictDialog(conflicts) dlg.exec_() solved, resolvedConflicts = dlg.solved, dlg.resolvedConflicts if not solved: self.repo.closeTransaction(conflicts[0].transactionId) return for conflict, resolution in zip(conflicts, list(resolvedConflicts.values())): if resolution == ConflictDialog.LOCAL: conflict.resolveWithLocalVersion() elif resolution == ConflictDialog.REMOTE: conflict.resolveWithRemoteVersion() elif resolution == ConflictDialog.DELETE: conflict.resolveDeletingFeature() else: conflict.resolveWithNewFeature(resolution) user, email = config.getUserInfo() if user is None: return self.repo.commitAndCloseMergeAndTransaction(user, email, "Resolved merge conflicts", conflicts[0].transactionId) iface.messageBar().pushMessage("GeoGig", "Branch has been correctly merged", level=QgsMessageBar.INFO, duration=5) repoWatcher.repoChanged.emit(self.repo)
def updatePublishedStyle(layer): global _currentMessageBarLayer track = pluginSetting("TrackLayers") if track and isTrackedLayer(layer): if iface.messageBar().currentItem() is None: _resetCurrentMessageBarLayer() if _currentMessageBarLayer != layer: _currentMessageBarLayer = layer widget = iface.messageBar().createMessage("", "This layer was uploaded to a geoserver catalog. Do you want to update the published style?") updateButton = QtWidgets.QPushButton(widget) updateButton.setText("Update") def updateStyle(): url = getTrackingInfo(layer) catalog = Catalog(url) wrapper = CatalogWrapper(catalog) wrapper.publishStyle(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() updateButton.pressed.connect(updateStyle) widget.layout().addWidget(updateButton) stopTrackingButton = QtWidgets.QPushButton(widget) stopTrackingButton.setText("Stop tracking this layer") def stopTracking(): removeTrackedLayer(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() stopTrackingButton.pressed.connect(stopTracking) widget.layout().addWidget(stopTrackingButton) iface.messageBar().pushWidget(widget, Qgis.Info) iface.messageBar().currentItem().geoserverLayer = layer
def prepareAlgorithm(self, alg): algInstance = alg.algorithm for param in algInstance.parameters: if not param.hidden: if param.name in alg.params: value = self.resolveValue(alg.params[param.name], param) else: if iface is not None: iface.messageBar().pushMessage(self.tr("Warning"), self.tr("Parameter %s in algorithm %s in the model is run with default value! Edit the model to make sure that this is correct.") % (param.name, alg.name), QgsMessageBar.WARNING, 4) value = param.default # We allow unexistent filepaths, since that allows # algorithms to skip some conversion routines if not param.setValue(value) and not isinstance(param, ParameterDataObject): raise GeoAlgorithmExecutionException( self.tr('Wrong value %s for %s %s', 'ModelerAlgorithm') % (value, param.__class__.__name__, param.name)) for out in algInstance.outputs: if not out.hidden: if out.name in alg.outputs: name = self.getSafeNameForOutput(alg.name, out.name) modelOut = self.getOutputFromName(name) if modelOut: out.value = modelOut.value else: out.value = None return algInstance
def close(self): if self.msg: dlg = MessageDialog() dlg.setTitle(QCoreApplication.translate('MessageBarProgress', 'Problem executing algorithm')) dlg.setMessage("<br>".join(self.msg)) dlg.exec_() iface.messageBar().clearWidgets()
def check_radius(self): if int(self.dlg.lineEdit_radius.text()) > 100000: color = '#f6989d' self.dlg.lineEdit_radius.setStyleSheet('QLineEdit { background-color: %s }' % color) iface.messageBar().pushMessage(u"Error:", u" The maximum supported radius is currently 100,000 meters.", level=QgsMessageBar.CRITICAL, duration=5) else: pass
def doUpdateLayer(self, dest, repo): if self.layer.dataProvider().fieldNameIndex("geogigid") == -1: iface.messageBar().pushMessage("Cannot update GeoGig repository. Layer has no 'geogigid' field", level = QgsMessageBar.WARNING, duration = 4) else: exported = exportVectorLayer(self.layer) repo.importshp(exported, False, dest, "geogigid", True) setInSync(self.layer, True)
def startProgressBar(maxValue, msg = ""): global progress progressMessageBar = iface.messageBar().createMessage(msg) progress = QtGui.QProgressBar() progress.setMaximum(maxValue) progress.setAlignment(QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, QgsMessageBar.INFO)
def run(self): print "into thread" print self.lyr wkr = Import(self.lyr) self.msg_bar_item = QgsMessageBarItem("", "Import des entités", self.progress_bar) iface.messageBar().pushItem(self.msg_bar_item) wkr.progress.connect(self.update_progress_bar) wkr.run()
def displayMessageBar(title = None, msg = None,level=QgsMessageBar.INFO,duration=5): ''' Display the message at the good place ''' if iface.QuickOSM_mainWindowDialog.isVisible(): iface.QuickOSM_mainWindowDialog.messageBar.pushMessage(title, msg, level,duration) else: iface.messageBar().pushMessage(title, msg, level,duration)
def __init__(self, text=""): self.progressMessageBar = \ iface.messageBar().createMessage(text) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO)
def __init__(self): self.progressMessageBar = \ iface.messageBar().createMessage(self.tr('Executing algorithm')) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO)
def runQuery(self): ''' Process for running the query ''' #Block the button and save the initial text QApplication.setOverrideCursor(Qt.WaitCursor) self.pushButton_browse_output_file.setDisabled(True) self.pushButton_showQuery.setDisabled(True) self.startProcess() QApplication.processEvents() #Get all values key = unicode(self.lineEdit_key.text()) value = unicode(self.lineEdit_value.text()) nominatim = unicode(self.lineEdit_nominatim.text()) timeout = self.spinBox_timeout.value() outputDir = self.lineEdit_browseDir.text() prefixFile = self.lineEdit_filePrefix.text() #Which geometry at the end ? outputGeomTypes = self.getOutputGeomTypes() #Which osm's objects ? osmObjects = self.__getOsmObjects() try: #Test values if not osmObjects: raise OsmObjectsException if not outputGeomTypes: raise OutPutGeomTypesException #If bbox, we must set None to nominatim, we can't have both bbox = None if self.radioButton_extentLayer.isChecked() or self.radioButton_extentMapCanvas.isChecked(): nominatim = None bbox = self.getBBox() if nominatim == '': nominatim = None if outputDir and not os.path.isdir(outputDir): raise DirectoryOutPutException numLayers = Process.ProcessQuickQuery(dialog = self, key=key, value=value, nominatim=nominatim, bbox=bbox, osmObjects=osmObjects, timeout=timeout, outputDir=outputDir, prefixFile=prefixFile,outputGeomTypes=outputGeomTypes) #We can test numLayers to see if there are some results if numLayers: self.label_progress.setText(QApplication.translate("QuickOSM",u"Successful query !")) iface.messageBar().pushMessage(QApplication.translate("QuickOSM",u"Successful query !"), level=QgsMessageBar.INFO , duration=5) else: self.label_progress.setText(QApplication.translate("QuickOSM",u"No result")) iface.messageBar().pushMessage(QApplication.translate("QuickOSM", u"Successful query, but no result."), level=QgsMessageBar.WARNING , duration=7) except GeoAlgorithmExecutionException,e: self.displayGeoAlgorithmException(e)
def __init__(self, algname=None): self.progressMessageBar = \ iface.messageBar().createMessage(self.tr('Executing algorithm <i>{0}</i>'.format(algname if algname else ''))) self.progress = QProgressBar() self.progress.setMaximum(100) self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) self.progressMessageBar.layout().addWidget(self.progress) iface.messageBar().pushWidget(self.progressMessageBar, iface.messageBar().INFO)
def execute(self): alg = self.itemData ok, msg = alg.canExecute() if not ok: iface.messageBar().pushMessage(QCoreApplication.translate('EditModelAction', 'Cannot edit model: {}').format(msg), level=Qgis.Warning) else: dlg = ModelerDialog(alg) dlg.update_model.connect(self.updateModel) dlg.show()
def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) w3wCoord = self.toW3W(pt) if w3wCoord: iface.messageBar().pushMessage("what3words", "The 3 word address: '{}' has been copied to the clipboard".format(w3wCoord), level=QgsMessageBar.INFO, duration=6) clipboard = QApplication.clipboard() clipboard.setText(w3wCoord) else: iface.messageBar().pushMessage("what3words", "Could not convert the selected point to a 3 word address", level=QgsMessageBar.WARNING, duration=3)
def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) w3wCoord = self.toW3W(pt) if w3wCoord: iface.messageBar().pushMessage("what3words", "3 Word Address: " + w3wCoord, level=QgsMessageBar.INFO, duration=3) clipboard = QApplication.clipboard() clipboard.setText(w3wCoord) else: iface.messageBar().pushMessage("what3words", "Could not converted the selected point 3 word address.", level=QgsMessageBar.WARNING, duration=3)
def display_message_bar( title=None, msg=None, level=Qgis.Info, duration=5): """ Display the message at the good place """ if iface.QuickOSM_mainWindowDialog.isVisible(): iface.QuickOSM_mainWindowDialog.messageBar.pushMessage( title, msg, level, duration) else: iface.messageBar().pushMessage(title, msg, level, duration)
def __init__(self, parent=None, project=None, gui=None): """Constructor.""" super(NewFuelFormulaEditor, self).__init__(parent) # parent is the dock widget with all graphical elements self.gui = parent # init some globals self.applicationPath = os.path.dirname(os.path.realpath(__file__)) self.project = project self.projectPath = os.path.dirname(self.project.fileName()) self.formulaDict = None self.formulaFileName = None self.temporaryFormulaFileName = None self.vehicleTab = None self.key = "FuelProperties/FormulasConfig" # Set up the user interface from Designer. self.setupUi(self) # get the conf filename confFileName = self.project.value(self.key, "./NewFuelFormulas.json") if not confFileName: message = self.tr("No formula file specified in the project for the key %s" % key) iface.messageBar().pushMessage(message, QgsMessageBar.CRITICAL) return if not os.path.isabs(confFileName): self.formulaFileName = os.path.join(self.projectPath, confFileName) # create temporary formulaFileName useful to manage save and reset self.temporaryFormulaFileName = os.path.join(self.projectPath, ".temp.formulas") shutil.copy(self.formulaFileName, self.temporaryFormulaFileName) # commented because hiding in Windows lock the file # setFileWindowsHidden(self.temporaryFormulaFileName) # set origin formula filename if not self.formulaFileName: return self.formulaFile_LEdit.setText(self.formulaFileName) # set listeners to creats new, save or saveas formula file self.formulaFile_LEdit.returnPressed.connect(self.loadFormulaConf) self.selectFunctionFile_TButton.clicked.connect(self.loadFormulaConf) self.loadDefaultFormulaFile_PButton.clicked.connect(self.setDefaultFormulaConf) self.saveAsFormulaFile_PButton.clicked.connect(self.saveAsFormulaConf) self.saveFormulaFile_PButton.clicked.connect(self.saveFormulaFile) # set save button disabled at the beginning self.saveFormulaFile_PButton.setEnabled(False) # create gui basing on conf self.reloadFormulaConf()
def display_message_bar( title=None, msg=None, level=QgsMessageBar.INFO, duration=5): try: if iface.Blurring_mainWindowDialog.isVisible(): iface.Blurring_mainWindowDialog.messageBar.pushMessage( title, msg, level, duration) else: iface.messageBar().pushMessage(title, msg, level, duration) except AttributeError: iface.messageBar().pushMessage(title, msg, level, duration)
def fileDialog_saveSampling(self, combo_box): if combo_box.currentText() not in Sampling.samplings: iface.messageBar().pushMessage( "AcATaMa", "Error, please select a valid sampling file", level=Qgis.Warning) return suggested_filename = os.path.splitext(Sampling.samplings[combo_box.currentText()].ThematicR.file_path)[0] \ + "_sampling.gpkg" file_out, _ = QFileDialog.getSaveFileName( self, self.tr("Save sampling file"), suggested_filename, self. tr("GeoPackage files (*.gpkg);;Shape files (*.shp);;All files (*.*)" )) if file_out != '': layer = combo_box.currentLayer() file_format = \ "GPKG" if file_out.endswith(".gpkg") else "ESRI Shapefile" if file_out.endswith(".shp") else None QgsVectorFileWriter.writeAsVectorFormat(layer, file_out, "System", layer.crs(), file_format) iface.messageBar().pushMessage("AcATaMa", "File saved successfully", level=Qgis.Success)
def set_center( self ): #Set the canvas center and scale to approximate page location and zoom level. try: location_X, location_Y = [ float(c) for c in self.dockwidget.txt_center.text().split(',') ] center = QgsPointXY(location_X, location_Y) canvasCrs = iface.mapCanvas().mapSettings().destinationCrs() qstoryCrs = QgsCoordinateReferenceSystem(4326) transform = QgsCoordinateTransform(qstoryCrs, canvasCrs, QgsProject.instance()) canvas_X, canvas_Y = transform.transform(center.x(), center.y()) iface.mapCanvas().setCenter(QgsPointXY(canvas_X, canvas_Y)) canvas_scale = (591657550.500000 * 2) / (exp( log(2) * int(self.dockwidget.spin_zoom.value()))) iface.mapCanvas().zoomScale(canvas_scale) except: iface.messageBar().pushMessage( 'No Location', 'You need to set a location for this story page!', level=Qgis.Warning, duration=6)
def finished(self, result): if self.geojson==None and self.exception!=None: msgBox=QMessageBox() msgBox.setText("An error occured while querying: "+str(self.exception)) msgBox.exec() return if self.geojson==None: msgBox=QMessageBox() msgBox.setText("The query yielded no results. Therefore no layer will be created!") msgBox.exec() return if self.geojson!=None and isinstance(self.geojson, int) and not self.allownongeo: msgBox=QMessageBox() msgBox.setText("The query did not retrieve a geometry result. However, there were "+str(self.geojson)+" non-geometry query results. You can retrieve them by allowing non-geometry queries!") msgBox.exec() return self.progress.close() vlayer = QgsVectorLayer(json.dumps(self.geojson, sort_keys=True, indent=4),"unicorn_"+self.filename,"ogr") print(vlayer.isValid()) QgsProject.instance().addMapLayer(vlayer) canvas = iface.mapCanvas() canvas.setExtent(vlayer.extent()) iface.messageBar().pushMessage("Add layer", "OK", level=Qgis.Success)
def getWCSCoverages(self, mapObject): """Retrieves the list of WCS coverages available in this map. :param mapObject: the map we want the image from. :type mapObject: threddsFetcherRecursos.Map :returns: all the WCS Coverages available for this map in the THREDDS server. :rtype: list of WCSParser.WCScoverage """ try: wcsData = mapObject.getWCS() if wcsData is not None: wcsCatalog = wcsData.getCapabilitiesURL() WCSreader = WCS.WCSparser(wcsCatalog) return WCSreader.getAvailableCoverages() else: return None except (HTTPException, URLError, timeout) as e: #QgsMessageLog.logMessage(traceback.format_exc(), "THREDDS Explorer", QgsMessageLog.CRITICAL ) iface.messageBar().pushMessage("THREDDS Explorer", str(e), level=Qgis.Critical) return None
def configure_from_modelbaker(iface): """ Configures config.JAVA/ILI2PG paths using modelbaker. Returns whether modelbaker is available, and displays instructions if not. """ REQUIRED_VERSION = "v6.4.0" # TODO : update once https://github.com/opengisch/QgisModelBaker/pull/473 is released modelbaker = plugins.get("QgisModelBaker") if modelbaker is None: iface.messageBar().pushMessage( "Error", "This feature requires the ModelBaker plugin. Please install and activate it from the plugin manager.", level=Qgis.Critical, ) return False elif modelbaker.__version__ != "dev" and parse_version( modelbaker.__version__) < parse_version(REQUIRED_VERSION): iface.messageBar().pushMessage( "Error", f"This feature requires a more recent version of the ModelBaker plugin (currently : {modelbaker.__version__}). Please install and activate version {REQUIRED_VERSION} or newer from the plugin manager.", level=Qgis.Critical, ) return False # We reuse modelbaker's logic to get the java path and ili2pg executables from withing QGIS # Maybe we could reuse even more (IliExecutable...) ? stdout = SimpleNamespace() stdout.emit = logger.info stderr = SimpleNamespace() stderr.emit = logger.error config.JAVA = ili2dbutils.get_java_path(ili2dbconfig.BaseConfiguration()) config.ILI2PG = ili2dbutils.get_ili2db_bin(globals.DbIliMode.ili2pg, 4, stdout, stderr) return True
def save_as_qlr(self): """ Saves the lyr as a QLR file """ if not self.object: with open(self.path(), 'rb') as f: try: stream = Stream(f, False, force_layer=True, offset=0) self.object = stream.read_object() except RequiresLicenseException as e: message = '<p>{}. Please see <a href="https://north-road.com/slyr/">here</a> for details.</p>'.format( e) BrowserUtils.show_warning('Licensed version required', 'Convert LYR', message, level=Qgis.Critical) return True input_path = self.path() or self.layer_path input_folder, base = os.path.split(input_path) base, _ = os.path.splitext(self.name()) default_name = os.path.join(input_folder, base + '.qlr') dest_path, _ = QFileDialog.getSaveFileName(None, 'Save as QLR', default_name, 'QLR files (*.qlr *.QLR)') if dest_path: context = Context() res, error = LayerConverter.object_to_qlr(self.object, input_path, dest_path, context) if not res: iface.messageBar().pushMessage('Save as QLR', error, Qgis.Critical) return True
def useLayerExtent(self): CANVAS_KEY = 'Use canvas extent' extentsDict = {} extentsDict[CANVAS_KEY] = { "extent": iface.mapCanvas().extent(), "authid": iface.mapCanvas().mapSettings().destinationCrs().authid() } extents = [CANVAS_KEY] layers = QgsProcessingUtils.compatibleLayers(QgsProject.instance()) for layer in layers: authid = layer.crs().authid() if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF) \ and authid is not None: layerName = u'{} [{}]'.format(layer.name(), authid) else: layerName = layer.name() extents.append(layerName) extentsDict[layerName] = { "extent": layer.extent(), "authid": authid } (item, ok) = QInputDialog.getItem(self, self.tr('Select extent'), self.tr('Use extent from'), extents, False) if ok: self.setValueFromRect( QgsReferencedRectangle( extentsDict[item]["extent"], QgsCoordinateReferenceSystem(extentsDict[item]["authid"]))) if extentsDict[item]["authid"] != iface.mapCanvas().mapSettings( ).destinationCrs().authid(): iface.messageBar().pushMessage( self.tr("Warning"), self. tr("The projection of the chosen layer is not the same as canvas projection! The selected extent might not be what was intended." ), QgsMessageBar.WARNING, 8)
def start_worker(worker, iface, message, with_progress=True): # configure the QgsMessageBar message_bar_item = iface.messageBar().createMessage(message) progress_bar = QProgressBar() progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) if not with_progress: progress_bar.setMinimum(0) progress_bar.setMaximum(0) cancel_button = QPushButton() cancel_button.setText('Cancel') cancel_button.clicked.connect(worker.kill) message_bar_item.layout().addWidget(progress_bar) message_bar_item.layout().addWidget(cancel_button) iface.messageBar().pushWidget(message_bar_item, Qgis.Info) # start the worker in a new thread # let Qt take ownership of the QThread thread = QThread(iface.mainWindow()) worker.moveToThread(thread) worker.set_message.connect(lambda message: set_worker_message( message, message_bar_item)) worker.toggle_show_progress.connect(lambda show: toggle_worker_progress( show, progress_bar)) worker.toggle_show_cancel.connect(lambda show: toggle_worker_cancel( show, cancel_button)) worker.finished.connect(lambda result: worker_finished( result, thread, worker, iface, message_bar_item)) worker.error.connect(lambda e: worker_error(e)) worker.was_killed.connect(lambda result: worker_killed( result, thread, worker, iface, message_bar_item)) worker.progress.connect(progress_bar.setValue) thread.started.connect(worker.run) thread.start() return thread, message_bar_item
def obte_llista_capa_objecte(self): """Retorna una llista de capes objecte.""" self.dlg.capa_objecte_list.clear() self.capa_objecte = None self.entitat = None self.dlg.entitat_select.clear() self.dlg.entitat.clear() self.dlg.capa_objecte_usat.setText("Selecciona una capa de la llista") self.dlg.entitat_usat.setText(u"Selecciona una entitat de la llista") if not self.lloc: iface.messageBar().pushMessage( u"Primer has de seleccionar el lloc on fer la cerca", level=QgsMessageBar.CRITICAL, duration=10 ) return capa_objecte = self.dlg.capa_objecte.text().encode('utf-8') llista_amenities = requests.get(AMENITIES) llista_amenities = llista_amenities.json() for element in llista_amenities['data']: if element['value']: if capa_objecte.lower() in (str(element['value']. encode('utf-8')).lower()): self.dlg.capa_objecte_list.addItem(element['value']) print (u"Trobades %d capes" % (self.dlg.capa_objecte_list.count())) if self.dlg.capa_objecte_list.count() < 1: iface.messageBar().pushMessage( u"No hi ha cap capa amb %s. Torna-ho a provar" % (capa_objecte), level=QgsMessageBar.CRITICAL, duration=10 )
def display_critical_message_bar( title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8): """ Display a critical message bar. :param title: The title of the message bar. :type title: str :param message: The message inside the message bar. :type message: str :param more_details: The message inside the 'Show details' button. :type more_details: str :param button_text: The text of the button if 'more_details' is not empty. :type button_text: str :param duration: The duration for the display, default is 8 seconds. :type duration: int """ iface.messageBar().clearWidgets() widget = iface.messageBar().createMessage(title, message) if more_details: button = QPushButton(widget) button.setText(button_text) button.pressed.connect( lambda: display_critical_message_box( title=title, message=more_details)) widget.layout().addWidget(button) iface.messageBar().pushWidget(widget, QgsMessageBar.CRITICAL, duration)
def prepareAlgorithm(self, alg): algInstance = alg.algorithm for param in algInstance.parameters: if not param.hidden: if param.name in alg.params: value = self.resolveValue(alg.params[param.name], param) else: if iface is not None: iface.messageBar().pushMessage( self.tr("Warning"), self. tr("Parameter {0} in algorithm {1} in the model is run with default value! Edit the model to make sure that this is correct." ).format(param.name, alg.displayName()), QgsMessageBar.WARNING, 4) value = param.default # We allow unexistent filepaths, since that allows # algorithms to skip some conversion routines if not param.setValue(value) and not isinstance( param, ParameterDataObject): raise GeoAlgorithmExecutionException( self.tr('Wrong value {0} for {1} {2}', 'ModelerAlgorithm').format( value, param.__class__.__name__, param.name)) for out in algInstance.outputs: if not out.hidden: if out.name in alg.outputs: name = self.getSafeNameForOutput(alg.modeler_name, out.name) modelOut = self.getOutputFromName(name) if modelOut: out.value = modelOut.value else: out.value = None return algInstance
def display_success_message_bar(title=None, message=None, more_details=None, button_text=tr('Show details ...'), duration=8): """ Display a success message bar. :param title: The title of the message bar. :type title: str :param message: The message inside the message bar. :type message: str :param more_details: The message inside the 'Show details' button. :type more_details: str :param button_text: The text of the button if 'more_details' is not empty. :type button_text: str :param duration: The duration for the display, default is 8 seconds. :type duration: int """ widget = iface.messageBar().createMessage(title, message) if more_details: button = QPushButton(widget) button.setText(button_text) button.pressed.connect(lambda: display_information_message_box( title=title, message=more_details)) widget.layout().addWidget(button) if QGis.QGIS_VERSION_INT >= 20700: iface.messageBar().pushWidget(widget, QgsMessageBar.SUCCESS, duration) else: iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, duration)
def updatePublishedStyle(layer): global _currentMessageBarLayer track = pluginSetting("TrackLayers", "geoserverexplorer") if track and isTrackedLayer(layer): if iface.messageBar().currentItem() is None: _resetCurrentMessageBarLayer() if _currentMessageBarLayer != layer: _currentMessageBarLayer = layer widget = iface.messageBar().createMessage( "", "This layer was uploaded to a geoserver catalog. Do you want to update the published style?" ) updateButton = QtWidgets.QPushButton(widget) updateButton.setText("Update") def updateStyle(): url = getTrackingInfo(layer) catalog = Catalog(url) wrapper = CatalogWrapper(catalog) wrapper.publishStyle(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() updateButton.pressed.connect(updateStyle) widget.layout().addWidget(updateButton) stopTrackingButton = QtWidgets.QPushButton(widget) stopTrackingButton.setText("Stop tracking this layer") def stopTracking(): removeTrackedLayer(layer) iface.messageBar().popWidget() _resetCurrentMessageBarLayer() stopTrackingButton.pressed.connect(stopTracking) widget.layout().addWidget(stopTrackingButton) iface.messageBar().pushWidget(widget, Qgis.Info) iface.messageBar().currentItem().geoserverLayer = layer
def load_composition(self): """ Creates the composition object (which is needed for creating the file) from the template file. :returns: the composition object :rtype: QgsComposition """ template_path = get_plugin_path() + self.templates[ self.dockwidget.comboBox_template.currentText()] template_file = open(template_path, "r") content = template_file.read() template_file.close() # the method from QgsComposition for loading the template needs to be a QDomDocument document = QDomDocument() document.setContent(content) # composition = QgsComposition(iface.mapCanvas().mapSettings()) does not work #TODO: is deprecated but works ...fix in new version https://hub.qgis.org/issues/11077 composition = QgsComposition(iface.mapCanvas().mapRenderer()) if not composition.loadFromTemplate(document): iface.messageBar().pushMessage("Error while loading template!") return # set map map_item = composition.getComposerItemById("map") map_item.setMapCanvas(iface.mapCanvas()) map_item.zoomToExtent(iface.mapCanvas().extent()) # set legend try: legend_item = composition.getComposerItemById("legend") legend_item.updateLegend() except AttributeError: # in case first template was selected pass composition.refreshItems() return composition
def geometry_changed(self, qgsfId, geom): """ Called when feature is changed @param qgsfId: Id of added feature @type qgsfId: qgis.core.QgsFeature.QgsFeatureId @param geom: geometry of added feature @type geom: qgis.core.QgsGeometry """ # get new feature geom and convert to correct format wkt = geom.asWkt() sql = general_select.convert_geometry result = self.edit_dialog.db.execute_return(sql, (wkt, )) self.edit_dialog.geom = result.fetchall()[0][0] result = self.edit_dialog.db.execute_return( buildings_select.building_outline_shape_by_building_outline_id, (qgsfId, )) area = geom.area() if area < 10: iface.messageBar().pushMessage( "INFO", "You've edited the outline to less than 10sqm, are you sure this is correct?", level=Qgis.Info, duration=3, ) result = result.fetchall()[0][0] if self.edit_dialog.geom == result: if qgsfId in list(self.edit_dialog.geoms.keys()): del self.edit_dialog.geoms[qgsfId] self.disable_UI_functions() else: self.edit_dialog.geoms[qgsfId] = self.edit_dialog.geom self.enable_UI_functions() self.populate_edit_comboboxes() self.select_comboboxes_value() self.edit_dialog.activateWindow() self.edit_dialog.btn_edit_save.setDefault(True)
def finished(self, result): if result: layers = {} valid = True for mosaic, files in self.filenames.items(): mosaiclayers = [] for filename in files: mosaiclayers.append( QgsRasterLayer(filename, os.path.basename(filename), "gdal")) layers[mosaic] = mosaiclayers valid = valid and (False not in [ lay.isValid() for lay in mosaiclayers ]) if not valid: widget = iface.messageBar().createMessage( "Planet Explorer", f"Order '{self.order.name}' correctly downloaded ") button = QPushButton(widget) button.setText("Open order folder") button.clicked.connect(lambda: QDesktopServices.openUrl( QUrl.fromLocalFile(self.order.download_folder()))) widget.layout().addWidget(button) iface.messageBar().pushWidget(widget, level=Qgis.Success) else: if self.order.load_as_virtual: for mosaic, files in self.filenames.items(): vrtpath = os.path.join(self.order.download_folder(), mosaic, f'{mosaic}.vrt') gdal.BuildVRT(vrtpath, files) layer = QgsRasterLayer(vrtpath, mosaic, "gdal") QgsProject.instance().addMapLayer(layer) else: for mosaic, mosaiclayers in layers.items(): for layer in mosaiclayers: QgsProject.instance().addMapLayer(layer) #TODO create groups iface.messageBar().pushMessage( "Planet Explorer", f"Order '{self.order.name}' correctly downloaded and processed", level=Qgis.Success, duration=5) elif self.exception is not None: QgsMessageLog.logMessage( f"Order '{self.order.name}' could not be downloaded.\n{self.exception}", QGIS_LOG_SECTION_NAME, Qgis.Warning) iface.messageBar().pushMessage( "Planet Explorer", f"Order '{self.order.name}' could not be downloaded. See log for details", level=Qgis.Warning, duration=5)
def createBuffer(self, lBeni, b1, b2): #Crea un buffer per ogni bene contenuto nella lista in input; #Il raggio del buffer corrisponde alla distanza del bene dipendente più lontano; #Setta lo stile e aggiunge il layer con i buffer layer = Utils().getLayerBeni3003() buff_layer = False for feat in layer.getFeatures(): if feat['ident'] in lBeni: beneId = str(feat['id']) dipendentiIds = QueryLayer().getDependenciesList( beneId, b1, b2) if len(dipendentiIds) > 2: buff_layer = QgsVectorLayer("Polygon?crs=epsg:3003", 'bufferBene' + beneId, "memory") geom = feat.geometry().centroid() bufferDist = self.getFarestDistance(beneId, dipendentiIds) * 1000 buff = geom.buffer(bufferDist, 25) f = QgsFeature() f.setGeometry(buff) f.setFields(feat.fields()) f.setAttributes(feat.attributes()) buff_layer.dataProvider().addFeatures([f]) Utils().setStyle("buffer", buff_layer) QgsProject.instance().addMapLayer(buff_layer) if buff_layer != False: if len(lBeni) > 1: Utils().zoomToLayer(Utils().getLayerBeni()) else: Utils().zoomToLayer(buff_layer) else: iface.messageBar().pushMessage( 'Attenzione', 'Non esistono beni o relazioni con queste caratteristiche', level=Qgis.Critical)
def annuler_la_derniere_modification(*args): id_ouvrage = args[0] id_layer = args[1] layer = QgsProject.instance().mapLayer(id_layer) # use processing alg cancel_last_modification params = { 'SOURCE_LAYER': layer, 'SOURCE_ID': id_ouvrage } try: processing.run('raepa:cancel_last_modification', params) except QgsProcessingException: QgsMessageLog.logMessage('Erreur dans les logs de Processing/PostGIS.', 'RAEPA', Qgis.Critical) iface.messageBar().pushMessage( 'Erreur dans les logs de Processing/PostGIS.', level=Qgis.Critical, duration=2) return # Refresh upstream and downstream for layername in [layer.name(), 'Canalisations ASS, Canalisations AEP']: gl = QgsProject.instance().mapLayersByName(layername) if gl: gl[0].triggerRepaint()
def couper_la_canalisation_sous_cet_ouvrage(*args): id_ouvrage = args[0] id_layer = args[1] layer = QgsProject.instance().mapLayer(id_layer) # Use alg to do cut_pipe_under_item sql = "SELECT raepa.decoupage_canalisation_par_ouvrage('{}');".format(id_ouvrage) params = { 'INPUT_SQL': sql } try: processing.run('raepa:execute_sql', params) except QgsProcessingException: QgsMessageLog.logMessage('Erreur dans les logs de Processing/PostGIS.', 'RAEPA', Qgis.Critical) iface.messageBar().pushMessage( 'Erreur dans les logs de Processing/PostGIS.', level=Qgis.Critical, duration=2) return # Refresh layers for layername in [layer.name(), 'Canalisations ASS, Canalisations AEP']: gl = QgsProject.instance().mapLayersByName(layername) if gl: gl[0].triggerRepaint()
def routes_color(i, disp=False): r = i.row() m = i.model() e_ch_col = m.fieldIndex( 'e') #not same as self.e_ch col. Something to do with model vs view? #e_ch=m.index(r,e_ch_col).data() e_ch = i.sibling(0, e_ch_col).data() #last_e_ch=m.index(r-1,e_ch_col).data()#e_ch of last row last_e_ch = i.sibling(-1, e_ch_col).data() s_ch_col = m.fieldIndex('s') #s_ch=m.index(r,s_ch_col).data()#start_ch of next row s_ch = i.sibling(0, e_ch_col).data() # next_s_ch=m.index(r+1,s_ch_col).data()#start_ch of next row next_s_ch = i.sibling(1, e_ch_col).data() if disp: iface.messageBar().pushMessage(str(e_ch) + ' ' + str(next_s_ch)) if next_s_ch: # not None if e_ch > next_s_ch: #end_ch of row>s_ch of next row return QBrush(Qt.red) if next_s_ch - e_ch > GAP_SIZE: # gap between e_ch of row and s_ch of next row return QBrush(Qt.yellow) if last_e_ch: #not none if last_e_ch > s_ch: #end_ch of last row>s_ch return QBrush(Qt.red) if s_ch - last_e_ch > GAP_SIZE: #gap between e_ch of last row and s_ch of row return QBrush(Qt.yellow)
def run_sketch_line(network, ref): """ Run an action with two values for sketchline @param network:network of the bus @type network:str @param ref:ref of the bus @type ref:str """ network = unicode(network, "UTF-8") ref = unicode(ref, "UTF-8") if network == '' or ref == '': iface.messageBar().pushMessage( tr("OSMData", u"Sorry man, this field is empty for this entity."), level=QgsMessageBar.WARNING, duration=7) else: var = QDesktopServices() url = "http://www.overpass-api.de/api/sketch-line?" \ "network=" + network + "&ref=" + ref var.openUrl(QUrl(url))
def uiCalcNDVI(self): self.sensorType = self.ndviSensorType.currentText() self.NIRBand = self.ndviLineEditNIR.text() self.VNIRBand = self.ndviLineEditVNIR.text() self.RedBand = self.ndviLineEditRed.text() self.outputRaster = self.ndviLineEditOutputRaster.text() self.rasterType = str(self.ndviFormat.currentText()) #Loading the raster to the QGIS project if (self.ndviAddToProject.isChecked()): self.addToQGIS = 'Yes' else: self.addToQGIS = 'No' if self.sensorType == 'Landsat': #Validate the inputs when the selected sensor is Landsat if self.NIRBand == '': iface.messageBar().pushWarning("Land Surface Temperature Plugin","The near infrared band is required") elif self.RedBand == '': iface.messageBar().pushWarning("Land Surface Temperature Plugin","The red band is required") elif self.outputRaster == '': iface.messageBar().pushWarning("Land Surface Temperature Plugin","The output save location is required") elif self.NIRBand != '' and self.RedBand != '' and self.outputRaster != '': self.argList = [self.RedBand, self.NIRBand, self.outputRaster, self.rasterType, self.addToQGIS] self.startWorker('LSTNDVI', self.argList, 'Calculating NDVI') elif self.sensorType == 'ASTER': #Validate the inputs when the selected sensor is ASTER if self.VNIRBand == '': iface.messageBar().pushWarning("Land Surface Temperature Plugin","The the visible/near infrared band is required") elif self.outputRaster == '': iface.messageBar().pushWarning("Land Surface Temperature Plugin","Specify output to be saved") #elif self.VNIRBand != '' and self.outputRaster != '': #self.argList = [self.VNIRBand, self.outputRaster, self.rasterType, self.addToQGIS] #self.startWorker('ASTERNDVI', self.argList, 'Calculating NDVI') self.closePlugin()
def finished(self, result): """ This function is threadsafe for GUI-Actions and called after run terminates. """ if self.guionly: self.pyratTool.guirun(iface.mainWindow()) if result and not self.failed: iface.messageBar().pushMessage(self.pyratTool.name + " finished.", level=Qgis.Success) for layer in [ newlayer for newlayer in pyrat.data.getLayerIDs() if newlayer not in self.existinglayers ]: # Show the generated Layer(s) in QGIS anno = pyrat.data.getAnnotation(layer=layer) if 'info' not in anno: anno['info'] = "Pyrat-Layer " + layer pyrat.data.setAnnotation( {'info': anno['info'] + "-" + self.pyratTool.name}, layer=layer) ViewerToQGISInterface.display[layer] = { 'scaling': 'min->max', 'bwlayer': layer, 'colour': False } PyRATBridge.pyratToLayer(self.layer) PyRATBridge.layerTreeWidget.redraw() else: iface.messageBar().pushMessage(self.pyratTool.name + " failed. Look in the (system)" + " console for more information.", level=Qgis.Critical) del self.plugin
def loadConfiguration(self): ''' Function to load last conf get from settings ''' if not self.project: return # from th eproject, get JSON filename to load currentVehicleClassesJson = self.project.value( '/FleetComposition/fleetComposition', self.gui.defaultVehicleClassesFileName) # check if json is relative path or absolute if not os.path.isabs(currentVehicleClassesJson): currentVehicleClassesJson = os.path.join( self.projectPath, currentVehicleClassesJson) # load json conf try: with open(currentVehicleClassesJson) as confFile: # loaded in and OrderedDict to allow maintaining the order of classes # contained in the json file. This will be reflected in the order # shown in the sunburst visualization/editor self.vehicleClassesDict = json.load( confFile, object_pairs_hook=collections.OrderedDict) self.configurationLoaded.emit(True) except Exception as ex: self.vehicleClassesDict = None QgsMessageLog.logMessage(traceback.format_exc(), 'QTraffic', QgsMessageLog.CRITICAL) iface.messageBar().pushMessage( self.tr("Error loading Conf JSON file. Please check the log"), QgsMessageBar.CRITICAL) return
def onDelete(self): """Delete selected features. Ask user to confirm this action. """ layer = self.getActiveLayer() if not layer: return count = layer.selectedFeatureCount() if count > 0: # ask if features should be really deleted (no undo avaialble) reply = QMessageBox.question( self, self.tr("Delete?"), self.tr("Do you want to delete {} selected features? " "This operation cannot be reverted.").format(count), QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: # delete selected features from currently selected layer layer.setReadOnly(False) iface.actionToggleEditing().trigger() iface.actionDeleteSelected().trigger() iface.actionSaveActiveLayerEdits().trigger() iface.actionToggleEditing().trigger() layer.setReadOnly(True) else: # inform user - no features selected, nothing to be deleted iface.messageBar().pushMessage( self.tr("Info"), self.tr("No features selected. Nothing to be deleled."), level=QgsMessageBar.INFO, duration=3) # disable deselect/delete buttons self.actionDeselect.setEnabled(False) self.actionDelete.setEnabled(False)
def getBedPhysRegion(self): selector = meshSelector(iface, self.dlg.saveFolderEdit.text()) result = selector.run() if result: f = open(selector.mesh2dm) meshLines = f.readlines() physRef, boundsRef = shepred.read2dmMesh(meshLines) physRef.sort() _physRef = dict() for i in range(0, len(physRef)): _physRef.update({i+1: str(physRef[i])}) self.boundsRef = boundsRef self.physRef = _physRef iface.messageBar().pushMessage(selector.mesh2dm) subprocess.call(['cmd', '/c', 'copy', '/Y', selector.mesh2dm.replace('/', '\\'), os.path.join(self.dlg.saveFolderEdit.text(), 'sim')]) self.dlg.label_45.setText(os.path.basename(selector.mesh2dm)) if selector.meshMsh: boundsRef, physRef = shepred.readMshMesh(selector.meshMsh) self.boundsRef = boundsRef self.physRef = physRef
def finished(self, result): if self.query == "": msgBox = QMessageBox() msgBox.setWindowTitle("No search query specified") msgBox.setText("No search query specified for this triplestore") msgBox.exec() return if "SELECT" in self.query: if len(self.results["results"]) == 0 or len( self.results["results"]["bindings"]) == 0: msgBox = QMessageBox() msgBox.setWindowTitle("Empty search result") msgBox.setText("The search yielded no results") msgBox.exec() return for res in self.results["results"]["bindings"]: item = QListWidgetItem() item.setData(1, str(res["class"]["value"])) if "label" in res: item.setText( str(res["label"]["value"] + " (" + res["class"]["value"] + ")")) else: item.setText(str(res["class"]["value"])) self.searchResult.addItem(item) else: i = 0 for result in self.results: item = QListWidgetItem() item.setData(1, self.qids[i]) item.setText(str(self.results[result])) self.searchResult.addItem(item) i += 1 iface.messageBar().pushMessage("Searched for concepts in", "OK", level=Qgis.Success)
def setProgressBarMessages(self, val): # --- Progress bar in the QGIS user messages (top) if val <= 15: message = QCoreApplication.translate("Task message","Starting...") iface.messageBar().pushMessage(message) elif val < 50: message = QCoreApplication.translate("Task message","Calculating according to grades and weights...") iface.messageBar().pushMessage(message) elif val < 100: message = QCoreApplication.translate("Task message","Preparing final raster...") iface.messageBar().pushMessage(message) elif val == 100: iface.messageBar().clearWidgets() # def cancelTask(self): # self.task.cancel()
def creator_geometry_changed(self, qgsfId, geom): """ Called when feature is changed @param qgsfId: Id of added feature @type qgsfId: qgis.core.QgsFeature.QgsFeatureId @param geom: geometry of added feature @type geom: qgis.core.QgsGeometry """ if qgsfId in list(self.edit_dialog.added_geoms.keys()): area = geom.area() if area < 10: iface.messageBar().pushMessage( "INFO", "You've edited the outline to less than 10sqm, are you sure this is correct?", level=Qgis.Info, duration=3, ) wkt = geom.asWkt() if not wkt: self.disable_UI_functions() self.edit_dialog.geom = None return sql = general_select.convert_geometry result = self.edit_dialog.db.execute_return(sql, (wkt, )) geom = result.fetchall()[0][0] self.edit_dialog.added_geoms[qgsfId] = geom if qgsfId == list(self.edit_dialog.added_geoms.keys())[-1]: self.edit_dialog.geom = geom else: iface.messageBar().pushMessage( "WRONG GEOMETRY EDITIED", "Only the currently added outline can be edited. Please go to edit geometry to edit existing outlines", level=Qgis.Warning, duration=5, ) self.edit_dialog.btn_edit_save.setDisabled(1)
def connect(self): #need this for qsqlTableModel etc. self.db.setHostName(self.host.text()) self.db.setDatabaseName(self.database.text()) self.db.setUserName(self.user.text()) self.db.setPassword(self.password.text()) if self.con: self.con.close() #but psycopg2 better than QSqlQuery try: self.con=psycopg2.connect(host=self.host.text(),dbname=self.database.text(),user=self.user.text(),password=self.password.text()) self.db.open() self.set_connected(True) self.cur=self.con.cursor(cursor_factory=psycopg2.extras.DictCursor) self.reconnected.emit() except Exception as e: self.cur=None self.set_connected(False) iface.messageBar().pushMessage('fitting tool: failed to connect: '+str(e))