def open_file_browser(self): # noinspection PyArgumentList shapefile = QFileDialog.getOpenFileName( parent=self.parent, caption=tr('Select shapefile'), filter='Shapefile (*.shp)') self.le_shapefile.setText(shapefile)
def open_file_browser(self): # noinspection PyArgumentList output_file = QFileDialog.getSaveFileNameAndFilter( parent=self.parent, caption=tr('Export as CSV'), filter='CSV (*.csv)') self.le_output.setText(output_file[0])
def save_y_values(self): if not self.tableWidget.rowCount(): return False csv_string = 'parameter,values\n' for value in self.tab: csv_string += str(value) + '\n' last_directory = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName( parent=self, caption=tr('Select file'), directory=last_directory, filter='CSV (*.csv)') if output_file: path = dirname(output_file) set_last_input_path(path) fh = open(output_file, 'w') fh.write(csv_string) fh.close() return True
def save_table(self): if not self.tableWidget.rowCount(): return False csv_string = 'parameter,values\n' for i in range(self.tableWidget.rowCount()): item_param = self.tableWidget.item(i, 0) item_value = self.tableWidget.item(i, 1) csv_string += \ str(item_param.text()) + ',' + item_value.text() + '\n' last_directory = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName( parent=self, caption=tr('Select file'), directory=last_directory, filter='CSV (*.csv)') if output_file: path = dirname(output_file) set_last_input_path(path) fh = open(output_file, 'w') fh.write(csv_string) fh.close() return True
def setOutDirectory(self): outDir = QFileDialog.getExistingDirectory( self, self.tr("Select output directory"), ".") if not outDir: return self.leOutputDir.setText(outDir)
def run_calc(self, calc_id=None, file_names=None, directory=None): """ Run a calculation. If `calc_id` is given, it means we want to run a calculation re-using the output of the given calculation """ text = self.tr('Select the files needed to run the calculation,' ' or the zip archive containing those files.') if directory is None: default_dir = QSettings().value('irmt/run_oqengine_calc_dir', QDir.homePath()) else: default_dir = directory if not file_names: file_names = QFileDialog.getOpenFileNames(self, text, default_dir) if not file_names: return if directory is None: selected_dir = QFileInfo(file_names[0]).dir().path() QSettings().setValue('irmt/run_oqengine_calc_dir', selected_dir) else: file_names = [os.path.join(directory, os.path.basename(file_name)) for file_name in file_names] if len(file_names) == 1: file_full_path = file_names[0] _, file_ext = os.path.splitext(file_full_path) if file_ext == '.zip': zipped_file_name = file_full_path else: # NOTE: an alternative solution could be to check if the single # file is .ini, to look for all the files specified in the .ini # and to build a zip archive with all them msg = "Please select all the files needed, or a zip archive" log_msg(msg, level='C', message_bar=self.message_bar) return else: _, zipped_file_name = tempfile.mkstemp() with zipfile.ZipFile(zipped_file_name, 'w') as zipped_file: for file_name in file_names: zipped_file.write(file_name) run_calc_url = "%s/v1/calc/run" % self.hostname with WaitCursorManager('Starting calculation...', self.message_bar): if calc_id is not None: # FIXME: currently the web api is expecting a hazard_job_id # although it could be any kind of job_id. This will have to be # changed as soon as the web api is updated. data = {'hazard_job_id': calc_id} else: data = {} files = {'archive': open(zipped_file_name, 'rb')} try: resp = self.session.post( run_calc_url, files=files, data=data, timeout=20) except HANDLED_EXCEPTIONS as exc: self._handle_exception(exc) return if resp.ok: self.refresh_calc_list() return resp.json() else: log_msg(resp.text, level='C', message_bar=self.message_bar)
def selectXlsFiles(self): projFolder = toUnicode(self.projFolderEdit.text()) xlsFiles = QFileDialog.getOpenFileNames( directory=projFolder, filter='*.xls; *.xlsx', caption=toUnicode(MSG['msg06'])) textString = '' for xls in xlsFiles: textString = xls + ';' textString = textString[0: -1] self.xlsFilesEdit.setText(textString) items = list() itemNames = list() for xlsFile in xlsFiles: Species = readXls(xlsFile) for specie in Species: if toUnicode(specie[0][13]) not in itemNames: itemNames.append(toUnicode(specie[0][13])) specieListItem = specieItem(toUnicode(specie[0][13]), specie, self.specieListWidget) items.append(specieListItem) for item in items: self.specieListWidget.addItem(item) if items: self.specieListWidget.setCurrentRow(0) item = self.specieListWidget.currentItem() self.showAttribute(item)
def open_file_browser(self): # noinspection PyArgumentList shapefile = QFileDialog.getOpenFileName( parent=self.parent, caption=tr('Select table'), filter='Table (*.xls *.xlsx *.dbf)') self.le_shapefile.setText(shapefile)
def on_output_data_dir_btn_clicked(self): default_dir = QSettings().value('irmt/output_data_dir', QDir.homePath()) path = QFileDialog.getExistingDirectory( self, self.tr('Choose output directory'), default_dir) if path: QSettings().setValue('irmt/output_data_dir', path) self.output_data_dir_le.setText(path)
def run(self): self.dlg.show() self.updateLayers() self.registry.layersAdded.connect(self.updateLayers) self.registry.layerRemoved.connect(self.updateLayers) result = self.dlg.exec_() if result == 1: folder = QFileDialog.getExistingDirectory() self.exportItems(toUnicode(folder))
def browseForInput(self): """ Open a browse for files dialog - for the moment set to browse directory mode """ settings = QtCore.QSettings() startingDir = str(settings.value("OsTranslatorII/lastInputFolder", os.path.expanduser("~"))) d = str( QFileDialog.getExistingDirectory(None, 'Browse For Input', startingDir) ) if d != os.sep and d.lower() != 'c:\\' and d != '': settings.setValue("OsTranslatorII/lastInputFolder", d) self.inputLineEdit.setText(d)
def selectProjFolder(self): try: presetFolder = self.dlg.projFolderEdit.text() except (KeyError): presetFolder = '' caption = 'Please choose a project folder' folderName = QFileDialog.getExistingDirectory(self.dlg, caption, presetFolder) self.dlg.projFolderEdit.setText(toUnicode(folderName))
def open_file_browser(self): # noinspection PyArgumentList raster_filter = QgsProviderRegistry.instance().fileRasterFilters() # noinspection PyArgumentList raster = QFileDialog.getOpenFileName(parent=self.parent, caption=tr('Select raster'), filter=raster_filter) self.le_shapefile.setText(raster)
def selectTECFile(self): Caption = 'Please select a _TEC_.dat file or multiple files' projFolder = toUnicode(self.dlg.projFolderEdit.text()) filePathes = QFileDialog.getOpenFileNames( self.dlg, Caption, os.path.join(projFolder, 'sim'), "*.dat") for path in filePathes: path = toUnicode(path) fileWidget = TECfile(self.dlg.fileListWidget, 0, toUnicode(path), self.iface) self.dlg.fileListWidget.addItem(fileWidget)
def import_layer_from_csv(parent, csv_path, layer_name, iface, longitude_field='lon', latitude_field='lat', delimiter=',', quote='"', lines_to_skip_count=0, wkt_field=None, save_as_shp=False, dest_shp=None, zoom_to_layer=True, has_geom=True): url = QUrl.fromLocalFile(csv_path) url.addQueryItem('type', 'csv') if has_geom: if wkt_field is not None: url.addQueryItem('wktField', wkt_field) else: url.addQueryItem('xField', longitude_field) url.addQueryItem('yField', latitude_field) url.addQueryItem('spatialIndex', 'no') url.addQueryItem('crs', 'epsg:4326') url.addQueryItem('subsetIndex', 'no') url.addQueryItem('watchFile', 'no') url.addQueryItem('delimiter', delimiter) url.addQueryItem('quote', quote) url.addQueryItem('skipLines', str(lines_to_skip_count)) url.addQueryItem('trimFields', 'yes') layer_uri = str(url.toEncoded()) layer = QgsVectorLayer(layer_uri, layer_name, "delimitedtext") if save_as_shp: dest_filename = dest_shp or QFileDialog.getSaveFileName( parent, 'Save loss shapefile as...', os.path.expanduser("~"), 'Shapefiles (*.shp)') if dest_filename: if dest_filename[-4:] != ".shp": dest_filename += ".shp" else: return result = save_layer_as_shapefile(layer, dest_filename) if result != QgsVectorFileWriter.NoError: raise RuntimeError('Could not save shapefile') layer = QgsVectorLayer(dest_filename, layer_name, 'ogr') if layer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(layer) iface.setActiveLayer(layer) if zoom_to_layer: iface.zoomToActiveLayer() else: msg = 'Unable to load layer' log_msg(msg, level='C', message_bar=iface.messageBar()) return None return layer
def addTecFiles(self): simFolder = os.path.join(self.settings.value('projFolder'), 'sim') TecFiles = QFileDialog().getOpenFileNames(directory=simFolder) if TecFiles: for file in TecFiles: item = TECfile(self.tecList, QListWidgetItem.Type, file, self.iface) item.readTEC(file) item.readVariables(item.dat) self.tecList.addItem(item) self.addAttribute()
def run(self): self.dlg.show() self.layerFromRegistry() self.registry.layersAdded.connect(self.layerFromRegistry) self.registry.layerRemoved.connect(self.layerFromRegistry) result = self.dlg.exec_() if result == 1: folder = QFileDialog.getExistingDirectory() folder = toUnicode(folder) self.setOutputDir(folder) self.exportContour()
def exportText(self): projFolder = self.settings.value('projFolder') if self.settings.value('profileTextExport') == '.txt': exportFile = QFileDialog.getSaveFileName( directory=projFolder, filter='Text files(*.txt)') exportFile = toUnicode(exportFile) if self.profiles and exportFile: f = open(exportFile, 'w') if self.dlg.batchChecker.checkState() == 0: plotTool().exportToTxt(self.profiles, f) elif self.dlg.batchChecker.checkState() == 2: layer = self.dlg.layerCombo.currentLayer() self.batchExportAsTxt(layer, f) f.close() elif self.settings.value('profileTextExport') == '.csv': exportFile = QFileDialog.getSaveFileName( directory=projFolder, filter='Text files(*.csv)') exportFile = toUnicode(exportFile) if self.profiles and exportFile: f = open(exportFile, 'w') if self.dlg.batchChecker.checkState() == 0: plotTool().exportToCsv(self.profiles, f) elif self.dlg.batchChecker.checkState() == 2: layer = self.dlg.layerCombo.currentLayer() self.batchExportAsCsv(layer, f) f.close() elif self.settings.value('profileTextExport') == '.xls': exportFile = QFileDialog.getSaveFileName( directory=projFolder, filter='Excel Workbook(*.xls)') exportFile = toUnicode(exportFile) if self.profiles and exportFile: wb = xlwt.Workbook() if self.dlg.batchChecker.checkState() == 0: sh = wb.add_sheet('profile') plotTool().exportToXls(self.profiles, sh) elif self.dlg.batchChecker.checkState() == 2: layer = self.dlg.layerCombo.currentLayer() self.batchExportAsXls(layer, wb) wb.save(exportFile)
def ask_for_download_destination_folder(parent, text='Download destination'): """ Open a dialog to ask for a download destination folder, initially pointing to the home directory. :param parent: the parent dialog :param text: the dialog's title text :returns: full path of the destination folder """ return QFileDialog.getExistingDirectory(parent, text, os.path.expanduser("~"))
def select_file(self): last_folder = get_last_input_path() # noinspection PyArgumentList output_file = QFileDialog.getSaveFileName(parent=self, caption=tr('Select file'), directory=last_folder, filter='Shapefiles (*.shp)') if output_file: self.lineEdit_outputFile.setText(output_file) path = dirname(output_file) set_last_input_path(path) else: self.lineEdit_outputFile.setText('')
def genReport(self): tec = self.tecItemList.currentItem() projFolder = self.settings.value('projFolder') saveFile = QFileDialog.getSaveFileName(filter=self.tr('*.txt;; *.csv'), directory=projFolder) if saveFile.endswith('.txt'): self.reportAsTxt(tec, saveFile) elif saveFile.endswith('.csv'): self.reportAsCsv(tec, saveFile) else: QMessageBox(QMessageBox.Critical, title=toUnicode(MSG['msg26']), text=toUnicode(MSG['msg25']))
def select_files(self): """ Open a file browser to select multiple files in the ipt_dir, and return the list of names of selected files """ try: ipt_dir = self.parent().ipt_dir file_names = QFileDialog.getOpenFileNames(self.parent().parent(), 'Select files', ipt_dir) ls = [os.path.basename(file_name) for file_name in file_names] except Exception as exc: return {'ret': 1, 'content': None, 'reason': str(exc)} else: return {'ret': 0, 'content': ls, 'reason': 'ok'}
def select_file(self): """ Open a file browser to select a single file in the ipt_dir, and return the name of the selected files """ try: ipt_dir = self.parent().ipt_dir file_name = QFileDialog.getOpenFileName(self.parent().parent(), 'Select file', ipt_dir) basename = os.path.basename(file_name) except Exception as exc: return {'ret': 1, 'content': None, 'reason': str(exc)} else: return {'ret': 0, 'content': basename, 'reason': 'ok'}
def addTECFiles(self): filePath = QFileDialog.getOpenFileName( caption=toUnicode(MSG['msg02']), directory=self.dlg.projFolderEdit.text(), filter="*.dat") if filePath: fileWidget = TECfile(self.dlg.tecSelectListWidget, 0, toUnicode(filePath), self.iface) self.dlg.tecSelectListWidget.addItem(fileWidget) self.dlg.addAttributeToSettings() # Limit allowed TEC file to 1 TEC file only if self.dlg.tecSelectListWidget.count() >= 1: self.dlg.addTecBtn.setEnabled(False)
def import_loss_layer_from_csv(self, csv_file_path, dest_shp=None, delete_lon_lat=False): # FIXME: hardcoded field names longitude_field = 'LON' latitude_field = 'LAT' lines_to_skip_count = count_heading_commented_lines(csv_file_path) url = QUrl.fromLocalFile(csv_file_path) url.addQueryItem('type', 'csv') url.addQueryItem('xField', longitude_field) url.addQueryItem('yField', latitude_field) url.addQueryItem('spatialIndex', 'no') url.addQueryItem('subsetIndex', 'no') url.addQueryItem('watchFile', 'no') url.addQueryItem('delimiter', ',') url.addQueryItem('crs', 'epsg:4326') url.addQueryItem('skipLines', str(lines_to_skip_count)) url.addQueryItem('trimFields', 'yes') layer_uri = str(url.toEncoded()) csv_layer = QgsVectorLayer(layer_uri, 'Loss', "delimitedtext") dest_filename = dest_shp or QFileDialog.getSaveFileName( self, 'Save loss shapefile as...', os.path.expanduser("~"), 'Shapefiles (*.shp)') if dest_filename: if dest_filename[-4:] != ".shp": dest_filename += ".shp" else: return result = save_layer_as_shapefile(csv_layer, dest_filename) if result != QgsVectorFileWriter.NoError: raise RuntimeError('Could not save shapefile') shp_layer = QgsVectorLayer( dest_filename, 'Loss data', 'ogr') if delete_lon_lat: ProcessLayer(shp_layer).delete_attributes( [longitude_field, latitude_field]), if shp_layer.isValid(): QgsMapLayerRegistry.instance().addMapLayer(shp_layer) else: msg = 'Invalid loss map' log_msg(msg, level='C', message_bar=self.iface.messageBar()) return None return shp_layer
def outTIF(self, plotWidget, d_folder, name, title): if d_folder: fileName = os.path.join(d_folder, name + '.tif') else: if self.settings.value('lastOutputDir'): folder = self.settings.value('lastOutputDir') else: folder = self.settings.value('projFolder') fileName = QFileDialog.getSaveFileName( caption="Save Plot As .tif file", directory=folder, filter="Tagged Image File Format (*.tif;*.tiff)") fileName = toUnicode(fileName) if fileName: if not title: title = self.settings.value('figureTitle') plotWidget.setTitle(title) pix = QPixmap(QSize(600, 400)) sh = QBrush(pix) sh.setColor(Qt.white) sh.setStyle(Qt.SolidPattern) painter = QPainter() painter.begin(pix) painter.setBrush(sh) painter.drawRect(0, 0, 600, 400) painter.end() legend = QwtLegend() plotWidget.insertLegend(legend) plotWidget.setAxisTitle(QwtPlot.xBottom, self.settings.value('xAxisTitle')) plotWidget.setAxisTitle(QwtPlot.yLeft, self.settings.value('yAxisTitle')) QSettings().setValue("lastOutputDir", os.path.dirname(fileName)) filter = QwtPlotPrintFilter() filter.setOptions(QwtPlotPrintFilter.PrintAll & ~QwtPlotPrintFilter.PrintBackground) plotWidget.print_(pix, filter) pix.save(fileName) plotWidget.insertLegend(None) plotWidget.setAxisTitle(QwtPlot.xBottom, None) plotWidget.setAxisTitle(QwtPlot.yLeft, None) plotWidget.setTitle(None)
def open_zonal_layer_dialog(self): """ Open a file dialog to select the zonal layer to be loaded :returns: the zonal layer """ text = self.tr('Select zonal layer to import') filters = self.tr('Vector shapefiles (*.shp);;SQLite (*.sqlite);;' 'All files (*.*)') default_dir = QSettings().value('irmt/select_layer_dir', QDir.homePath()) file_name, file_type = QFileDialog.getOpenFileNameAndFilter( self, text, default_dir, filters) if not file_name: return None selected_dir = QFileInfo(file_name).dir().path() QSettings().setValue('irmt/select_layer_dir', selected_dir) zonal_layer_plus_stats = self.load_zonal_layer(file_name) return zonal_layer_plus_stats
def run(self): self.dlg.show() result = self.dlg.exec_() if result == 1: self.workingFolder = toUnicode( QFileDialog.getExistingDirectory( directory=self.settings.value('projFolder'))) self.settings.setValue('animeName', self.dlg.outputNameEdit.text()) self.settings.setValue('animeLapse', int(self.dlg.timeLapseEdit.text())) if self.workingFolder: # Load map export template from .qgs file # composer, mapSet = self.loadTemplate(template) self.renderLayers() if self.dlg.exportTypeCombo.currentText() == '.gif': self.genGif() elif self.dlg.exportTypeCombo.currentText() == '.mp4': self.genMp4()
def open_file_dialog(self, dialog_type): """ Open a file dialog to select the data file to be loaded :param string dialog_type: 'loss_layer' or 'zonal_layer' :returns: a layer """ if dialog_type == 'loss_layer': text = self.tr('Select loss map to import') # FIXME: What should be the format of the raster maps? filters = self.tr('Loss curves from the OpenQuake-engine (*.csv);;' 'Shapefile vector loss curves (*.shp);;' 'Geojson vector loss curves (*.geojson);;' 'Raster loss curves (*.*)') elif dialog_type == 'zonal_layer': text = self.tr('Select zonal layer to import') filters = self.tr('Vector shapefiles (*.shp);;SQLite (*.sqlite);;' 'All files (*.*)') else: raise RuntimeError('Invalid dialog_type: {}'.format(dialog_type)) default_dir = QSettings().value('irmt/select_layer_dir', QDir.homePath()) file_name, file_type = QFileDialog.getOpenFileNameAndFilter( self, text, default_dir, filters) if dialog_type == 'zonal_layer': if not file_name: return None selected_dir = QFileInfo(file_name).dir().path() QSettings().setValue('irmt/select_layer_dir', selected_dir) layer = self.load_zonal_layer(file_name) elif dialog_type == 'loss_layer': if not file_name: return None selected_dir = QFileInfo(file_name).dir().path() QSettings().setValue('irmt/select_layer_dir', selected_dir) if file_type == 'Raster loss curves (*.*)': self.loss_layer_is_vector = False if file_type == 'Loss curves from the OpenQuake-engine (*.csv)': layer = self.import_loss_layer_from_csv(file_name) else: layer = self.load_loss_layer(file_name) else: raise RuntimeError return layer
def downloadContent(self, reply): self.stop() home = os.path.expanduser('~') downloads = os.path.join(home, 'Downloads') download = os.path.join(home, 'Download') if os.path.isdir(downloads): dest_dir = downloads if os.path.isdir(download): dest_dir = download if not dest_dir: dest_dir = QFileDialog.getExistingDirectory( self, tr("Select the destination folder"), home, QFileDialog.ShowDirsOnly) if not dest_dir: return try: file_name = reply.rawHeader('Content-Disposition').split('=')[1] file_name = str(file_name).strip('"') except Exception as exc: header_pairs = reply.rawHeaderPairs() self.gem_api.common.error( 'Unable to get the file name from headers: %s\n' 'Exception: %s' % (header_pairs, str(exc))) return file_content = str(reply.readAll()) # From # http://doc.qt.io/archives/qt-4.8/qwebpage.html#unsupportedContent # "The receiving slot is responsible for deleting the reply" reply.close() reply.deleteLater() file_fullpath = os.path.join(dest_dir, file_name) if os.path.exists(file_fullpath): name, ext = os.path.splitext(file_name) i = 1 while True: file_fullpath = os.path.join(dest_dir, '%s_%s%s' % (name, i, ext)) if not os.path.exists(file_fullpath): break i += 1 with open(file_fullpath, "w") as f: f.write(file_content) self.gem_api.common.info('File downloaded as: %s' % file_fullpath)
def open_file_dialog(self): """ Open a file dialog to select the data file to be loaded """ text = self.tr('Select the OQ-Engine output file to import') if self.output_type in OQ_CSV_TO_LAYER_TYPES: filters = self.tr('CSV files (*.csv)') else: raise NotImplementedError(self.output_type) default_dir = QSettings().value('irmt/load_as_layer_dir', QDir.homePath()) path = QFileDialog.getOpenFileName(self, text, default_dir, filters) if not path: return selected_dir = QFileInfo(path).dir().path() QSettings().setValue('irmt/load_as_layer_dir', selected_dir) self.path = path self.path_le.setText(self.path) return path