def showLoadingMsg(self, lyrList=None, msgType=None): """ Shows a message box to user if successfully loaded data or not. If not, shows to user a list of not loaded layers and allows user to choice between ignore and continue or cancel the importation. :param lyrList: (list) a list of not loaded layers. :param msgType: (str) type of message box - warning or information. :return: (signal) value returned from the clicked button. """ msg = QMessageBox() msg.setWindowTitle(self.tr("Information about importing rules")) if lyrList and msgType == "warning": msg.setIcon(QMessageBox.Warning) msg.setText(self.tr("Some rules have not been loaded")) msg.setInformativeText( self.tr("Do you want to ignore and continue or cancel?")) textLyrList = sorted(set(lyrList)) formatedLyrList = ["{}" for item in textLyrList] msgString = ",".join(formatedLyrList).replace(",", "\n") formatedMsgString = self.tr( "The following layers have not been loaded:\n") + \ msgString.format(*textLyrList) msg.setDetailedText(formatedMsgString) msg.setStandardButtons(QMessageBox.Ignore | QMessageBox.Cancel) msg.setDefaultButton(QMessageBox.Cancel) else: msg.setIcon(QMessageBox.Information) msg.setText(self.tr("Successfully loaded rules!")) choice = msg.exec_() return choice
def showLoadingMsg(self, invalidRules=None, msgType=None): """ Shows a message box to user if successfully loaded data or not. If not, shows to user a list of not loaded layers and allows user to choice between ignore and continue or cancel the importation. :param lyrList: (list) a list of not loaded layers. :param msgType: (str) type of message box - warning or information. :return: (signal) value returned from the clicked button. """ msg = QMessageBox() msg.setWindowTitle(self.tr("DSGTools: importing spatial rules")) if invalidRules and msgType == "warning": msg.setIcon(QMessageBox.Warning) msg.setText(self.tr("Some rules have not been loaded")) msg.setInformativeText( self.tr("Do you want to ignore and continue or cancel?")) msgString = "\n".join((r.ruleName() for r in invalidRules)) formatedMsgString = self.tr( "The following layers have not been loaded:\n{0}").format( msgString) msg.setDetailedText(formatedMsgString) msg.setStandardButtons(QMessageBox.Ignore | QMessageBox.Cancel) msg.setDefaultButton(QMessageBox.Cancel) else: msg.setIcon(QMessageBox.Information) msg.setText(self.tr("Successfully loaded rules!")) choice = msg.exec_() return choice
def runModel(self): valid, errors = self.model().validate() if not valid: message_box = QMessageBox() message_box.setWindowTitle(self.tr('Model is Invalid')) message_box.setIcon(QMessageBox.Warning) message_box.setText(self.tr('This model is not valid and contains one or more issues. Are you sure you want to run it in this state?')) message_box.setStandardButtons(QMessageBox.Yes | QMessageBox.Cancel) message_box.setDefaultButton(QMessageBox.Cancel) error_string = '' for e in errors: e = re.sub(r'<[^>]*>', '', e) error_string += '• {}\n'.format(e) message_box.setDetailedText(error_string) if message_box.exec_() == QMessageBox.Cancel: return def on_finished(successful, results): self.setLastRunChildAlgorithmResults(dlg.results().get('CHILD_RESULTS', {})) self.setLastRunChildAlgorithmInputs(dlg.results().get('CHILD_INPUTS', {})) dlg = AlgorithmDialog(self.model().create(), parent=self) dlg.setParameters(self.model().designerParameterValues()) dlg.algorithmFinished.connect(on_finished) dlg.exec_() if dlg.wasExecuted(): self.model().setDesignerParameterValues(dlg.createProcessingParameters(include_default=False))
def exec_warning_dialog(title, msg, body=None): box = QMessageBox(QMessageBox.Warning, title, msg, QMessageBox.Close) if "</a>" in msg: msg = msg.replace("\n", "<br>") box.setTextFormat(Qt.RichText) box.setText(msg) if body is not None: box.setDetailedText(body) return box.exec_()
def unhandled_exception_message(error_details, dialog_title, error_text): msg = error_text + "<p>This should not happen, " \ "<a href=\"https://github.com/lutraconsulting/qgis-mergin-plugin/issues\">" \ "please report the problem</a>." box = QMessageBox() box.setIcon(QMessageBox.Critical) box.setWindowTitle(dialog_title) box.setText(msg) box.setDetailedText(error_details) box.exec_()
def details_message_box(error, more_details): msgBox = QMessageBox() msgBox.setWindowTitle("AcATaMa - Error handler") msgBox.setText("<i>{}</i>".format(error)) msgBox.setInformativeText("If you consider this as an error of AcATaMa, report it in " "<a href='https://github.com/SMByC/AcATaMa/issues'>issue tracker</a>") msgBox.setDetailedText(more_details) msgBox.setTextFormat(Qt.RichText) msgBox.setStandardButtons(QMessageBox.Ok) msgBox.exec() del msgBox
def on_b4_click(self): msg = QMessageBox() msg.setWindowTitle("OSM file filter") self.pbf_filtered = self.dlg1.lineEdit3.text() if Path(self.pbf_filtered).suffixes == Path(self.pbf_file).suffixes: if os.path.isfile(self.poly_file): filter_pbf_with_poly(self.pbf_file, self.poly_file, self.pbf_filtered) self.iface.messageBar().pushMessage( "osm.pbf data filter using polygon done! see output file {}" .format(self.pbf_filtered), level=Qgis.Success, duration=3) # msg.setText("Done!") # msg.setIcon(QMessageBox.Information) # msg.setInformativeText( # "osm.pbf file filter using bounding polygons completed.") # _ = msg.exec_() else: self.iface.messageBar().pushMessage( "Ensure input poly file exits", level=Qgis.Warning, duration=4) msg.setText("File type error") msg.setIcon(QMessageBox.Warning) msg.setInformativeText( "Use the browse button to choose a valid .poly file") msg.buttonClicked.connect(self.popup_button) _ = msg.exec_() else: self.iface.messageBar().pushMessage("Output file extension error", level=Qgis.Warning, duration=4) msg.setText("Output file error") msg.setIcon(QMessageBox.Critical) msg.setInformativeText("Set output file extension to osm.pbf") msg.setDetailedText( "To properly set output file name, choose valid osm.pbf file and poly file using the browse file buttons and click Ok to set default Outputfile name." ) msg.buttonClicked.connect(self.popup_button) _ = msg.exec_()
def do_delete_data_action(self, count_id): dlg = DeleteDialog(self.iface) tz = pytz.timezone("Europe/Zurich") if dlg.exec_(): start = tz.localize(dlg.start_date.dateTime().toPyDateTime()) end = tz.localize(dlg.end_date.dateTime().toPyDateTime()) definitive = dlg.definitive.isChecked() quarantine = dlg.quarantine.isChecked() count = models.Count.objects.get(id=count_id) msg = QMessageBox() msg.setIcon(QMessageBox.Warning) msg.setText("Effacement des données") # msg.setInformativeText(f"Effacement des données") msg.setDetailedText("Les données suivantes seront supprimées:\n" f"comptage: {count_id}\n" f"de: {start.strftime('%d.%m.%Y')}\n" f"à: {end.strftime('%d.%m.%Y')} inclus\n" f"provisoires: {quarantine}\n" f"définitives: {definitive}") msg.setWindowTitle("Effacement des données") msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel) retval = msg.exec_() if retval == QMessageBox.Ok: qs = models.CountDetail.objects.filter( id_count=count, timestamp__range=(start, end + timedelta(days=1)), ) if not definitive: qs = qs.filter(status=definitions.IMPORT_STATUS_QUARANTINE) if not quarantine: qs = qs.filter(status=definitions.IMPORT_STATUS_DEFINITIVE) qs.delete()
def change_project(self, project): ''' set given project as the active project. Only one project can be active at a time. Reloads the definition and domain widgets. ''' if not project: self.ui.domain_button.setEnabled(False) self.ui.definition_button.setEnabled(False) return projektrahmendaten = Projektrahmendaten.features(project=project)[0] version = projektrahmendaten.basisdaten_version success = self.project_manager.load_basedata(version=version) # check the availability of the base data the project was created with if not success: server_versions = self.project_manager.server_versions available = [v['version'] for v in server_versions] v_repr = f' (v{version})' if version else '' if version not in available: QMessageBox.warning( self.ui, 'Fehler', f'Die Basisdaten{v_repr}, mit denen das Projekt erstellt ' 'wurde sind nicht mehr online verfügbar.\n\n' 'Sie können das Projekt leider nicht weiterverwenden. ' 'Bitte erstellen Sie ein neues Projekt.') else: reply = QMessageBox.question( self.ui, 'Basisdaten herunterladen', f'Die Basisdaten{v_repr}, mit denen das Projekt erstellt ' 'wurde, wurden lokal nicht gefunden.\n\n' 'Möchten Sie diese Daten jetzt herunterladen? ', QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: settings = SettingsDialog(self) settings.download_basedata(version=version) self.ui.project_combo.setCurrentIndex(0) return try: if getattr(self, 'project_definitions', None): self.project_definitions.unload() del (self.project_definitions) for domain in self.domains: domain.unload() del (domain) # ToDo: put that in project.close() and get # workspaces of this project only for ws in Workspace.get_instances(): if not ws.database.read_only: ws.close() self.project_manager.active_project = project self.setup_definitions() self.setup_domains() # append groups to force initial order of layers ProjectLayer.add_group(self.project_definitions.layer_group, prepend=True) for domain in self.domains: group = ProjectLayer.add_group(domain.layer_group, prepend=False) group.setItemVisibilityChecked(False) parent = group.parent() # in case parent is sub-group of project group, hide as well if parent.name() != self.project.groupname: parent.setItemVisibilityChecked(False) # check active project, uncheck other projects layer_root = QgsProject.instance().layerTreeRoot() for p in self.project_manager.projects: group = layer_root.findGroup(p.groupname) if group: group.setItemVisibilityChecked( p.groupname == project.groupname) # show area layers self.project_definitions.show_outputs(zoom=True) backgroundOSM = OSMBackgroundLayer(groupname='Hintergrundkarten') backgroundOSM.draw(checked=False) backgroundGrey = TerrestrisBackgroundLayer( groupname='Hintergrundkarten') backgroundGrey.draw() self.ui.domain_button.setEnabled(True) self.ui.definition_button.setEnabled(True) # ToDo: show last active widget except FileNotFoundError as e: message = QMessageBox() message.setIcon(QMessageBox.Warning) message.setText(f'Das Projekt "{project.name}" ist beschädigt.') message.setInformativeText('Bitte löschen Sie das Projekt oder ' 'wenden Sie sich an den Administrator') message.setWindowTitle('Fehler') message.setDetailedText(str(e)) message.exec_()
def exportData(self): """ Las ubicaciones se guardan serializadas en fichero """ # import os # os.system('D:/projectes_py/qVista/kk.chm') def crear__listaDatos(self, parent=QModelIndex()): """ Creamos array de diccionarios que es un objeto serializable """ datos = [] n_linea = -1 raiz = 0 def itemList_2(self, n_linea, datos, raiz, parent=QModelIndex()): """ Función recursiva para la lectura de todos los nodos del arbol. Una vez obtenidos se formatean adecuadamente y se añaden a la lista """ n_linea += 1 if n_linea == 0: raiz = int(str(parent)[38:-1], 16) for row in range(self.ubicacions.model.rowCount(parent)): idx = self.ubicacions.model.index(row, 0, parent) i_xxmin = self.ubicacions.model.index(row, 1, parent) i_yymin = self.ubicacions.model.index(row, 2, parent) i_xxmax = self.ubicacions.model.index(row, 3, parent) i_yymax = self.ubicacions.model.index(row, 4, parent) i_proy = self.ubicacions.model.index(row, 5, parent) #??? nn = int(str(idx)[38:-1], 16) par = int(str(parent)[38:-1], 16) try: xmin_i = int(self.ubicacions.model.data(i_xxmin)) ymin_i = int(self.ubicacions.model.data(i_yymin)) xmax_i = int(self.ubicacions.model.data(i_xxmax)) ymax_i = int(self.ubicacions.model.data(i_yymax)) except: xmin_i = 0 ymin_i = 0 xmax_i = 0 ymax_i = 0 subdatos = { 'level': 0, 'id_': nn, 'parent_id': par, 'mi_ubi': self.ubicacions.model.data(idx), 'xmin': xmin_i, 'ymin': ymin_i, 'xmax': xmax_i, 'ymax': ymax_i } datos.append(subdatos) if self.ubicacions.model.hasChildren(idx): itemList_2(self, n_linea, datos, raiz, idx) return raiz # invocamos la función para obtener la lista raiz = itemList_2(self, n_linea, datos, raiz) # Bucle para hacer tunning de datos for ii in range(len(datos)): if datos[ii]['parent_id'] != raiz: datos[ii]['level'] = 1 return (datos) datos = crear__listaDatos(self) try: # if os.path.exists(fic_guardar_arbre): # os.remove(fic_guardar_arbre) with open(fic_guardar_arbre, 'wb') as fga: pickle.dump(datos, fga) datos.clear() fga.close() # msg = QMessageBox() # msg.setIcon(QMessageBox.Information) # literal= "Ubicacions desades" # msg.setText(literal) # # msg.setInformativeText("OK para salir del programa \nCANCEL para seguir en el programa") # msg.setWindowTitle("QvUbicacions") # retval = msg.exec_() except: msg = QMessageBox() msg.setIcon(QMessageBox.Warning) literal = "Error en escriure el fitxer: " + fic_guardar_arbre msg.setText(literal) # msg.setInformativeText("OK para salir del programa \nCANCEL para seguir en el programa") msg.setWindowTitle("QvUbicacions ERROR") msg.setDetailedText( "Comprovar que existeix i es pot escriure en: " + os.path.dirname(fic_guardar_arbre)) msg.setStandardButtons(QMessageBox.Close) retval = msg.exec_() #No fem res amb el valor de retorn (???)
def exec_warning_dialog(title, msg, body=None): box = QMessageBox(QMessageBox.Warning, title, msg, QMessageBox.Close) if not body is None: box.setDetailedText(body) return box.exec_()