Python qgis.utils.iface.mainWindow() Examples
The following are 22
code examples of qgis.utils.iface.mainWindow().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
qgis.utils.iface
, or try the search function
.
Example #1
Source File: str_components.py From stdm with GNU General Public License v2.0 | 6 votes |
def __init__(self): """ Initialize the STR component class. """ super(ComponentUtility, self).__init__() self.current_profile = current_profile() self.social_tenure = self.current_profile.social_tenure self.parties = self.social_tenure.parties self.spatial_units = self.social_tenure.spatial_units self.str_model = None self.str_doc_model = None if len(self.parties) > 0: self.party_1 = self.parties[0] if len(self.spatial_units) > 0: self.spatial_unit_1 = self.spatial_units[0] try: self.str_model, self.str_doc_model = entity_model( self.social_tenure, False, True ) except Exception as ex: QMessageBox.critical( iface.mainWindow(), QApplication.translate('ComponentUtility', 'Database Error'), str(ex) )
Example #2
Source File: str_components.py From stdm with GNU General Public License v2.0 | 6 votes |
def select_file_dialog(self, title): """ Displays a file dialog for a user to specify a source document :param title: The title of the file dialog :type title: String """ # Get last path for supporting documents last_path = last_document_path() if last_path is None: last_path = '/home' files = QFileDialog.getOpenFileNames( iface.mainWindow(), title, last_path, "Source Documents (*.jpg *.jpeg *.png *.bmp *.tiff *.svg)" ) return files
Example #3
Source File: progress_dialog.py From stdm with GNU General Public License v2.0 | 6 votes |
def closeEvent(self, event): title = self.tr('Interruption Error') message = self.tr( 'Are you sure you want to ' 'cancel the process?' ) warning_result = QMessageBox.critical( iface.mainWindow(), title, message, QMessageBox.Yes, QMessageBox.No ) if warning_result: event.accept() else: event.ignore()
Example #4
Source File: Map.py From qgis-earthengine-plugin with MIT License | 6 votes |
def getZoom(): """ Returns the current zoom level of the map. https://developers.google.com/earth-engine/api_docs#map.getzoom, note that in QGIS zoom is a floating point number Uses: >>> from ee_plugin import Map >>> print(Map.getZoom()) """ # from https://gis.stackexchange.com/questions/268890/get-current-zoom-level-from-qgis-map-canvas scale = iface.mapCanvas().scale() dpi = iface.mainWindow().physicalDpiX() maxScalePerPixel = 156543.04 inchesPerMeter = 39.37 zoom = math.log((dpi * inchesPerMeter * maxScalePerPixel / scale), 2) return zoom
Example #5
Source File: script_editor_dialog.py From qgis-processing-r with GNU General Public License v3.0 | 6 votes |
def runAlgorithm(self): alg = RAlgorithm(description_file=None, script=self.editor.text()) if alg.error is not None: error = QgsError(alg.error, "R") QgsErrorDialog.show(error, self.tr("Execution error") ) return alg.setProvider(QgsApplication.processingRegistry().providerById("r")) alg.initAlgorithm() dlg = alg.createCustomParametersWidget(iface.mainWindow()) if not dlg: dlg = AlgorithmDialog(alg, parent=iface.mainWindow()) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() if canvas.mapTool() != prevMapTool: if canvas.mapTool(): canvas.mapTool().reset() canvas.setMapTool(prevMapTool)
Example #6
Source File: mainPlugin.py From PyRAT with Mozilla Public License 2.0 | 6 votes |
def pyratToLayer(layerid=None): """Exports a PyRAT-layer into QGIS""" if type(layerid) is str: pyrat.data.activateLayer(layerid) annotation = pyrat.data.getAnnotation() if 'info' in annotation: filename = path.join(pyrat.data.tmpdir, annotation['info'] + ".rat") else: filename = path.join(pyrat.data.tmpdir, "PyRAT.rat") filename, s = QFileDialog.getSaveFileName( iface.mainWindow(), "Save the PyRAT-Layer", filename, "RAT-File (*.rat)") if not s or filename == "": return pyrat.save.rat((filename, "rat"), geo_envi_hdr=True) iface.addRasterLayer(filename, path.basename(filename).split(".")[0])
Example #7
Source File: autoInstaller.py From PyRAT with Mozilla Public License 2.0 | 6 votes |
def _installWith(system): if _qtModule: ans = _qtModule.QMessageBox.question( iface.mainWindow(), "Install missing packages?", "Install missing packages with " + system + "?\r\n" "(You'll get a notification when finished)", _qtModule.QMessageBox.Yes | _qtModule.QMessageBox.No, _qtModule.QMessageBox.Yes) return ans == _qtModule.QMessageBox.Yes else: valid = {"": True, "yes": True, "y": True, "no": False, "on": False, "n": False} while True: choice = input( "Install missing packages with " + system + " [Y/n]? " ).lower() if choice in valid: return valid[choice] else: _print("Please respond with 'yes' or 'no' (or 'y' or 'n').")
Example #8
Source File: autoInstaller.py From PyRAT with Mozilla Public License 2.0 | 5 votes |
def _unknownError(): if _qtModule: _qtModule.QMessageBox.critical( iface.mainWindow(), "Aborting", "Errors occured during package installation.\r\n" "Please look into the console for more details.")
Example #9
Source File: Master Script Model.py From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 | 5 votes |
def inputDialog(self, inputType, title, content): if (inputType == 1): return QInputDialog.getText(iface.mainWindow(), title, content) if (inputType == 2): return QInputDialog.getInt(iface.mainWindow(), title, content)
Example #10
Source File: Master Script Model.py From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 | 5 votes |
def information(self, title, content): return QMessageBox.information(iface.mainWindow(), title, content)
Example #11
Source File: Master Script Model.py From GeoPythonConf2018-QGIS-Processing-Workshop with GNU General Public License v3.0 | 5 votes |
def question(self, title, content): return QMessageBox.question(iface.mainWindow(), title, content, QMessageBox.Yes, QMessageBox.No)
Example #12
Source File: preLoader.py From PyRAT with Mozilla Public License 2.0 | 5 votes |
def _writeLDPRELOAD(): try: with open(os.path.join( os.environ["CONDA_PREFIX"], "etc", "conda", "activate.d", "qgis-activate.sh" ), "a") as script: script.write("export LD_PRELOAD=\"" + os.path.join( os.environ["CONDA_PREFIX"], "lib", "libedit.so") + " $LD_PRELOAD\"") with open(os.path.join( os.environ["CONDA_PREFIX"], "etc", "conda", "deactivate.d", "qgis-deactivate.sh" ), "a") as script: script.write("unset LD_PRELOAD") QMessageBox.warning( iface.mainWindow(), "Finish installation", "To finish the PyRATBridge installation please " "restart QGIS and reload your anaconda " "environment.") except Exception: QMessageBox.warning( iface.mainWindow(), "Exception during LD_PRELOAD configuration", "The installation is uncomplete and might crash on loading. " "Please reload the plugin or restart QGIS.")
Example #13
Source File: mainPlugin.py From PyRAT with Mozilla Public License 2.0 | 5 votes |
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
Example #14
Source File: mainPlugin.py From PyRAT with Mozilla Public License 2.0 | 5 votes |
def addMenuEntry(self, pyratTool): """Adds a PyRAT Tool to the QGIS-Menu""" menus = pyratTool.gui['menu'].split('|') submenu = self.pyratMenu for menu in menus: if menu not in [action.text() for action in submenu.actions()]: submenu = submenu.addMenu(menu) else: submenu = [action.menu() for action in submenu.actions() if action.text() == menu][0] action = QAction(pyratTool.gui['entry'], iface.mainWindow()) action.triggered.connect(lambda: PyRATBridge.menuAction(self, pyratTool)) submenu.addAction(action)
Example #15
Source File: hqgis.py From Hqgis with GNU General Public License v3.0 | 5 votes |
def messageShow(self, progress, count, max): if not progress: progressMessageBar = iface.messageBar().createMessage( "Looping through " + str(max) + " records ...") progress = QProgressBar() progress.setMaximum(max) progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter) progressMessageBar.layout().addWidget(progress) iface.messageBar().pushWidget(progressMessageBar, level=1) iface.mainWindow().repaint() # return progress if progress: progress.setValue(count) return(progress)
Example #16
Source File: autoInstaller.py From PyRAT with Mozilla Public License 2.0 | 5 votes |
def _noWritePerms(): _print("ERROR: The current user does not have " "write permissions to the target environment.") if _qtModule: _qtModule.QMessageBox.critical( iface.mainWindow(), "No write permissions", "You don't have write permissions to install the requested" " packages in the current python environment. Ask the " "environment administrator to install the packages or create " "a new conda environment with the requirements.yml file.")
Example #17
Source File: edit_script.py From qgis-processing-r with GNU General Public License v3.0 | 5 votes |
def execute(self): """ Called whenever the action is triggered """ file_path = self.itemData.description_file if file_path is not None: dlg = ScriptEditorDialog(file_path, iface.mainWindow()) dlg.show() else: QMessageBox.warning(None, self.tr("Edit Script"), self.tr("Can not find corresponding script file."))
Example #18
Source File: datasourceConversion.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def run(self, conversionMap): """ Executes conversion itself based on a conversion map. :param conversionMap: (dict) the conversion map. (SPECIFY FORMAT!) """ # task = DbConverter(iface, conversionMap, description=self.tr('DSGTools Dataset Conversion')) # summaryDlg = TextBrowserDialog(parent=iface.mainWindow()) # summaryDlg.savePushButton.setEnabled(False) # task.progressChanged.connect(summaryDlg.progressBar.setValue) # task.taskCompleted.connect(lambda : summaryDlg.setHtml(task.output['log'])) # task.taskCompleted.connect(lambda : summaryDlg.cancelPushButton.setEnabled(False)) # task.taskCompleted.connect(lambda : summaryDlg.savePushButton.setEnabled(True)) # task.conversionUpdated.connect(summaryDlg.addToHtml) # summaryDlg.cancelPushButton.clicked.connect(partial(self.cancelConversion, task, summaryDlg)) # # to clear log message before repopulating with conversion summary # task.conversionFinished.connect(summaryDlg.clearHtml) # QgsApplication.taskManager().addTask(task) # summaryDlg.show() # conversion off the thread conv = DbConverter(iface, conversionMap, description=self.tr('DSGTools Dataset Conversion')) summaryDlg = TextBrowserDialog(parent=iface.mainWindow()) summaryDlg.cancelPushButton.hide() summaryDlg.progressBar.hide() try: QtWidgets.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if not conv.run(): # advise conversion has failed msg = self.tr("Dataset conversion has finished with some errors. Check conversion log for details.") iface.messageBar().pushMessage(self.tr('Warning!'), msg, level=Qgis.Warning, duration=5) else: self.resetInterface() QtWidgets.QApplication.restoreOverrideCursor() summaryDlg.setHtml(conv.output['log']) except Exception as e: QtWidgets.QApplication.restoreOverrideCursor() msg = self.tr("Dataset conversion has failed: '{0}'").format(', '.join(map(str, e.args))) iface.messageBar().pushMessage(self.tr('Warning!'), msg, level=Qgis.Warning, duration=5) QgsMessageLog.logMessage(':'.join(e.args), "DSGTools Plugin", Qgis.Critical) summaryDlg.exec_()
Example #19
Source File: gsexploreritems.py From qgis-geoserver-plugin with GNU General Public License v2.0 | 5 votes |
def checkWorkspaces(self): ws = self.getDefaultWorkspace() if ws is None: QMessageBox.warning(iface.mainWindow(), 'No workspaces', "You must have at least one workspace in your catalog\n" "to perform this operation.", QMessageBox.Ok) return False return True
Example #20
Source File: pg_utils.py From stdm with GNU General Public License v2.0 | 5 votes |
def vector_layer(table_name, sql='', key='id', geom_column='', layer_name='', proj_wkt=None): """ Returns a QgsVectorLayer based on the specified table name. """ if not table_name: return None conn = stdm.data.app_dbconn if conn is None: return None if not geom_column: geom_column = None ds_uri = conn.toQgsDataSourceUri() ds_uri.setDataSource("public", table_name, geom_column, sql, key) if not layer_name: layer_name = table_name if proj_wkt is not None: iface.mainWindow().blockSignals(True) v_layer = QgsVectorLayer(ds_uri.uri(), layer_name, "postgres") if proj_wkt is not None: iface.mainWindow().blockSignals(False) try: target_crs = QgsCoordinateReferenceSystem( proj_wkt, QgsCoordinateReferenceSystem.InternalCrsId ) v_layer.setCrs(target_crs) except Exception: pass return v_layer
Example #21
Source File: mainPlugin.py From PyRAT with Mozilla Public License 2.0 | 4 votes |
def initGui(self): """Initalise the Plugin-UI""" if not pyratImport: iface.messageBar().pushMessage("PyRAT not found!", level=Qgis.Critical) return if 'PyRAT' not in [action.text() for action in iface.mainWindow().menuBar().actions()]: self.pyratMenu = iface.mainWindow().menuBar().addMenu('PyRAT') else: self.pyratMenu = [action.menu() for action in iface.mainWindow().menuBar().actions() if action.text() == 'PyRAT'][0] action = QAction("Layer2PyRAT", iface.mainWindow()) action.triggered.connect(PyRATBridge.layerToPyrat) self.pyratMenu.addAction(action) action = QAction("PyRAT2Layer", iface.mainWindow()) action.triggered.connect(PyRATBridge.pyratToLayer) self.pyratMenu.addAction(action) action = QAction("Cleanup PyRAT", iface.mainWindow()) action.triggered.connect(PyRATBridge.clearPyRAT) self.pyratMenu.addAction(action) action = QAction("Show PyRAT GUI", iface.mainWindow()) action.triggered.connect(self.showPyrat) self.pyratMenu.addAction(action) self.pyratMenu.addSeparator() # Init PyRAT-Tools, adapted from pyrat.viewer for qgis from inspect import getmembers, isclass modules = [pyrat.load, pyrat.save, pyrat.transform, pyrat.filter, pyrat.polar, pyrat.insar, pyrat.plugins, pyrat.viewer] for current_module in modules: modules = getmembers(current_module, isclass) for mod in modules: if issubclass(mod[1], pyrat.Worker): plugin = mod[1] if(hasattr(plugin, 'gui') and plugin.gui['entry'] != "Python console"): self.addMenuEntry(plugin) self.pyratLayerTree = QDockWidget("PyRAT Layers", iface.mainWindow()) PyRATBridge.layerTreeWidget = LayerTreeWidget( parent=self.pyratLayerTree, viewer=ViewerToQGISInterface) self.pyratLayerTree.setObjectName("PyRAT Layers") self.pyratLayerTree.setWidget(PyRATBridge.layerTreeWidget) iface.addDockWidget(Qt.LeftDockWidgetArea, self.pyratLayerTree)
Example #22
Source File: mainPlugin.py From PyRAT with Mozilla Public License 2.0 | 4 votes |
def layerToPyrat(): """Imports a QGIS-Layer into PyRAT""" layers = list() for layer in QgsProject.instance().layerTreeRoot().layerOrder(): # 1: QgsMapLayer.LayerType.RasterLayer if layer.type() == 1: layers.append(layer.name()) layername, s = QInputDialog.getItem( iface.mainWindow(), "Select a layer", "Select a layer to export to PyRAT:", layers, editable=False) if not s: return layer = QgsProject.instance().mapLayersByName(layername)[0] dataProv = layer.dataProvider() extent = dataProv.extent() rows = layer.height() cols = layer.width() block = dataProv.block(1, extent, cols, rows) arr = np.frombuffer(block.data(), dtype=qgis_types[block.dataType()] ).reshape((rows, cols)) pyratlayer = pyrat.adddata(arr) # Add metadata to the PyRAT-Layer description = layer.crs().description() meta = {"info": layer.name(), "geo_min_east": extent.xMinimum(), # Subtract 1 due to QGIS inclusive minimum "geo_min_north": extent.yMinimum() - 1, "geo_ps_east": layer.rasterUnitsPerPixelX(), "geo_ps_north": layer.rasterUnitsPerPixelY()} if description.startswith('WGS 84 / UTM zone '): zone = int(description[:-1].rsplit(" ", 1)[1]) if description[-1] == "S": zone = -zone meta["geo_projection"] = 1 meta["geo_zone"] = zone pyrat.setmeta(meta) ViewerToQGISInterface.display[pyratlayer] = {'scaling': 'min->max', 'bwlayer': pyratlayer, 'colour': False} PyRATBridge.layerTreeWidget.redraw()