def run(self): """Run method that performs all the real work""" # Do some initialisations # The progressbar self.dlg.progressBar.setValue(0.0) # Prepare for sorting layers = QgsProject.instance().mapLayers() layerslist = [] for id in layers.keys(): if layers[id].type() == QgsMapLayer.VectorLayer: if not layers[id].isValid(): QMessageBox.information(None, self.tr('Information'), 'Layer ' + layers[id].name() + ' is not valid') else: if (layers[id].geometryType() == QgsWkbTypes.PointGeometry): layerslist.append((layers[id].name(), id)) # Sort the layers by name layerslist.sort(key=lambda x: x[0], reverse=False) # Add to the input layer combobox self.dlg.InputLayer.clear() for layerdescription in layerslist: self.dlg.InputLayer.addItem(layerdescription[0], layerdescription[1]) # show the dialog self.dlg.show()
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 canvasReleaseEvent(self, e): point = self.plugin.transform( self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(e.x(), e.y()) ) QApplication.setOverrideCursor(Qt.WaitCursor) fs = self.plugin.highlight( where=u"st_contains(wkb_geometry,st_geomfromtext('POINT(%.3lf %.3lf)'::text,%d))" % ( point.x(), point.y(), self.plugin.getepsg() ) ) if len(fs) == 0: QApplication.restoreOverrideCursor() QMessageBox.information(None, u"Fehler", u"Kein Flurstück gefunden.") return try: s = QSettings("norBIT", "EDBSgen/PRO") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("localhost", int(s.value("norGISPort", "6102")))) sock.send("NORGIS_MAIN#EDBS#ALBKEY#{}#".format(fs[0]['flsnr']).encode("utf-8")) sock.close() if win32: window = win32gui.FindWindow(None, s.value("albWin", "norGIS")) win32gui.SetForegroundWindow(window) except socket.error: QMessageBox.information(None, u"Fehler", u"Verbindung zu norGIS schlug fehl.") QApplication.restoreOverrideCursor()
def canvasReleaseEvent(self, e): point = self.iface.mapCanvas().getCoordinateTransform().toMapCoordinates(e.x(), e.y()) point = self.plugin.transform(point) p = "POINT(%.3lf %.3lf)" % (point.x(), point.y()) try: QApplication.setOverrideCursor(Qt.WaitCursor) fs = self.plugin.retrieve(u"st_contains(wkb_geometry,st_geomfromtext('{}'::text,{}))".format( p, self.plugin.getepsg() )) if not self.plugin.logQuery("eigentuemerInfo", p, [i['flsnr'] for i in fs]): QMessageBox.information(None, u"Hinweis", u"Flurstücke werden ohne Protokollierung nicht angezeigt.") return if len(fs) == 0: QMessageBox.information(None, u"Hinweis", u"Kein Flurstück gefunden.") return fs = self.plugin.highlight(fs=fs, zoomTo=False) finally: QApplication.restoreOverrideCursor() page = self.getPage(fs) if page is not None: Info.showInfo(self.plugin, page, fs[0]['gmlid'], self.iface.mainWindow())
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 searchForRaster(self, path): """ Checks if a raster from a saved project is present in the table of content or exists at the given location (path). """ rasterFound = False availRaster = self.getAvailableRaster() for rlyr in availRaster: lyrPath = rlyr.grid.dataProvider().dataSourceUri() if lyrPath == path: self.setRaster(rlyr.name) rasterFound = True self.setCorrectRasterInField(rlyr.name) break if not rasterFound: if os.path.exists(path): baseName = QFileInfo(path).baseName() rlayer = QgsRasterLayer(path, baseName) QgsProject.instance().addMapLayer(rlayer) self.updateRasterList() self.setCorrectRasterInField(baseName) self.setRaster(baseName) self.draw.setEnabled(True) else: txt = "Raster mit dem Pfad {} ist " \ "nicht vorhanden".format(path) title = "Fehler beim Laden des Rasters" QMessageBox.information(self, title, txt)
def currentIndex(self): """ returns row index of selected index """ sel = self.viewIndexes.selectionModel() indexes = sel.selectedRows() if len(indexes) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("No indices were selected.")) return -1 return indexes[0].row()
def finish(self, algorithm_results): for count, results in enumerate(algorithm_results): self.loadHTMLResults(results, count) self.createSummaryTable(algorithm_results) self.mainWidget().setEnabled(True) QMessageBox.information(self, self.tr('Batch processing'), self.tr('Batch processing completed'))
def display(self): # Only display the results if some constraints were detected if self.resModel.rowCount() == 0: QMessageBox.information(self.iface.mainWindow(), 'No constraints found', 'The query did not locate any constraints.') return crd = ConstraintResultsDialog(self.resModel) crd.exec_()
def currentColumn(self): """ returns row index of selected column """ sel = self.viewFields.selectionModel() indexes = sel.selectedRows() if len(indexes) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("nothing selected")) return -1 return indexes[0].row()
def currentConstraint(self): """ returns row index of selected index """ sel = self.viewConstraints.selectionModel() indexes = sel.selectedRows() if len(indexes) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("Nothing selected")) return -1 return indexes[0].row()
def _displayThemeStateChanged(self, p_theme, p_state): """ give a warning to user that KLIC message could not be read from selected folder """ l_titleMsg = "Status Thema Gewijzigd" l_msg = "Status is nu %s voor thema %s" % (p_state, str(p_theme)) QMessageBox.information(self, l_titleMsg, l_msg)
def deleteField(self): """ delete selected field """ row = self.selectedField() if row is None: QMessageBox.information(self, self.tr("DB Manager"), self.tr("no field selected")) else: self.fields.model().removeRows(row, 1) self.updatePkeyCombo()
def createTable(self): """ create table with chosen fields, optionally add a geometry column """ if not self.hasSchemas: schema = None else: schema = str(self.cboSchema.currentText()) if len(schema) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("select schema!")) return table = str(self.editName.text()) if len(table) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("enter table name!")) return m = self.fields.model() if m.rowCount() == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("add some fields!")) return useGeomColumn = self.chkGeomColumn.isChecked() if useGeomColumn: geomColumn = str(self.editGeomColumn.text()) if len(geomColumn) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("set geometry column name")) return geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()] geomDim = self.spinGeomDim.value() try: geomSrid = int(self.editGeomSrid.text()) except ValueError: geomSrid = 0 useSpatialIndex = self.chkSpatialIndex.isChecked() flds = m.getFields() pk_index = self.cboPrimaryKey.currentIndex() if pk_index >= 0: flds[pk_index].primaryKey = True # commit to DB QApplication.setOverrideCursor(Qt.WaitCursor) try: if not useGeomColumn: self.db.createTable(table, flds, schema) else: geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex self.db.createVectorTable(table, flds, geom, schema) except (ConnectionError, DbError) as e: DlgDbError.showError(e, self) return finally: QApplication.restoreOverrideCursor() QMessageBox.information(self, self.tr("Good"), self.tr("everything went fine"))
def sourceRoads_show(self): if self.sources_roads_layer_comboBox.currentText() == "": QMessageBox.information(self, self.tr("opeNoise - Calculate Noise Levels"), self.tr("Please specify the roads sources layer.")) return False else: d = do_SourceDetailsRoads.Dialog(self.iface, self.sources_roads_layer_comboBox.currentText()) d.setWindowModality(Qt.ApplicationModal) d.show() d.exec_()
def HelpParameters_show(self): QMessageBox.information(self, self.tr("opeNoise - Help"), self.tr(''' <p><strong>Research ray:</strong>maximum distance of influence of the source to the receiver in meters. Receivers points beyond research ray return -99 value. A smaller research ray reduce the calculation time with consequent loss of precision in sound levels.</p> <p><strong>Atmospheric absorption:</strong> enter air temperature and relative humidity, in accordance with the ISO 9613 - 1</p> <p><strong>Lden definition: </strong>in accordance with the Directive 2002/49/CE and the regulation of the specific nation. The plugin automatically calculates the value of Lden when data referred to the three reference periods are set (Day, Evening, Night).</p> <p> </p> '''))
def finish(self): for count, alg in enumerate(self.algs): self.loadHTMLResults(alg, count) self.createSummaryTable() QApplication.restoreOverrideCursor() self.mainWidget.setEnabled(True) QMessageBox.information(self, self.tr("Batch processing"), self.tr("Batch processing completed"))
def navigate(self): """manage navigation / paging""" caller = self.sender().objectName() if caller == 'btnFirst': self.startfrom = 0 elif caller == 'btnLast': self.startfrom = self.catalog.results['matches'] - self.maxrecords elif caller == 'btnNext': self.startfrom += self.maxrecords if self.startfrom >= self.catalog.results["matches"]: msg = self.tr('End of results. Go to start?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = 0 else: return elif caller == "btnPrev": self.startfrom -= self.maxrecords if self.startfrom <= 0: msg = self.tr('Start of results. Go to end?') res = QMessageBox.information(self, self.tr('Navigation'), msg, (QMessageBox.Ok | QMessageBox.Cancel)) if res == QMessageBox.Ok: self.startfrom = (self.catalog.results['matches'] - self.maxrecords) else: return QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) try: self.catalog.getrecords2(constraints=self.constraints, maxrecords=self.maxrecords, startposition=self.startfrom, esn='full') except ExceptionReport as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Search error'), self.tr('Search error: %s') % err) return except Exception as err: QApplication.restoreOverrideCursor() QMessageBox.warning(self, self.tr('Connection error'), self.tr('Connection error: %s') % err) return QApplication.restoreOverrideCursor() self.display_results()
def createComment(self): #Function that add a comment to the selected table try: #Using the db connector, executing de SQL query Comment on table self.db.connector._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS E\'{2}\';'.format(self.table.schema().name, self.table.name, self.viewComment.text())) except DbError as e: DlgDbError.showError(e, self) return self.refresh() #Display successful message QMessageBox.information(self, self.tr("Add comment"), self.tr("Table successfully commented"))
def saveFiles(self): if (not self.distancesAndAzimuths) or (not self.points): QMessageBox.information(self.iface.mainWindow(), self.tr("Warning!"), self.tr("Click on calculate button first to generate the needed data.")) else: confrontingList = list() for i in range(self.tableWidget.rowCount()): item = self.tableWidget.item(i, 7) confrontingList.append(item.text()) d = MemorialGenerator(self.iface.mapCanvas().currentLayer().crs().description(), self.centralMeridian, self.lineEdit.text(), self.tableWidget, self.area, self.perimeter) d.exec_()
def createTable(self): """ create table with chosen fields, optionally add a geometry column """ if not self.hasSchemas: schema = None else: schema = str(self.cboSchema.currentText()) if len(schema) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("A valid schema must be selected first.")) return table = str(self.editName.text()) if len(table) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("A valid table name is required.")) return m = self.fields.model() if m.rowCount() == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("At least one field is required.")) return useGeomColumn = self.chkGeomColumn.isChecked() if useGeomColumn: geomColumn = str(self.editGeomColumn.text()) if len(geomColumn) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("A name is required for the geometry column.")) return geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()] geomDim = self.spinGeomDim.value() try: geomSrid = int(self.editGeomSrid.text()) except ValueError: geomSrid = 0 useSpatialIndex = self.chkSpatialIndex.isChecked() flds = m.getFields() pk_index = self.cboPrimaryKey.currentIndex() if pk_index >= 0: flds[pk_index].primaryKey = True # commit to DB with OverrideCursor(Qt.WaitCursor): try: if not useGeomColumn: self.db.createTable(table, flds, schema) else: geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex self.db.createVectorTable(table, flds, geom, schema) except (ConnectionError, DbError) as e: DlgDbError.showError(e, self) return QMessageBox.information(self, self.tr("DB Manager"), self.tr("Table created successfully."))
def createFiles(self): self.copyAndRenameFiles() self.createSelo() self.createFullMemorial() self.createArea() self.createSimpleMemorial() QMessageBox.information(self, self.tr('Information!'), self.tr('Files created successfully!'))
def fillTable(self): """Makes the CSV. """ decimalPlaces = self.spinBox.value() q = Decimal(10)**-decimalPlaces distancesAndAzimuths = list() isValid = self.isValidType() if isValid: distancesAndAzimuths = self.calculate() try: convergence = float(self.lineEdit.text()) except ValueError: QMessageBox.information(self.iface.mainWindow(), self.tr("Warning!"), self.tr("Please, insert the meridian convergence.")) return isClosed = False if self.points[0] == self.points[len(self.points) - 1]: isClosed = True self.tableWidget.setRowCount(len(distancesAndAzimuths)) prefix = self.prefixEdit.text() for i in range(0,len(distancesAndAzimuths)): azimuth = self.dd2dms(distancesAndAzimuths[i][1]) realAzimuth = self.dd2dms(distancesAndAzimuths[i][1] + convergence) itemVertex = QTableWidgetItem(prefix+str(i)) self.tableWidget.setItem(i, 0, itemVertex) e = Decimal(self.points[i].x()).quantize(q) itemE = QTableWidgetItem(str(e)) self.tableWidget.setItem(i, 1, itemE) n = Decimal(self.points[i].y()).quantize(q) itemN = QTableWidgetItem(str(n)) self.tableWidget.setItem(i, 2, itemN) if (i == len(distancesAndAzimuths) - 1) and isClosed: itemSide = QTableWidgetItem(prefix+str(i)+"-{}0".format(prefix)) self.tableWidget.setItem(i, 3, itemSide) else: itemSide = QTableWidgetItem(prefix+str(i)+"-{}".format(prefix)+str(i+1)) self.tableWidget.setItem(i, 3, itemSide) itemAz = QTableWidgetItem(azimuth) self.tableWidget.setItem(i, 4, itemAz) itemRealAz = QTableWidgetItem(realAzimuth) self.tableWidget.setItem(i, 5, itemRealAz) dist = "%0.2f"%(distancesAndAzimuths[i][0]) itemDistance = QTableWidgetItem(dist) self.tableWidget.setItem(i, 6, itemDistance) itemConfronting = QTableWidgetItem("") self.tableWidget.setItem(i, 7, itemConfronting)
def controls(self): self.run_buttonBox.setEnabled( False ) if self.layer_comboBox.currentText() == "": QMessageBox.information(self, self.tr("opeNoise - Apply Noise Symbology"), self.tr("Please specify the input vector layer.")) return 0 if self.level_comboBox.currentText() == "": message = self.tr("Please specify the level field to apply") + "\n" + self.tr("the noise symbology.") QMessageBox.information(self, self.tr("opeNoise - Apply Noise Symbology"), self.tr(message)) return 0 return 1
def createComment(self): """Adds a comment to the selected table""" try: schem = self.table.schema().name tab = self.table.name com = self.viewComment.text() self.db.connector.commentTable(schem, tab, com) except DbError as e: DlgDbError.showError(e, self) return self.refresh() #Display successful message QMessageBox.information(self, self.tr("Add comment"), self.tr("Table successfully commented"))
def reload_saved_settings(self): saved_settings, __ = QFileDialog.getOpenFileName(None,'Open file', on_Settings.getOneSetting('directory_last') , "Settings (*.xml);;All files (*)") if saved_settings is None or saved_settings == "": return try: on_Settings.copySavedSettingsToSettings(saved_settings) self.reload_settings() except: QMessageBox.information(self, self.tr("opeNoise - Calculate Noise Levels"), self.tr("Sorry, but somethigs wrong in import saved settings."))
def show_about_dialog(self): infoString = self.tr( u"Geosearch DK lader brugeren zoome til navngivne steder i Danmark.<br />" u"Pluginet benytter tjenesten 'geosearch' fra <a href=\"http://kortforsyningen.dk/\">kortforsyningen.dk</a>" u" og kræver derfor et gyldigt login til denne tjeneste.<br />" u"Pluginets webside: <a href=\"http://github.com/Septima/qgis-geosearch\">github.com/Septima/qgis-geosearch</a><br />" u"Udviklet af: Septima<br />" u"Mail: <a href=\"mailto:[email protected]\">[email protected]</a><br />" u"Web: <a href=\"http://www.septima.dk\">www.septima.dk</a>\n" ) QMessageBox.information( self.qgisIface.mainWindow(), "Om Geosearch DK", infoString )
def deleteComment(self): #Function that drop the comment to the selected table try: #Using the db connector, executing de SQL query Comment on table using the NULL definition self.db.connector._execute(None, 'COMMENT ON TABLE "{0}"."{1}" IS NULL;'.format(self.table.schema().name, self.table.name)) except DbError as e: DlgDbError.showError(e, self) return self.refresh() #Refresh line edit, put a void comment self.viewComment.setText('') #Display successful message QMessageBox.information(self, self.tr("Delete comment"), self.tr("Comment deleted"))
def confirm(self): # runs when OK button is pressed # initialise input parameters self.BASE_LAYER = self.dlg.ui.comboBase.currentItemData() self.SECONDARY_LAYER = self.dlg.ui.comboSecondary.currentItemData() self.SURFACE_LAYER = self.dlg.ui.comboSurface.currentItemData() self.LOCALITIES_LAYER = self.dlg.ui.comboLocalities.currentItemData() self.TAXON_FIELD_INDEX = self.dlg.ui.comboTaxonField.currentItemData()[0] self.GRID_LAYER = self.dlg.ui.comboGrid.currentItemData() self.X_MIN = float(self.dlg.ui.leMinX.text()) self.Y_MIN = float(self.dlg.ui.leMinY.text()) self.X_MAX = float(self.dlg.ui.leMaxX.text()) self.Y_MAX = float(self.dlg.ui.leMaxY.text()) self.OUT_WIDTH = self.dlg.ui.spnOutWidth.value() self.OUT_HEIGHT = self.dlg.ui.spnOutHeight.value() self.OUT_DIR = self.dlg.ui.leOutDir.text() try: self.getUniqueValues() except: message = "Could not get unique values from localities layer. " message += "Check that the localities layer and taxon identifier " message += "field are properly specified." QMessageBox.information(self.dlg,"Distribution Map Generator", message) return question = "This will generate " + str(self.UNIQUE_COUNT) question += " maps. Are you sure you want to continue?" reply = QMessageBox.question(self.dlg,'Distribution Map Generator', question, QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) self.GRID_INDEX = QgsSpatialIndex() for feat in getLayerFromId(self.GRID_LAYER).getFeatures(): self.GRID_INDEX.insertFeature(feat) if reply == QMessageBox.Yes: try: self.process() except QgsCsException: return except Exception as ex: log(ex) return QMessageBox.information(self.dlg,"Distribution Map Generator", "Map processing complete.") self.dlg.ui.progressBar.setValue(0) QDialog.accept(self.dlg) else: return
def accept(self): self.run_buttonBox.setEnabled( False ) if self.controls() == 0: self.run_buttonBox.setEnabled( True ) return self.log_start() layer = QgsProject.instance().mapLayersByName(self.layer_comboBox.currentText())[0] field = self.level_comboBox.currentText() # writes the settings log file self.time_start = datetime.now() # Run try: on_ApplyNoiseSymbology.renderizeXY(layer, field) run = 1 except: error= traceback.format_exc() log_errors.write(error) run = 0 self.time_end = datetime.now() if run == 1: log_errors.write(self.tr("No errors.") + "\n\n") result_string = self.tr("Noise symbology assigned with success.") + "\n\n" +\ self.tr("Start: ") + self.time_start.strftime("%a %d/%b/%Y %H:%M:%S") + "\n" +\ self.tr("End: ") + self.time_end.strftime("%a %d/%b/%Y %H:%M:%S") + "\n"+\ self.tr("Duration: ") + str(self.duration()) QMessageBox.information(self, self.tr("opeNoise - Apply Noise Symbology"), self.tr(result_string)) # self.iface.messageBar().pushMessage(self.tr("opeNoise - Apply Noise Symbology"), self.tr("Process complete")) else: result_string = self.tr("Sorry, process not complete.") + "\n\n" +\ self.tr("View the log file to understand the problem:") + "\n" +\ str(log_errors_path_name) + "\n\n" +\ self.tr("Start: ") + self.time_start.strftime("%a %d/%b/%Y %H:%M:%S.%f") + "\n" +\ self.tr("End: ") + self.time_end.strftime("%a %d/%b/%Y %H:%M:%S.%f") + "\n"+\ self.tr("Duration: ") + str(self.duration()) QMessageBox.information(self, self.tr("opeNoise - Apply Noise Symbology"), self.tr(result_string)) # self.iface.messageBar().pushMessage("opeNoise - Apply Noise Symbology", "Process not complete") self.log_end() self.run_buttonBox.setEnabled( True ) # self.iface.mainWindow().statusBar().clearMessage() # self.iface.mapCanvas().refresh() self.close()
def onShowInfoFieldQ(self): msg = self.tr('Erklaerung Gesamtlast') QMessageBox.information(self, self.tr("Gesamtlast"), msg, QMessageBox.Ok)
def showMessage(self, msg, msg_type="Info"): if self.showQMessagesEnabled(): QMessageBox.information(self.iface.mainWindow(), msg_type, msg)
def success_msg(self, text): QMessageBox.information(self.dlg.show(), self.tr("Corridor Detection:Information"), self.tr(str(text)), QMessageBox.Ok)
def accept(self): if self.mode == self.ASK_FOR_INPUT_MODE: # create the input layer (if not already done) and # update available options self.reloadInputLayer() # sanity checks if self.inLayer is None: QMessageBox.information(self, self.tr("Import to database"), self.tr("Input layer missing or not valid")) return if self.cboTable.currentText() == "": QMessageBox.information(self, self.tr("Import to database"), self.tr("Output table name is required")) return if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): try: sourceSrid = self.editSourceSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid source srid: must be an integer")) return if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): try: targetSrid = self.editTargetSrid.text() except ValueError: QMessageBox.information(self, self.tr("Import to database"), self.tr("Invalid target srid: must be an integer")) return with OverrideCursor(Qt.WaitCursor): # store current input layer crs and encoding, so I can restore it prevInCrs = self.inLayer.crs() prevInEncoding = self.inLayer.dataProvider().encoding() try: schema = self.outUri.schema() if not self.cboSchema.isEnabled() else self.cboSchema.currentText() table = self.cboTable.currentText() # get pk and geom field names from the source layer or use the # ones defined by the user srcUri = QgsDataSourceUri(self.inLayer.source()) pk = srcUri.keyColumn() if not self.chkPrimaryKey.isChecked() else self.editPrimaryKey.text() if not pk: pk = self.default_pk if self.inLayer.isSpatial() and self.chkGeomColumn.isEnabled(): geom = srcUri.geometryColumn() if not self.chkGeomColumn.isChecked() else self.editGeomColumn.text() if not geom: geom = self.default_geom else: geom = None options = {} if self.chkLowercaseFieldNames.isEnabled() and self.chkLowercaseFieldNames.isChecked(): pk = pk.lower() if geom: geom = geom.lower() options['lowercaseFieldNames'] = True # get output params, update output URI self.outUri.setDataSource(schema, table, geom, "", pk) typeName = self.db.dbplugin().typeName() providerName = self.db.dbplugin().providerName() if typeName == 'gpkg': uri = self.outUri.database() options['update'] = True options['driverName'] = 'GPKG' options['layerName'] = table else: uri = self.outUri.uri(False) if self.chkDropTable.isChecked(): options['overwrite'] = True if self.chkSinglePart.isEnabled() and self.chkSinglePart.isChecked(): options['forceSinglePartGeometryType'] = True outCrs = QgsCoordinateReferenceSystem() if self.chkTargetSrid.isEnabled() and self.chkTargetSrid.isChecked(): targetSrid = int(self.editTargetSrid.text()) outCrs = QgsCoordinateReferenceSystem(targetSrid) # update input layer crs and encoding if self.chkSourceSrid.isEnabled() and self.chkSourceSrid.isChecked(): sourceSrid = int(self.editSourceSrid.text()) inCrs = QgsCoordinateReferenceSystem(sourceSrid) self.inLayer.setCrs(inCrs) if self.chkEncoding.isEnabled() and self.chkEncoding.isChecked(): enc = self.cboEncoding.currentText() self.inLayer.setProviderEncoding(enc) onlySelected = self.chkSelectedFeatures.isChecked() # do the import! ret, errMsg = QgsVectorLayerExporter.exportLayer(self.inLayer, uri, providerName, outCrs, onlySelected, options) except Exception as e: ret = -1 errMsg = str(e) finally: # restore input layer crs and encoding self.inLayer.setCrs(prevInCrs) self.inLayer.setProviderEncoding(prevInEncoding) if ret != 0: output = QgsMessageViewer() output.setTitle(self.tr("Import to database")) output.setMessageAsPlainText(self.tr("Error {0}\n{1}").format(ret, errMsg)) output.showMessage() return # create spatial index if self.chkSpatialIndex.isEnabled() and self.chkSpatialIndex.isChecked(): self.db.connector.createSpatialIndex((schema, table), geom) self.db.connection().reconnect() self.db.refresh() QMessageBox.information(self, self.tr("Import to database"), self.tr("Import was successful.")) return QDialog.accept(self)
def _push_message(self, title, text, level=0, duration=0): # QGIS >= 2.0 if hasattr(self.iface, 'messageBar') and hasattr(self.iface.messageBar(), 'pushMessage'): self.iface.messageBar().pushMessage(title, text, level, duration) else: QMessageBox.information(self, title, text)
def doRemoveRestriction(self): # pass control to MapTool and then deal with Proposals issues from there ?? QgsMessageLog.logMessage("In doRemoveRestriction", tag="TOMs panel") self.proposalsManager.TOMsToolChanged.emit() #self.mapTool = None # Get the current proposal from the session variables self.currProposalID = self.proposalsManager.currentProposal() if self.currProposalID > 0: ''' if self.actionRemoveRestriction.isChecked(): # self.iface.mapCanvas().setMapTool(CreateRestrictionTool) # self.actionCreateRestiction.setChecked(True) # set TOMs layer as active layer (for editing)... QgsMessageLog.logMessage("In doRemoveRestriction - tool activated", tag="TOMs panel") #self.TOMslayer = QgsMapLayerRegistry.instance().mapLayersByName("TOMs_Layer")[0] #iface.setActiveLayer(self.TOMslayer) self.mapTool = RemoveRestrictionTool(self.iface, self.onRemoveRestriction) self.mapTool.setAction(self.actionRemoveRestriction) self.iface.mapCanvas().setMapTool(self.mapTool) # self.currLayer.editingStopped.connect (self.proposalsManager.updateMapCanvas) else: QgsMessageLog.logMessage("In doRemoveRestriction - tool deactivated", tag="TOMs panel") self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None self.actionRemoveRestriction.setChecked(False) ''' currRestrictionLayer = self.iface.activeLayer() #currRestrictionLayer.editingStopped.connect(self.proposalsManager.updateMapCanvas) if currRestrictionLayer: QgsMessageLog.logMessage( "In doRemoveRestriction. currLayer: " + str(currRestrictionLayer.name()), tag="TOMs panel") if currRestrictionLayer.selectedFeatureCount() > 0: selectedRestrictions = currRestrictionLayer.selectedFeatures( ) self.restrictionTransaction.startTransactionGroup() for currRestriction in selectedRestrictions: self.onRemoveRestriction(currRestrictionLayer, currRestriction) else: reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Select restriction for delete", QMessageBox.Ok) pass else: """if self.actionRemoveRestriction.isChecked(): self.actionRemoveRestriction.setChecked(False) if self.mapTool == None: self.actionRemoveRestriction.setChecked(False)""" reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Changes to current data are not allowed. Changes are made via Proposals", QMessageBox.Ok) pass
def sync_project(self): if not self.path: return if not self._unsaved_changes_check(): return pull_changes, push_changes, push_changes_summary = self.mc.project_status( self.path) if not sum( len(v) for v in list(pull_changes.values()) + list(push_changes.values())): QMessageBox.information(None, 'Project sync', 'Project is already up-to-date', QMessageBox.Close) return dlg = SyncDialog() dlg.pull_start(self.mc, self.path, self.project_name) dlg.exec_() # blocks until success, failure or cancellation if dlg.exception: # pull failed for some reason if isinstance(dlg.exception, LoginError): login_error_message(dlg.exception) elif isinstance(dlg.exception, ClientError): QMessageBox.critical(None, "Project sync", "Client error: " + str(dlg.exception)) else: unhandled_exception_message( dlg.exception_details(), "Project sync", f"Failed to sync project {self.project_name} due to an unhandled exception." ) return if dlg.pull_conflicts: msg = "Following conflicts between local and server version found: \n\n" for item in dlg.pull_conflicts: msg += item + "\n" msg += "\nYou may want to fix them before upload otherwise they will be uploaded as new files. " \ "Do you wish to proceed?" btn_reply = QMessageBox.question(None, 'Conflicts found', msg, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if btn_reply == QMessageBox.No: QApplication.restoreOverrideCursor() return if not dlg.is_complete: # we were cancelled return # pull finished, start push if any(push_changes.values()) and not self._have_writing_permissions(): QMessageBox.information( None, "Project sync", "You have no writing rights to this project", QMessageBox.Close) return dlg = SyncDialog() dlg.push_start(self.mc, self.path, self.project_name) dlg.exec_() # blocks until success, failure or cancellation self._reload_project( ) # TODO: only reload project if we pulled a newer version if dlg.exception: # push failed for some reason if isinstance(dlg.exception, LoginError): login_error_message(dlg.exception) elif isinstance(dlg.exception, ClientError): QMessageBox.critical(None, "Project sync", "Client error: " + str(dlg.exception)) else: unhandled_exception_message( dlg.exception_details(), "Project sync", f"Failed to sync project {self.project_name} due to an unhandled exception." ) return if dlg.is_complete: # TODO: report success only when we have actually done anything msg = "Mergin project {} synchronized successfully".format( self.project_name) QMessageBox.information(None, 'Project sync', msg, QMessageBox.Close) else: # we were cancelled - but no need to show a message box about that...? pass
def doRestrictionDetails(self): """ Select point and then display details """ QgsMessageLog.logMessage("In doRestrictionDetails", tag="TOMs panel") self.proposalsManager.TOMsToolChanged.emit() # Get the current proposal from the session variables currProposalID = self.proposalsManager.currentProposal() currRestrictionLayer = self.iface.activeLayer() if currRestrictionLayer: QgsMessageLog.logMessage( "In doRestrictionDetails. currLayer: " + str(currRestrictionLayer.name() + " Nr feats: " + str(currRestrictionLayer.selectedFeatureCount())), tag="TOMs panel") if currRestrictionLayer.selectedFeatureCount() > 0: if currProposalID == 0: # Ensure that no updates can occur for Proposal = 0 self.restrictionTransaction.rollBackTransactionGroup( ) # stop any editing else: self.restrictionTransaction.startTransactionGroup( ) # start editing selectedRestrictions = currRestrictionLayer.selectedFeatures() for currRestriction in selectedRestrictions: #self.restrictionForm = BayRestrictionForm(currRestrictionLayer, currRestriction) #self.restrictionForm.show() QgsMessageLog.logMessage( "In restrictionFormOpen. currRestrictionLayer: " + str(currRestrictionLayer.name()), tag="TOMs panel") dialog = self.iface.getFeatureForm(currRestrictionLayer, currRestriction) self.setupRestrictionDialog( dialog, currRestrictionLayer, currRestriction, self.restrictionTransaction) # connects signals dialog.show() #self.iface.openFeatureForm(self.currRestrictionLayer, self.currRestriction) # Disconnect the signal that QGIS has wired up for the dialog to the button box. # button_box.accepted.disconnect(restrictionsDialog.accept) # Wire up our own signals. #button_box.accepted.connect(self.restrictionTypeUtils.onSaveRestrictionDetails, currRestriction, # currRestrictionLayer, self.dialog)) else: reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Select restriction first and then choose information button", QMessageBox.Ok) pass #currRestrictionLayer.deselect(currRestriction.id()) else: reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Select restriction first and then choose information button", QMessageBox.Ok) pass
def doCreateSignRestriction(self): QgsMessageLog.logMessage("In doCreateSignRestriction", tag="TOMs panel") self.proposalsManager.TOMsToolChanged.emit() self.mapTool = None # Get the current proposal from the session variables currProposalID = self.proposalsManager.currentProposal() if currProposalID > 0: if self.actionCreateSignRestriction.isChecked(): # self.iface.mapCanvas().setMapTool(CreateRestrictionTool) # self.actionCreateRestiction.setChecked(True) # set TOMs layer as active layer (for editing)... QgsMessageLog.logMessage( "In doCreateSignRestriction - tool activated", tag="TOMs panel") # self.restrictionTransaction.startTransactionGroup() #self.currLayer = QgsMapLayerRegistry.instance().mapLayersByName("Signs")[0] #currLayer = self.tableNames.SIGNS currLayer = self.proposalsManager.tableNames.TOMsLayerDict.get( "Signs") self.iface.setActiveLayer(currLayer) self.restrictionTransaction.startTransactionGroup() self.mapTool = CreateRestrictionTool( self.iface, currLayer, self.proposalsManager, self.restrictionTransaction) self.mapTool.setAction(self.actionCreateSignRestriction) self.iface.mapCanvas().setMapTool(self.mapTool) #self.currLayer.editingStopped.connect (self.proposalsManager.updateMapCanvas) else: QgsMessageLog.logMessage( "In doCreateSignRestriction - tool deactivated", tag="TOMs panel") self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None self.actionCreateSignRestriction.setChecked(False) #self.currLayer.editingStopped() else: if self.actionCreateSignRestriction.isChecked(): self.actionCreateSignRestriction.setChecked(False) if self.mapTool == None: self.actionCreateSignRestriction.setChecked(False) reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Changes to current data is not allowed. Changes are made via Proposals", QMessageBox.Ok) pass
def createTable(self): """Creates table with chosen fields, optionally add a geometry column """ if not self.hasSchemas: schema = None else: schema = str(self.cboSchema.currentText()) if len(schema) == 0: QMessageBox.information( self, self.tr("DB Manager"), self.tr("A valid schema must be selected first.")) return table = str(self.editName.text()) if len(table) == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("A valid table name is required.")) return m = self.fields.model() if m.rowCount() == 0: QMessageBox.information(self, self.tr("DB Manager"), self.tr("At least one field is required.")) return useGeomColumn = self.chkGeomColumn.isChecked() if useGeomColumn: geomColumn = str(self.editGeomColumn.text()) if len(geomColumn) == 0: QMessageBox.information( self, self.tr("DB Manager"), self.tr("A name is required for the geometry column.")) return geomType = self.GEOM_TYPES[self.cboGeomType.currentIndex()] geomDim = self.spinGeomDim.value() try: geomSrid = int(self.editGeomSrid.text()) except ValueError: geomSrid = 0 useSpatialIndex = self.chkSpatialIndex.isChecked() flds = m.getFields() pk_index = self.cboPrimaryKey.currentIndex() if pk_index >= 0: flds[pk_index].primaryKey = True # commit to DB with OverrideCursor(Qt.WaitCursor): try: if not useGeomColumn: self.db.createTable(table, flds, schema) else: geom = geomColumn, geomType, geomSrid, geomDim, useSpatialIndex self.db.createVectorTable(table, flds, geom, schema) except (ConnectionError, DbError) as e: DlgDbError.showError(e, self) return QMessageBox.information(self, self.tr("DB Manager"), self.tr("Table created successfully."))
def run(self): QMessageBox.information(None, u'Minimal plugin', u'Do something useful here')
def photoDetails_field(self, restrictionDialog, currRestrictionLayer, currRestriction): # Function to deal with photo fields self.demandDialog = restrictionDialog self.currDemandLayer = currRestrictionLayer self.currFeature = currRestriction TOMsMessageLog.logMessage("In photoDetails", level=Qgis.Info) photoPath = QgsExpressionContextUtils.projectScope(QgsProject.instance()).variable('PhotoPath') projectFolder = QgsExpressionContextUtils.projectScope(QgsProject.instance()).variable('project_folder') path_absolute = os.path.join(projectFolder, photoPath) if path_absolute == None: reply = QMessageBox.information(None, "Information", "Please set value for PhotoPath.", QMessageBox.Ok) return # Check path exists ... if os.path.isdir(path_absolute) == False: reply = QMessageBox.information(None, "Information", "PhotoPath folder " + str( path_absolute) + " does not exist. Please check value.", QMessageBox.Ok) return # if cv2 is available, check camera nr try: cameraNr = int(self.params.setParam("CameraNr")) except Exception as e: TOMsMessageLog.logMessage("In photoDetails_field: cameraNr issue: {}".format(e), level=Qgis.Info) if cv2_available: cameraNr = QMessageBox.information(None, "Information", "Please set value for CameraNr.", QMessageBox.Ok) cameraNr = None TOMsMessageLog.logMessage("In photoDetails_field: cameraNr is: {}".format(cameraNr), level=Qgis.Info) layerName = self.currDemandLayer.name() # Generate the full path to the file fileName1 = "Photos_01" fileName2 = "Photos_02" fileName3 = "Photos_03" idx1 = self.currDemandLayer.fields().indexFromName(fileName1) idx2 = self.currDemandLayer.fields().indexFromName(fileName2) idx3 = self.currDemandLayer.fields().indexFromName(fileName3) TOMsMessageLog.logMessage("In photoDetails. idx1: " + str(idx1) + "; " + str(idx2) + "; " + str(idx3), level=Qgis.Info) if cameraNr is not None: TOMsMessageLog.logMessage("Camera TRUE", level=Qgis.Info) takePhoto = True else: TOMsMessageLog.logMessage("Camera FALSE", level=Qgis.Info) takePhoto = False FIELD1 = self.demandDialog.findChild(QLabel, "Photo_Widget_01") FIELD2 = self.demandDialog.findChild(QLabel, "Photo_Widget_02") FIELD3 = self.demandDialog.findChild(QLabel, "Photo_Widget_03") if FIELD1: TOMsMessageLog.logMessage("In photoDetails. FIELD 1 exists", level=Qgis.Info) if self.currFeature[idx1]: newPhotoFileName1 = os.path.join(path_absolute, self.currFeature[idx1]) TOMsMessageLog.logMessage("In photoDetails. photo1: {}".format(newPhotoFileName1), level=Qgis.Info) else: newPhotoFileName1 = None pixmap1 = QPixmap(newPhotoFileName1) if pixmap1.isNull(): pass # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1)) else: tab = FIELD1.parentWidget() grid = FIELD1.parentWidget().layout() photo_Widget1 = imageLabel(tab) TOMsMessageLog.logMessage( "In photoDetails. FIELD 1 w: {}; h: {}".format(FIELD1.width(), FIELD1.height()), level=Qgis.Info) photo_Widget1.setObjectName("Photo_Widget_01") photo_Widget1.setText("No photo is here") #photo_Widget1 = imageLabel(tab) grid.addWidget(photo_Widget1, 0, 0, 1, 1) FIELD1.hide() FIELD1.setParent(None) FIELD1 = photo_Widget1 FIELD1.set_Pixmap(pixmap1) TOMsMessageLog.logMessage("In photoDetails. FIELD 1 Photo1: " + str(newPhotoFileName1), level=Qgis.Info) TOMsMessageLog.logMessage("In photoDetails.pixmap1 size: {}".format(pixmap1.size()), level=Qgis.Info) FIELD1.pixmapUpdated.connect(functools.partial(self.displayPixmapUpdated, FIELD1)) #ZOOM_IN_1 = self.demandDialog.findChild(QPushButton, "pb_zoomIn_01") #ZOOM_IN_1.clicked.connect(FIELD1._zoomInButton) #ZOOM_OUT_1 = self.demandDialog.findChild(QPushButton, "pb_zoomOut_01") #ZOOM_OUT_1.clicked.connect(FIELD1._zoomOutButton) if takePhoto: START_CAMERA_1 = self.demandDialog.findChild(QPushButton, "startCamera1") TAKE_PHOTO_1 = self.demandDialog.findChild(QPushButton, "getPhoto1") TAKE_PHOTO_1.setEnabled(False) self.camera1 = formCamera(path_absolute, newPhotoFileName1, cameraNr) START_CAMERA_1.clicked.connect( functools.partial(self.camera1.useCamera, START_CAMERA_1, TAKE_PHOTO_1, FIELD1)) self.camera1.notifyPhotoTaken.connect(functools.partial(self.savePhotoTaken, idx1)) if FIELD2: TOMsMessageLog.logMessage("In photoDetails. FIELD 2 exisits", level=Qgis.Info) if self.currFeature[idx2]: newPhotoFileName2 = os.path.join(path_absolute, self.currFeature[idx2]) TOMsMessageLog.logMessage("In photoDetails. Photo1: " + str(newPhotoFileName2), level=Qgis.Info) else: newPhotoFileName2 = None # newPhotoFileName2 = os.path.join(path_absolute, str(self.currFeature[idx2])) # newPhotoFileName2 = os.path.join(path_absolute, str(self.currFeature.attribute(fileName2))) # TOMsMessageLog.logMessage("In photoDetails. Photo2: " + str(newPhotoFileName2), level=Qgis.Info) pixmap2 = QPixmap(newPhotoFileName2) if pixmap2.isNull(): pass # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1)) else: tab = FIELD2.parentWidget() grid = FIELD2.parentWidget().layout() photo_Widget2 = imageLabel(tab) TOMsMessageLog.logMessage( "In photoDetails. FIELD 2 w: {}; h: {}".format(FIELD2.width(), FIELD2.height()), level=Qgis.Info) photo_Widget2.setObjectName("Photo_Widget_02") photo_Widget2.setText("No photo is here") #photo_Widget2 = imageLabel(tab) grid.addWidget(photo_Widget2, 0, 0, 1, 1) FIELD2.hide() FIELD2.setParent(None) FIELD2 = photo_Widget2 FIELD2.set_Pixmap(pixmap2) TOMsMessageLog.logMessage("In photoDetails. FIELD 2 Photo2: " + str(newPhotoFileName2), level=Qgis.Info) TOMsMessageLog.logMessage("In photoDetails.pixmap2 size: {}".format(pixmap2.size()), level=Qgis.Info) FIELD2.pixmapUpdated.connect(functools.partial(self.displayPixmapUpdated, FIELD2)) #ZOOM_IN_2 = self.demandDialog.findChild(QPushButton, "pb_zoomIn_02") #ZOOM_IN_2.clicked.connect(FIELD2._zoomInButton) #ZOOM_OUT_2 = self.demandDialog.findChild(QPushButton, "pb_zoomOut_02") #ZOOM_OUT_2.clicked.connect(FIELD2._zoomOutButton) """ FIELD2.setPixmap(pixmap2) FIELD2.setScaledContents(True) TOMsMessageLog.logMessage("In photoDetails. Photo2: " + str(newPhotoFileName2), level=Qgis.Info)""" if takePhoto: START_CAMERA_2 = self.demandDialog.findChild(QPushButton, "startCamera2") TAKE_PHOTO_2 = self.demandDialog.findChild(QPushButton, "getPhoto2") TAKE_PHOTO_2.setEnabled(False) self.camera2 = formCamera(path_absolute, newPhotoFileName2, cameraNr) START_CAMERA_2.clicked.connect( functools.partial(self.camera2.useCamera, START_CAMERA_2, TAKE_PHOTO_2, FIELD2)) self.camera2.notifyPhotoTaken.connect(functools.partial(self.savePhotoTaken, idx2)) if FIELD3: TOMsMessageLog.logMessage("In photoDetails. FIELD 3 exisits", level=Qgis.Info) if self.currFeature[idx3]: newPhotoFileName3 = os.path.join(path_absolute, self.currFeature[idx3]) TOMsMessageLog.logMessage("In photoDetails. Photo1: " + str(newPhotoFileName3), level=Qgis.Info) else: newPhotoFileName3 = None # newPhotoFileName3 = os.path.join(path_absolute, str(self.currFeature[idx3])) # newPhotoFileName3 = os.path.join(path_absolute, # str(self.currFeature.attribute(fileName3))) # newPhotoFileName3 = os.path.join(path_absolute, str(layerName + "_Photos_03")) # TOMsMessageLog.logMessage("In photoDetails. Photo3: " + str(newPhotoFileName3), level=Qgis.Info) pixmap3 = QPixmap(newPhotoFileName3) if pixmap3.isNull(): pass # FIELD1.setText('Picture could not be opened ({path})'.format(path=newPhotoFileName1)) else: tab = FIELD3.parentWidget() grid = FIELD3.parentWidget().layout() photo_Widget3 = imageLabel(tab) TOMsMessageLog.logMessage( "In photoDetails. FIELD 3 w: {}; h: {}".format(FIELD3.width(), FIELD3.height()), level=Qgis.Info) photo_Widget3.setObjectName("Photo_Widget_03") photo_Widget3.setText("No photo is here") #photo_Widget3 = imageLabel(tab) grid.addWidget(photo_Widget3, 0, 0, 1, 1) FIELD3.hide() FIELD3.setParent(None) FIELD3 = photo_Widget3 FIELD3.set_Pixmap(pixmap3) TOMsMessageLog.logMessage("In photoDetails. FIELD 3 Photo3: " + str(newPhotoFileName3), level=Qgis.Info) TOMsMessageLog.logMessage("In photoDetails.pixmap3 size: {}".format(pixmap3.size()), level=Qgis.Info) FIELD3.pixmapUpdated.connect(functools.partial(self.displayPixmapUpdated, FIELD3)) #ZOOM_IN_3 = self.demandDialog.findChild(QPushButton, "pb_zoomIn_03") #ZOOM_IN_3.clicked.connect(FIELD3._zoomInButton) #ZOOM_OUT_3 = self.demandDialog.findChild(QPushButton, "pb_zoomOut_03") #ZOOM_OUT_3.clicked.connect(FIELD3._zoomOutButton) """FIELD3.setPixmap(pixmap3) FIELD3.setScaledContents(True) TOMsMessageLog.logMessage("In photoDetails. Photo3: " + str(newPhotoFileName3), level=Qgis.Info)""" if takePhoto: START_CAMERA_3 = self.demandDialog.findChild(QPushButton, "startCamera3") TAKE_PHOTO_3 = self.demandDialog.findChild(QPushButton, "getPhoto3") TAKE_PHOTO_3.setEnabled(False) self.camera3 = formCamera(path_absolute, newPhotoFileName3, cameraNr) START_CAMERA_3.clicked.connect( functools.partial(self.camera3.useCamera, START_CAMERA_3, TAKE_PHOTO_3, FIELD3)) self.camera3.notifyPhotoTaken.connect(functools.partial(self.savePhotoTaken, idx3)) pass
def initGui(self): from .autoInstaller import checkInstallation checkInstallation( ["numexpr", "scipy", "h5py", "PIL", "Cython", "matplotlib", "skimage", "mako", "pyqtgraph", "pywt", "mkl", "lxml"], ["-c", "defaults", "-c", "conda-forge", "numexpr", "scipy", "h5py", "pillow", "cython", "matplotlib", "scikit-image", "mako", "pyqtgraph>=0.10", "cvxpy", "pywavelets", "mkl-service", "hdf5=1.10.4", "lxml"], ["numexpr", "scipy", "h5py", "Pillow", "Cython", "matplotlib", "scikit-image", "Mako==1.0.12", "pyqtgraph", "PyWavelets", "mkl", "lxml"], qtModule="qgis.PyQt.QtWidgets") import sys crashFile = os.path.join(os.path.dirname(__file__), "CHECK_CRASH") if(os.path.exists(crashFile)): if(sys.platform == "linux" and "CONDA_PREFIX" in os.environ and "LD_PRELOAD" not in os.environ): ans = QMessageBox.question( iface.mainWindow(), "Crash on last startup", "The loading of PyRAT seems to have produced a crash.\n\r" "The issue might be solved with a " "LD_PRELOAD=$CONDA_PATH/lib/libedit.so statement. " "Do you want to add this now?", QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes) if(ans == QMessageBox.Yes): _writeLDPRELOAD() os.remove(crashFile) return else: QMessageBox.information( iface.mainWindow(), "Crash on last startup", "PyRAT seems to have produced a crash on last " "startup. Please report the issue if the crash " "continues to occur.") self.writeFail = False try: with open(crashFile, "w") as file: file.write("Checking pyrat loading...") except Exception: self.writeFail = True try: import pyrat except ModuleNotFoundError: print("WARNING: No PyRAT installation found") QMessageBox.warning(iface.mainWindow(), "PyRAT not found", "PyRAT was not found in the current " "python environment.") while(True): path = QFileDialog.getExistingDirectory( iface.mainWindow(), "PyRAT-Folder") if path == "": return if not os.path.isdir(os.path.join(path, "pyrat")): QMessageBox.warning( iface.mainWindow(), "No PyRAT installation", "The selected folder contains no pyrat-Module." " Please select a valid PyRAT folder. " "If you currently don't have PyRAT: " "https://github.com/birgander2/PyRAT") else: import shutil shutil.copytree( os.path.join(path, "pyrat"), os.path.join(sys.path[0], "pyrat")) break if not self.writeFail: os.remove(crashFile) from .mainPlugin import PyRATBridge self.mainPlugin = PyRATBridge() self.mainPlugin.initGui()
def onRemoveRestriction(self, currRestrictionLayer, currRestriction): QgsMessageLog.logMessage("In onRemoveRestriction. currLayer: " + str(currRestrictionLayer.id()) + " CurrFeature: " + str(currRestriction.id()), tag="TOMs panel") #self.currRestrictionLayer = currRestrictionLayer #self.currRestriction = currRestriction currProposalID = self.proposalsManager.currentProposal() currRestrictionLayerID = self.getRestrictionLayerTableID( currRestrictionLayer) idxRestrictionID = currRestriction.fields().indexFromName( "RestrictionID") if self.restrictionInProposal(currRestriction[idxRestrictionID], currRestrictionLayerID, currProposalID): # remove the restriction from the RestrictionsInProposals table - and from the currLayer, i.e., it is totally removed. # NB: This is the only case of a restriction being truly deleted QgsMessageLog.logMessage( "In onRemoveRestriction. Removing from RestrictionsInProposals and currLayer.", tag="TOMs panel") # Delete from RestrictionsInProposals result = self.deleteRestrictionInProposal( currRestriction[idxRestrictionID], currRestrictionLayerID, currProposalID) if result: QgsMessageLog.logMessage( "In onRemoveRestriction. Deleting restriction id: " + str(currRestriction.id()), tag="TOMs panel") deleteStatus = currRestrictionLayer.deleteFeature( currRestriction.id()) QgsMessageLog.logMessage( "In onRemoveRestriction. deleteStatus: " + str(deleteStatus), tag="TOMs panel") else: QMessageBox.information(None, "ERROR", ("Error deleting restriction ...")) else: # need to: # - enter the restriction into the table RestrictionInProposals as closed, and # QgsMessageLog.logMessage( "In onRemoveRestriction. Closing existing restriction.", tag="TOMs panel") self.addRestrictionToProposal(currRestriction[idxRestrictionID], currRestrictionLayerID, currProposalID, RestrictionAction.OPEN) # 2 = Close # Now save all changes # Trying to unset map tool to force updates ... #self.iface.mapCanvas().unsetMapTool(self.iface.mapCanvas().mapTool()) self.restrictionTransaction.commitTransactionGroup(None)
def create_project(self, project_name, project_dir, is_public, namespace): """ After user has selected project name, this function does the communication. If project_dir is None, we are creating empty project without upload. """ QApplication.setOverrideCursor(Qt.WaitCursor) try: self.mc.create_project(project_name, is_public, namespace) except Exception as e: QApplication.restoreOverrideCursor() QMessageBox.critical(None, 'Create Project', "Failed to create Mergin project.\n" + str(e)) return QApplication.restoreOverrideCursor() if not project_dir: # not going to upload anything so just pop a "success" message and exit self.depopulate() QMessageBox.information( None, 'Create Project', "An empty project has been created on the server", QMessageBox.Close) return ## let's do initial upload of the project data mp = MerginProject(project_dir) full_project_name = "{}/{}".format(namespace, project_name) mp.metadata = {"name": full_project_name, "version": "v0", "files": []} if not mp.inspect_files(): self.depopulate() QMessageBox.warning( None, "Create Project", "The project directory is empty - nothing to upload.") return dlg = SyncDialog() dlg.push_start(self.mc, project_dir, full_project_name) dlg.exec_() # blocks until success, failure or cancellation if dlg.exception: # push failed for some reason if isinstance(dlg.exception, LoginError): login_error_message(dlg.exception) elif isinstance(dlg.exception, ClientError): QMessageBox.critical(None, "Project sync", "Client error: " + str(dlg.exception)) else: unhandled_exception_message( dlg.exception_details(), "Project sync", f"Failed to sync project {project_name} due to an unhandled exception." ) return if not dlg.is_complete: # we were cancelled - but no need to show a message box about that...? return settings = QSettings() settings.setValue( 'Mergin/localProjects/{}/path'.format(full_project_name), project_dir) if project_dir == QgsProject.instance().absolutePath( ) or project_dir + '/' in QgsProject.instance().absolutePath(): write_project_variables(self.mc.username(), project_name, full_project_name, 'v1') self.depopulate( ) # make sure the project item has the link between remote and local project we have just added QMessageBox.information( None, 'Create Project', "Mergin project created and uploaded successfully", QMessageBox.Close)
def processingFinished(self): self.stopProcessing() QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed."))
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 onGenerate(self): """ Slot raised to initiate the certificate generation process. """ self._notif_bar.clear() success_status = True config = self.current_config() self.last_data_source = config.data_source() if config is None: self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \ "The entity configuration could not be extracted.")) return # Get selected records and validate records = self.tabWidget.currentWidget().entities() if self.chk_template_datasource.isChecked(): records = self._dummy_template_records() if len(records) == 0: self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \ "Please load at least one entity record")) return if not self._docTemplatePath: self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \ "Please select a document template to use")) return documentNamingAttrs = self.lstDocNaming.selectedMappings() if self.chkUseOutputFolder.checkState() == Qt.Checked and len( documentNamingAttrs) == 0: self._notif_bar.insertErrorNotification(QApplication.translate("DocumentGeneratorDialog", \ "Please select at least one field for naming the output document")) return # Set output file properties if self.rbExpImage.isChecked(): outputMode = DocumentGenerator.Image fileExtension = self.cboImageType.currentText() saveAsText = "Image File" else: outputMode = DocumentGenerator.PDF fileExtension = "pdf" saveAsText = "PDF File" # Show save file dialog if not using output folder if self.chkUseOutputFolder.checkState() == Qt.Unchecked: docDir = source_document_location() if self._outputFilePath: fileInfo = QFileInfo(self._outputFilePath) docDir = fileInfo.dir().path() self._outputFilePath, _ = QFileDialog.getSaveFileName( self, QApplication.translate("DocumentGeneratorDialog", "Save Document"), docDir, "{0} (*.{1})".format( QApplication.translate("DocumentGeneratorDialog", saveAsText), fileExtension)) if not self._outputFilePath: self._notif_bar.insertErrorNotification( QApplication.translate( "DocumentGeneratorDialog", "Process aborted. No output file was specified.")) return # Include extension in file name self._outputFilePath = self._outputFilePath # + "." + fileExtension # else: # Multiple files to be generated. # pass self._doc_generator.set_link_field(config.link_field()) self._doc_generator.clear_attr_value_formatters() if not self.chk_template_datasource.isChecked(): # Apply cell formatters for naming output files self._doc_generator.set_attr_value_formatters(config.formatters()) entity_field_name = "id" # Iterate through the selected records progressDlg = QProgressDialog(self) progressDlg.setMaximum(len(records)) try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) for i, record in enumerate(records): progressDlg.setValue(i) if progressDlg.wasCanceled(): success_status = False break # User-defined location if self.chkUseOutputFolder.checkState() == Qt.Unchecked: status, msg = self._doc_generator.run( self._docTemplatePath, entity_field_name, record.id, outputMode, data_source=self.ds_entity.name, filePath=self._outputFilePath) self._doc_generator.clear_temporary_layers() # Output folder location using custom naming else: status, msg = self._doc_generator.run( self._docTemplatePath, entity_field_name, record.id, outputMode, dataFields=documentNamingAttrs, fileExtension=fileExtension, data_source=self.ds_entity.name) self._doc_generator.clear_temporary_layers() if not status: result = QMessageBox.warning( self, QApplication.translate("DocumentGeneratorDialog", "Document Generate Error"), msg, QMessageBox.Ignore | QMessageBox.Abort) if result == QMessageBox.Abort: progressDlg.close() success_status = False # Restore cursor QApplication.restoreOverrideCursor() return # If its the last record and user has selected to ignore if i + 1 == len(records): progressDlg.close() success_status = False # Restore cursor QApplication.restoreOverrideCursor() return else: progressDlg.setValue(len(records)) QApplication.restoreOverrideCursor() QMessageBox.information( self, QApplication.translate("DocumentGeneratorDialog", "Document Generation Complete"), QApplication.translate( "DocumentGeneratorDialog", "Document generation has successfully completed.")) except DummyException as ex: LOGGER.debug(str(ex)) err_msg = sys.exc_info()[1] QApplication.restoreOverrideCursor() QMessageBox.critical( self, "STDM", QApplication.translate( "DocumentGeneratorDialog", "Error Generating documents - %s" % (err_msg))) success_status = False # Reset UI self.reset(success_status)
def doSplitRestriction(self): QgsMessageLog.logMessage("In doSplitRestriction - starting", tag="TOMs panel") self.proposalsManager.TOMsToolChanged.emit() self.mapTool = None # Get the current proposal from the session variables currProposalID = self.proposalsManager.currentProposal() if currProposalID > 0: if self.actionSplitRestriction.isChecked(): QgsMessageLog.logMessage( "In doSplitRestriction - tool being activated", tag="TOMs panel") # Need to clear any other maptools .... ******** currRestrictionLayer = self.iface.activeLayer() if currRestrictionLayer: QgsMessageLog.logMessage( "In doSplitRestriction. currLayer: " + str(currRestrictionLayer.name()), tag="TOMs panel") if currRestrictionLayer.selectedFeatureCount() > 0: self.restrictionTransaction.startTransactionGroup() """currRestriction = currRestrictionLayer.selectedFeatures()[0] restrictionForEdit = self.prepareRestrictionForEdit (currRestriction, currRestrictionLayer) currRestrictionLayer.deselect(currRestriction.id()) currRestrictionLayer.select(restrictionForEdit.id()) #currRestrictionLayer.selectByIds([editFeature.id()])""" #self.actionEditRestriction.setChecked(True) self.mapTool = TOMsSplitRestrictionTool( self.iface, currRestrictionLayer, self.proposalsManager, self.restrictionTransaction ) # This is where we use the Node Tool ... need canvas and panel?? """self.mapTool = TOMsNodeTool(self.iface, self.proposalsManager, self.restrictionTransaction, restrictionForEdit, currRestrictionLayer) # This is where we use the Node Tool ... need canvas and panel??""" self.mapTool.setAction(self.actionSplitRestriction) self.iface.mapCanvas().setMapTool(self.mapTool) #currRestrictionLayer.editingStopped.connect(self.proposalsManager.updateMapCanvas) else: reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Select restriction for edit", QMessageBox.Ok) self.actionSplitRestriction.setChecked(False) self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None else: reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Select restriction for edit", QMessageBox.Ok) self.actionSplitRestriction.setChecked(False) self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None else: QgsMessageLog.logMessage( "In doSplitRestriction - tool deactivated", tag="TOMs panel") self.actionSplitRestriction.setChecked(False) self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None pass else: """if self.actionEditRestriction.isChecked(): self.actionEditRestriction.setChecked(False) if self.mapTool == None: self.actionEditRestriction.setChecked(False)""" reply = QMessageBox.information( self.iface.mainWindow(), "Information", "Changes to current data are not allowed. Changes are made via Proposals", QMessageBox.Ok) self.actionSplitRestriction.setChecked(False) self.iface.mapCanvas().unsetMapTool(self.mapTool) self.mapTool = None pass QgsMessageLog.logMessage("In doSplitRestriction - leaving", tag="TOMs panel") pass
def about(self) -> None: QMessageBox.information(self.iface.mainWindow(), QCoreApplication.translate('GetFeatureInfoPrecision', "Server GetFeatureInfoPrecision"), QCoreApplication.translate('GetFeatureInfoPrecision', "Server GetFeatureInfoPrecision is a simple plugin for QGIS Server, it does just nothing in QGIS Desktop. See: <a href=\"https://github.com/3liz/qgis-wmsGetFeatureInfoPrecision\">plugin's homepage</a>"))
def aggiorna(self, proj_path, dir_output, nome, proj_vers, new_proj_vers): self.show() result = self.exec_() if result: try: pacchetto = os.path.join(self.plugin_dir, "data", "progetto_CLE.zip") if proj_vers < new_proj_vers: name_output = ( nome + "_backup_v" + str(proj_vers) + "_" + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M")) shutil.copytree(proj_path, os.path.join(dir_output, name_output)) zip_ref = zipfile.ZipFile(pacchetto, "r") zip_ref.extractall(proj_path) zip_ref.close() shutil.rmtree( os.path.join(proj_path, "progetto", "maschere")) shutil.copytree( os.path.join(proj_path, "progetto_CLE", "progetto", "maschere"), os.path.join(proj_path, "progetto", "maschere"), ) shutil.rmtree(os.path.join(proj_path, "progetto", "script")) shutil.copytree( os.path.join(proj_path, "progetto_CLE", "progetto", "script"), os.path.join(proj_path, "progetto", "script"), ) os.remove( os.path.join(proj_path, "progetto", "version.txt")) shutil.copyfile( os.path.join(os.path.dirname(__file__), "version.txt"), os.path.join(proj_path, "progetto", "version.txt"), ) os.remove(os.path.join(proj_path, "progetto_CLE.qgs")) shutil.copyfile( os.path.join(proj_path, "progetto_CLE", "progetto_CLE.qgs"), os.path.join(proj_path, "progetto_CLE.qgs"), ) self.load_new_qgs_file(proj_path) shutil.rmtree(os.path.join(proj_path, "progetto_CLE")) QMessageBox.information( None, self.tr("INFORMATION!"), self. tr("The project structure has been updated!\nThe backup copy has been saved in the following directory: " ) + name_output, ) # canvas_extent = iface.mapCanvas().extent() # subset_strings = {} # for vl in QgsProject.instance().mapLayers().values(): # subset_strings[vl.name()] = vl.subsetString() # QgsProject.instance().read(QgsProject.instance().fileName()) # for vl in QgsProject.instance().mapLayers().values(): # if subset_strings.get(vl.name(), '') != '': # vl.setSubsetString(subset_strings.get(vl.name())) # iface.mapCanvas().setExtent(canvas_extent) except Exception as z: QMessageBox.critical(None, "ERROR!", 'Error:\n"' + str(z) + '"')
def __init__(self, iface): # Save reference to the QGIS interface self.iface = iface QMessageBox.information(self.iface.mainWindow(), "Test", "__init__(self, iface) was called!", QMessageBox.Ok)
def run(self): QMessageBox.information( self.iface.mainWindow(), "Test", "run(self) was called!\n\nIt's time to learn more PyQGIS!", QMessageBox.Ok)
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 = NewRaptorDialog() self.dlg.cmbSpecies.currentTextChanged.connect( self.evt_cmbSpecies_changed) mc = self.iface.mapCanvas() self.dlg.spbLatitude.setValue(mc.center().y()) self.dlg.spbLongitude.setValue(mc.center().x()) self.dlg.dteLast.setDate(QDate.currentDate()) map_layers = [] for lyr in mc.layers(): map_layers.append(lyr.name()) missing_layers = [] if not "Raptor Nests" in map_layers: missing_layers.append("Raptor Nests") if not "Raptor Buffer" in map_layers: missing_layers.append("Raptor Buffer") if not "Linear Buffer" in map_layers: missing_layers.append("Linear Buffer") if missing_layers: msg = "The following layers are misisng from this project\n" for lyr in missing_layers: msg += "\n{}".format(lyr) QMessageBox.critical(self.dlg, "Missing layers", msg) return # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. lyrNests = QgsProject.instance().mapLayersByName("Raptor Nests")[0] lyrBuffer = QgsProject.instance().mapLayersByName( "Raptor Buffer")[0] lyrLinear = QgsProject.instance().mapLayersByName( "Linear Buffer")[0] idxNestID = lyrNests.fields().indexOf("Nest_ID") valNestID = lyrNests.maximumValue(idxNestID) + 1 valLat = self.dlg.spbLatitude.value() valLng = self.dlg.spbLongitude.value() valSpecies = self.dlg.cmbSpecies.currentText() valBuffer = self.dlg.spbBuffer.value() valStatus = self.dlg.cmbStatus.currentText() valLast = self.dlg.dteLast.date() QMessageBox.information( self.dlg, "Message", "New Nest ID: {}\n\nLatitude: {}\nLongitude: {}\nSpecies: {}\nBuffer: {}\nStatus: {}\nLast Survey: {}" .format(valNestID, valLat, valLng, valSpecies, valBuffer, valStatus, valLast)) ftrNest = QgsFeature(lyrNests.fields()) ftrNest.setAttribute("lat_y_dd", valLat) ftrNest.setAttribute("long_x_dd", valLng) ftrNest.setAttribute("recentspec", valSpecies) ftrNest.setAttribute("buf_dist", valBuffer) ftrNest.setAttribute("recentstat", valStatus) ftrNest.setAttribute("lastsurvey", valLast) ftrNest.setAttribute("Nest_ID", valNestID) geom = QgsGeometry(QgsPoint(valLng, valLat)) ftrNest.setGeometry(geom) pr = lyrNests.dataProvider() pr.addFeatures([ftrNest]) lyrNests.reload() pr = lyrBuffer.dataProvider() buffer = geom.buffer(valBuffer, 10) ftrNest.setGeometry(buffer) pr.addFeatures([ftrNest]) lyrBuffer.reload() dlgTable = DlgTable() dlgTable.setWindowTitle( "Impacts Table for Nest {}".format(valNestID)) # Find linear projects that will be impacted and report them in the table bb = buffer.boundingBox() linears = lyrLinear.getFeatures(bb) for linear in linears: valID = linear.attribute("Project") valType = linear.attribute("type") valDistance = linear.geometry().distance(geom) if valDistance < valBuffer: # Populate table with linear data row = dlgTable.tblImpacts.rowCount() dlgTable.tblImpacts.insertRow(row) dlgTable.tblImpacts.setItem(row, 0, QTableWidgetItem(str(valID))) dlgTable.tblImpacts.setItem(row, 1, QTableWidgetItem(valType)) twi = QTableWidgetItem("{:4.5f}".format(valDistance)) twi.setTextAlignment(QtCore.Qt.AlignRight) dlgTable.tblImpacts.setItem(row, 2, twi) dlgTable.tblImpacts.sortItems(2) dlgTable.show() dlgTable.exec_() else: QMessageBox.information(self.dlg, "Message", "Should only run if cancelled")
def gpsErrorEncountered(self, e): TOMsMessageLog.logMessage("In enableTools - GPS connection has error ", level=Qgis.Info) QMessageBox.information(self.iface.mainWindow(), "ERROR", ("Error encountered with GNSS. Closing tools ...")) self.gnssStopped.emit()
def open_dock(self): """ This method will be called when you click the toolbar button or select the plugin menu item. """ # Try to catch every Exception and show it in a graphical window. try: # Show the output of the plugin: #console.show_console() # works but better: pythonConsole = self.iface.mainWindow().findChild( QDockWidget, 'PythonConsole') try: if not pythonConsole.isVisible(): pythonConsole.setVisible(True) except AttributeError: # can be 'None' above console.show_console() self.out("PythonConsole Error catched", False) self.out("open_dock()") # Test for catching a exception and show this to the user by a window: #raise RuntimeWarning("manual exception raised") # 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 # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) # Close dock via toolbar button: if self.dock: if self.dock.isVisible(): self.dock.close() return # if first start else: """ Detect first start after installation. There seems to be a problem with plugin reloading, so after (re)install there occur errors. So we handle this issue manually with a one time check file (deleted after the following message). """ if self._model.check_file.exists(): msg = "After reinstalling the plugin QGIS should be restarted now,\n"\ " otherwise plugin errors are to be expected!" QMessageBox.warning(self.iface.mainWindow(), 'initialize plugin', msg) # Message should only appear one time, so the # check file must be removed now: self._model.check_file.unlink() self.out( "check file '{}' removed, message doesn't appear again." .format(self._model.check_file)) msg = "It's recommended to exit QGIS now.\n\nExit QGIS?" reply = QMessageBox.question(self.iface.mainWindow(), 'Continue?', msg, QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: self.iface.actionExit().trigger() return # maybe unnecessary # if self._init_dock() news_file = self._model.news_file try: with news_file.open() as f: l_text = [f.read()] if l_text: l_text.append( "\nThis info window won't be displayed again!\n") l_text.append( "You can view the change history at any time here:" ) l_text.append( "=> https://plugins.qgis.org/plugins/radolan2map/#plugin-versions" ) text = '\n'.join(l_text) QMessageBox.information(self.iface.mainWindow(), "New changes", text) except FileNotFoundError: pass else: news_file.unlink() self.out( "news file '{}' removed, message doesn't appear again." .format(news_file)) # else self._settings_tab.update_projection_based_on_current_project() """ DockWidget exists but maybe it's invisible Bring DockWidget to front (maybe it's minimized elsewhere...) """ width = self.dock.frameGeometry().width() height = self.dock.frameGeometry().height() # that's fine - if necessary, get the initialized values from the .ui: self.dock.setMinimumSize(QSize(width, height)) # width, height # -> prevents a too small Widget # show the dockwidget self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock) self.dock.show() # Ohne diese Anweisung wurde das Fenster ab QGIS3 im Hintergrund geöffnet. #self.dock.setWindowFlags(Qt.WindowStaysOnTopHint) except Exception as e: l_msg = ["{}\n\n".format(e)] l_msg.append( "If this error persists - even after restarting QGIS - it may be" ) l_msg.append(" helpful to update your QGIS / Python installation") l_msg.append(" and working with a new QGIS user profile.") l_msg.append("\nIf nothing helps, please write a bug report.") msg = "".join(l_msg) self.out(msg, False) QMessageBox.critical(self.iface.mainWindow(), 'Exception catched', msg)
def convArcInfo(self, prec): for i in range(0, self.polynum): j = i + 1 self.plainTextEdit.appendPlainText("%s area%s" % (j, j)) self.plainTextEdit.appendPlainText("\nregions") provider = self.ml.dataProvider() i = 1 n = 1 mod = min(self.ids) p = 1 if mod == 1: p = 0 for ne in range(mod, self.polynum + mod): feat = QgsFeature() geom = QgsGeometry() fiter = self.ml.getFeatures(QgsFeatureRequest(ne)) if fiter.nextFeature(feat): geom = QgsGeometry(feat.geometry()) if geom.isMultipart(): multi_polygon = geom.asMultiPolygon() for polygon in multi_polygon: for ring in polygon: self.plainTextEdit.appendPlainText("%s area%s" % (n, feat.id() + p)) n += 1 else: polygon = geom.asPolygon() for ring in polygon: self.plainTextEdit.appendPlainText("%s area%s" % (n, feat.id() + p)) n += 1 i += 1 self.plainTextEdit.appendPlainText("END") n = 1 for ne in range(mod, self.polynum + mod): pn = 1 feat = QgsFeature() geom = QgsGeometry() fiter = self.ml.getFeatures(QgsFeatureRequest(ne)) if fiter.nextFeature(feat): geom = QgsGeometry(feat.geometry()) id = feat.id() + p if geom.isMultipart(): multi_polygon = geom.asMultiPolygon() for polygon in multi_polygon: for ring in polygon: self.plainTextEdit.appendPlainText("%s 0 0" % (n)) for v in ring: self.plainTextEdit.appendPlainText( "%s %s" % (round(v.x(), prec), round(v.y(), prec))) pn += 1 self.plainTextEdit.appendPlainText("END") n += 1 else: polygon = geom.asPolygon() for ring in polygon: self.plainTextEdit.appendPlainText("%s 0 0" % (n)) for v in ring: self.plainTextEdit.appendPlainText( "%s %s" % (round(v.x(), prec), round(v.y(), prec))) pn += 1 self.plainTextEdit.appendPlainText("END") n += 1 if pn >= 10000: QMessageBox.information( self, "Too many points", "Polygon No. %s contains to many points to read into GeoBUGS.\nSimplifying of polygon can solve this problem." % (id), buttons=QMessageBox.Ok, defaultButton=QMessageBox.NoButton) self.progressBar.setValue(100 * id / self.polynum) self.plainTextEdit.appendPlainText("END")
def show_info(self, msg): QMessageBox.information(self.iface.mainWindow(), self.context, msg)
def ok_param(self, dic_param): # To avoid problem of layer names not found try: # Find the layer objects lyr_lines = self.project.mapLayersByName(dic_param["lin_lyr"])[0] lyr_nodes = self.project.mapLayersByName(dic_param["nod_lyr"])[0] # Start editing line or node layer if dic_param["move_mode"] == 0: if not lyr_lines.startEditing(): QMessageBox.information( self.iface.mainWindow(), self.err_title_txt, self.err_noedit_txt % (dic_param["lin_lyr"])) return else: if not lyr_nodes.startEditing(): QMessageBox.information( self.iface.mainWindow(), self.err_title_txt, self.err_noedit_txt % (dic_param["nod_lyr"])) return # Reviews all the line objects for lin_obj in lyr_lines.getFeatures(): # Find the node references in the line object # Only the 2 first references are processed try: val_attsnode = lin_obj[dic_param["lin_att1"]].split( dic_param["lin_att_sep"]) except: QMessageBox.information( self.iface.mainWindow(), self.err_title_txt, self.err_noatt_txt % (dic_param["lin_att1"])) break # Check if 2 point numbers found if len(val_attsnode) > 1: # Reviews all the node objects for node_obj in lyr_nodes.getFeatures(): if node_obj[dic_param["nod_att"]] == val_attsnode[0]: # The first vertex of the line is moved to the position of the node if dic_param["move_mode"] == 0: node_geom = node_obj.geometry().asPoint() lyr_lines.moveVertex(node_geom.x(), node_geom.y(), lin_obj.id(), 0) # The node is moved to the position of the first vertex of the line else: line_geom = lin_obj.geometry() line_geom.convertToSingleType() line_geompl = line_geom.asPolyline() node_geom = node_obj.geometry() lyr_nodes.moveVertex(line_geompl[0][0], line_geompl[0][1], node_obj.id(), 0) if node_obj[dic_param["nod_att"]] == val_attsnode[1]: line_geom = lin_obj.geometry() line_geom.convertToSingleType() line_geompl = line_geom.asPolyline() # The last vertex of the line is moved to the position of the node if dic_param["move_mode"] == 0: last_vtx = len(line_geompl) - 1 node_geom = node_obj.geometry().asPoint() lyr_lines.moveVertex(node_geom.x(), node_geom.y(), lin_obj.id(), last_vtx) # The node is moved to the position of the last vertex of the line else: last_vtx = len(line_geompl) - 1 node_geom = node_obj.geometry() lyr_nodes.moveVertex(line_geompl[last_vtx][0], line_geompl[last_vtx][1], node_obj.id(), 0) # Validate the modification of the line or the node layer if dic_param["move_mode"] == 0: lyr_lines.commitChanges() else: lyr_nodes.commitChanges() # Refresh the canvas self.canvas.refresh() except: pass # End message QMessageBox.information(self.iface.mainWindow(), self.fnc_title_txt, self.end_txt)
def check_login(self): version_ok = True if not self.api.check_auth(): self._qgis3_info() login_dialog = QDialog(self) login_dialog.ui = Ui_LoginDialog() login_dialog.ui.setupUi(login_dialog) login_dialog.ui.editUser.setText(self.user) login_ok = False while not login_ok and version_ok: self.api.set_url(self.api_url()) if not login_dialog.exec_(): self.api.set_auth( user=login_dialog.ui.editUser.text(), password=None) return login_ok self.api.set_auth( user=login_dialog.ui.editUser.text(), password=login_dialog.ui.editPassword.text()) try: login_info = self.api.check_login( version_info=self._version_info()) # QGIS private Cloud has no tos_accepted try: if not login_info['tos_accepted']: result = QMessageBox.information( None, self.tr("Accept new Privacy Policy"), self.tr("""Due to the GDPR qgiscloud.com has a new <a href='http://qgiscloud.com/en/pages/privacy'> Privacy Policy </a>. To continue using qgiscloud.com, you must accept the new policy. """), QMessageBox.StandardButtons( QMessageBox.No | QMessageBox.Yes)) if result == QMessageBox.No: login_ok = False return else: result = self.api.accept_tos() except: pass self.user = login_dialog.ui.editUser.text() self._update_clouddb_mode(login_info['clouddb']) version_ok = StrictVersion(self.version) >= StrictVersion(login_info['current_plugin']) if not version_ok: self.ui.lblVersionPlugin.setPalette(self.palette_red) QMessageBox.information(None, self.tr('New Version'), self.tr('New plugin release {version} is available! Please upgrade the QGIS Cloud plugin.').format(version=login_info['current_plugin'])) self.store_settings() self.ui.btnLogin.hide() self.ui.lblSignup.hide() self.ui.btnLogout.show() self.ui.widgetDatabases.setEnabled(True) self.ui.widgetMaps.setEnabled(True) self.ui.lblLoginStatus.setText( self.tr("Logged in as {0} ({1})").format(self.user, login_info['plan'])) self.ui.lblLoginStatus.show() self._push_message( self.tr("QGIS Cloud"), self.tr("Logged in as {0}").format(self.user), level=0, duration=2) self.refresh_databases() self.refresh_maps() if not version_ok: self._push_message(self.tr("QGIS Cloud"), self.tr( "Unsupported versions detected. Please check your versions first!"), level=1) version_ok = False self.ui.tabWidget.setCurrentWidget(self.ui.aboutTab) login_ok = True self.update_local_layers() except ForbiddenError: QMessageBox.critical( self, self.tr("Account Disabled"), self.tr("Account {username} is disabled! Please contact [email protected]").format(username=login_dialog.ui.editUser.text())) login_ok = False except UnauthorizedError: QMessageBox.critical( self, self.tr("Login for user {username} failed").format(username=login_dialog.ui.editUser.text()), self.tr("Wrong user name or password")) login_ok = False except (TokenRequiredError, ConnectionException) as e: QMessageBox.critical( self, self.tr("Login failed"), self.tr("Login failed: %s") % str(e)) login_ok = False return version_ok