def getHttp(self, command, payload={}, headers={"Accept": "application/json"}): try: pwdok, prompted = self.getPassword() if pwdok: QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) QtCore.QCoreApplication.processEvents() try: url = self.url + command r = requests.get(url, params=payload, headers=headers, auth=(self.user, self.password)) if r.status_code == 401: if prompted: self.resetCredentials() raise GeogigAuthException() try: r.raise_for_status() except Exception as e: if prompted: self.resetCredentials() raise GeogigError("Error using GET at " + url, str(e),causedBy=e) return r.json() except requests.exceptions.ConnectionError as e: if prompted: self.resetCredentials() raise else: if prompted: self.resetCredentials() raise GeogigAuthException() finally: QtWidgets.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()
def __init__(self, parent): super().__init__(parent.canvas) self.canvas = parent.canvas self.parent = parent self.markers = [] #custom cursor self.cursor = QtGui.QCursor(QtGui.QPixmap(["16 16 3 1", " c None", ". c #FF0000", "+ c #FFFFFF", " ", " +.+ ", " ++.++ ", " +.....+ ", " +. .+ ", " +. . .+ ", " +. . .+ ", " ++. . .++", " ... ...+... ...", " ++. . .++", " +. . .+ ", " +. . .+ ", " ++. .+ ", " ++.....+ ", " ++.++ ", " +.+ "]))
def delete(self, command, headers={}): try: pwdok, prompted = self.getPassword() if pwdok: QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) QtCore.QCoreApplication.processEvents() try: url = self.url + command r = requests.delete(url, headers=headers, auth=(self.user, self.password)) if r.status_code == 401: if prompted: self.resetCredentials() raise GeogigAuthException() try: r.raise_for_status() except Exception as e: if prompted: self.resetCredentials() raise GeogigError("Error using DELETE at " + url, str(e)) except requests.exceptions.ConnectionError as e: if prompted: self.resetCredentials() raise else: if prompted: self.resetCredentials() raise GeogigAuthException() finally: QtWidgets.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()
def __init__(self, iface): #construtor self.iface = iface self.canvas = iface.mapCanvas() super(AcquisitionFree, self).__init__(self.canvas) self.rubberBand = None self.rubberBandToStopState = None self.drawing = False self.snapCursorRubberBand = None self.active = False self.contadorVert = 0 self.stopState = False self.cur = QtGui.QCursor( QtGui.QPixmap([ "18 13 4 1", " c None", "# c #FF0000", ". c #FF0000", "+ c #1210f3", " ", " +++++++++++ ", " + # + ", " + # + ", "+ # +", "+ # +", "++#############++", "+ # +", "+ # +", " + # +", " + # + ", " +++++++++++ ", " ", ])) self.controlPressed = False
def enable_busy_cursor(): """Set the hourglass enabled and stop listening for layer changes.""" from qgis.core import QgsApplication from qgis.PyQt import QtGui, QtCore QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor))
def execute(func, message=None): ''' Executes a lengthy tasks in a separate thread and displays a waiting dialog if needed. Sets the cursor to wait cursor while the task is running. This function does not provide any support for progress indication :param func: The function to execute. :param message: The message to display in the wait dialog. If not passed, the dialog won't be shown ''' global _dialog cursor = QtWidgets.QApplication.overrideCursor() waitCursor = (cursor is not None and cursor.shape() == QtCore.Qt.WaitCursor) dialogCreated = False try: QtCore.QCoreApplication.processEvents() if not waitCursor: QtWidgets.QApplication.setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) if message is not None: t = ExecutorThread(func) loop = QtCore.QEventLoop() t.finished.connect(loop.exit, QtCore.Qt.QueuedConnection) if _dialog is None: dialogCreated = True _dialog = QtGui.QProgressDialog(message, "Running", 0, 0, iface.mainWindow()) _dialog.setWindowTitle("Running") _dialog.setWindowModality(QtCore.Qt.WindowModal) _dialog.setMinimumDuration(1000) _dialog.setMaximum(100) _dialog.setValue(0) _dialog.setMaximum(0) _dialog.setCancelButton(None) else: oldText = _dialog.labelText() _dialog.setLabelText(message) QtWidgets.QApplication.processEvents() t.start() loop.exec_(flags=QtCore.QEventLoop.ExcludeUserInputEvents) if t.exception is not None: raise t.exception return t.returnValue else: return func() finally: if message is not None: if dialogCreated: _dialog.reset() _dialog = None else: _dialog.setLabelText(oldText) if not waitCursor: QtWidgets.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()
def __init__(self, nom): QtWidgets.QMainWindow.__init__(self) self.ui = Ui_graphicsWindow() self.ui.setupUi(self, nom) self.ui.graphicsView.resizeEvent = self.gwResizeEvent self.currentRect = None self.myRect = QtCore.QRect() self.myPen = QtGui.QPen() self.rayon = 20 self.ui.widget.paintEvent = self.draw cursorPath = ":/Anaglyph/Icons/cursor3x3.png" cursorImage = QtGui.QImage(cursorPath) cursorPix = QtGui.QPixmap.fromImage(cursorImage) self.invisibleCursor = QtGui.QCursor(cursorPix) self.normalCursor = self.cursor()
def post(self, command, json=None, params={}, headers={"Accept": "application/json"}): try: pwdok, prompted = self.getPassword() if pwdok: QtWidgets.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor)) QtCore.QCoreApplication.processEvents() try: url = self.url + command if json is not None: r = requests.post(url, json=json, headers=headers, auth=(self.user, self.password)) else: r = requests.post(url, data=params, headers=headers, auth=(self.user, self.password)) if r.status_code == 401: if prompted: self.resetCredentials() raise GeogigAuthException() try: r.raise_for_status() except Exception as e: if prompted: self.resetCredentials() raise GeogigError("Error using POST at " + url, str(e)) try: return r.json() except: return [] except requests.exceptions.ConnectionError as e: if prompted: self.resetCredentials() raise else: if prompted: self.resetCredentials() raise GeogigAuthException() finally: QtWidgets.QApplication.restoreOverrideCursor() QtCore.QCoreApplication.processEvents()
def accept(self): """Do PetaBencana download and display it in QGIS. .. versionadded: 3.3 """ self.save_state() try: self.require_directory() except CanceledImportDialogError: return QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) source = self.define_url() # save the file as json first name = 'jakarta_flood.json' output_directory = self.output_directory.text() output_prefix = self.filename_prefix.text() overwrite = self.overwrite_flag.isChecked() date_stamp_flag = self.include_date_flag.isChecked() output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) title = self.tr("Can't access API") try: self.download(source, output_base_file_path) # Open downloaded file as QgsMapLayer options = QgsVectorLayer.LayerOptions(False) layer = QgsVectorLayer(output_base_file_path, 'flood', 'ogr', options) except Exception as e: disable_busy_cursor() QMessageBox.critical(self, title, str(e)) return self.time_stamp = time.strftime('%d-%b-%Y %H:%M:%S') # Now save as shp name = 'jakarta_flood.shp' output_base_file_path = self.get_output_base_path( output_directory, output_prefix, date_stamp_flag, name, overwrite) QgsVectorFileWriter.writeAsVectorFormat(layer, output_base_file_path, 'CP1250', QgsCoordinateTransform(), 'ESRI Shapefile') # Get rid of the GeoJSON layer and rather use local shp del layer self.copy_style(output_base_file_path) self.copy_keywords(output_base_file_path) layer = self.add_flooded_field(output_base_file_path) # check if the layer has feature or not if layer.featureCount() <= 0: city = self.city_combo_box.currentText() message = self.tr('There are no floods data available on {city} ' 'at this time.').format(city=city) display_warning_message_box(self, self.tr('No data'), message) disable_busy_cursor() else: # add the layer to the map project = QgsProject.instance() project.addMapLayer(layer) disable_busy_cursor() self.done(QDialog.Accepted)
def fetch(self): """ Fetch Occurrence records for selected taxon. """ QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) QgsMessageLog.logMessage('Fetching occurrences', 'SpeciesExplorer', 0) name = self.results_list.selectedItems()[0].text() end_of_records = False offset = 0 layer = QgsVectorLayer('Point', name, 'memory') layer.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) provider = layer.dataProvider() counter = 0 while not end_of_records: url = ('https://api.gbif.org/v1/occurrence/search?' 'scientificName=%s&offset=%i' % (name, offset)) offset += 100 result = gbif_GET(url, None) count = int(result['count']) end_of_records = result['endOfRecords'] records = result['results'] QgsMessageLog.logMessage( 'Fetching record %s of %s occurrences' % (offset, count), 'SpeciesExplorer', 0) # Will populate this in create_fields call if len(records) == 0: QgsMessageLog.logMessage('No records found', 'SpeciesExplorer', 0) QMessageBox.information(self, 'Species Explorer', 'No records found for %s' % name) return field_lookups = self.create_fields(layer, records[0]) QgsMessageLog.logMessage('Field lookup: %s' % field_lookups, 'SpeciesExplorer', 0) for record in records: QgsMessageLog.logMessage('Record: %s' % record, 'SpeciesExplorer', 0) if ('decimalLongitude' not in record or 'decimalLatitude' not in record): continue feature = QgsFeature() feature.setGeometry( QgsGeometry.fromPointXY( QgsPointXY(record['decimalLongitude'], record['decimalLatitude']))) attributes = [counter] for key in field_lookups: try: attributes.append(record[key]) except KeyError: # just append an empty item to make sure the list # size is correct attributes.append('') feature.setAttributes(attributes) provider.addFeatures([feature]) counter += 1 if offset > count: end_of_records = True QgsMessageLog.logMessage('End of records: %s' % end_of_records, 'SpeciesExplorer', 0) layer.commitChanges() QgsProject.instance().addMapLayer(layer) # recursively walk back the cursor to a pointer while QgsApplication.instance().overrideCursor() is not None and \ QgsApplication.instance().overrideCursor().shape() == \ QtCore.Qt.WaitCursor: QgsApplication.instance().restoreOverrideCursor()
def enable_busy_cursor(self): """Set the hourglass enabled.""" QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor) )
def setCursor(self, cursor): self.cursor = QtGui.QCursor(cursor)
def __init__(self, canvas, button): qgis.gui.QgsMapTool.__init__(self, canvas) self.canvas = canvas self.cursor = QtGui.QCursor(QtCore.Qt.CrossCursor) self.button = button
def accept(self): """Handler for when OK is clicked.""" input_path = self.input_path.text() input_title = self.line_edit_title.text() input_source = self.line_edit_source.text() output_path = self.output_path.text() if not output_path.endswith('.tif'): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, tr('InaSAFE'), tr('Output file name must be tif file')) if not os.path.exists(input_path): # noinspection PyArgumentList,PyCallByClass,PyTypeChecker QMessageBox.warning(self, tr('InaSAFE'), tr('Input file does not exist')) return algorithm = 'nearest' if self.nearest_mode.isChecked(): algorithm = 'nearest' elif self.inverse_distance_mode.isChecked(): algorithm = 'invdist' elif self.use_ascii_mode.isChecked(): algorithm = 'use_ascii' # Smoothing smoothing_method = NONE_SMOOTHING if self.numpy_smoothing.isChecked(): smoothing_method = NUMPY_SMOOTHING if self.scipy_smoothing.isChecked(): smoothing_method = SCIPY_SMOOTHING # noinspection PyUnresolvedReferences QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor)) extra_keywords = {} if self.check_box_custom_shakemap_id.isChecked(): event_id = self.line_edit_shakemap_id.text() extra_keywords[extra_keyword_earthquake_event_id['key']] = event_id current_index = self.combo_box_source_type.currentIndex() source_type = self.combo_box_source_type.itemData(current_index) if source_type: extra_keywords[ extra_keyword_earthquake_source['key']] = source_type file_name = convert_mmi_data(input_path, input_title, input_source, output_path, algorithm=algorithm, algorithm_filename_flag=True, smoothing_method=smoothing_method, extra_keywords=extra_keywords) file_info = QFileInfo(file_name) base_name = file_info.baseName() self.output_layer = QgsRasterLayer(file_name, base_name) # noinspection PyUnresolvedReferences QgsApplication.instance().restoreOverrideCursor() if self.load_result.isChecked(): # noinspection PyTypeChecker mmi_ramp_roman(self.output_layer) self.output_layer.saveDefaultStyle() if not self.output_layer.isValid(): LOGGER.debug("Failed to load") else: # noinspection PyArgumentList QgsProject.instance().addMapLayer(self.output_layer) iface.zoomToActiveLayer() if (self.keyword_wizard_checkbox.isChecked() and self.keyword_wizard_checkbox.isEnabled()): self.launch_keyword_wizard() self.done(self.Accepted)
def enable_busy_cursor(): """Set the hourglass enabled and stop listening for layer changes.""" QgsApplication.instance().setOverrideCursor( QtGui.QCursor(QtCore.Qt.WaitCursor))
def set_cursor(self, cursor_shape): cursor = QtGui.QCursor() cursor.setShape(cursor_shape) self.iface.mapCanvas().setCursor(cursor)
def activatePickTool(self): aoi_list = [sec.aoi_as_ogr() for sec in self.WSMProj.sections] tool = WSMPickTool(self.iface, aoi_list, self) c = QtGui.QCursor(bm, bm) self.iface.mapCanvas().setCursor(c) self.iface.mapCanvas().setMapTool(tool)