Esempio n. 1
0
    def exportCsv(self):
        fileDlg = QFileDialog()
        filePath = fileDlg.getSaveFileName(None,
                                           u"Selecionar arquivo de saída", "",
                                           u"Arquivo CSV (*.csv)")[0]

        if filePath != "" and filePath[-4:].lower() != ".csv":
            filePath += ".csv"

        if filePath != "":
            csvFile = open(filePath, 'w')
        else:
            return

        csvFile.write(u'Ponto;X;Y;Azimute;Distancia;Destino\n')

        for i in range(0, self.mapList.topLevelItemCount() - 1):
            csvFile.write(u'{};{};{};{};{};{}\n'.format(
                self.mapList.topLevelItem(i).data(0, 0),
                self.mapList.topLevelItem(i).data(1, 0),
                self.mapList.topLevelItem(i).data(2, 0),
                self.mapList.topLevelItem(i).data(3, 0),
                self.mapList.topLevelItem(i).data(4, 0),
                self.mapList.topLevelItem(i).data(5, 0)))

        csvFile.close()
Esempio n. 2
0
 def import_(self):
     """
     Request a file for Workflow importation and sets it to GUI.
     :return: (bool) operation status.
     """
     fd = QFileDialog()
     filename = fd.getOpenFileName(
         caption=self.tr('Select a Workflow file'),
         filter=self.tr('DSGTools Workflow (*.workflow *.json)'))
     filename = filename[0] if isinstance(filename, tuple) else ""
     if not filename:
         return False
     try:
         self.importWorkflow(filename)
     except Exception as e:
         self.messageBar.pushMessage(
             self.tr('Invalid workflow'),
             self.tr(
                 "Unable to export workflow to '{fp}' ({error}).").format(
                     fp=filename, error=str(e)),
             level=Qgis.Critical,
             duration=5)
         return False
     self.messageBar.pushMessage(
         self.tr('Success'),
         self.tr("Workflow '{fp}' imported!").format(fp=filename),
         level=Qgis.Info,
         duration=5)
     return True
Esempio n. 3
0
 def loadMapping(self):
     dialog = QFileDialog(self.dlg)
     dialog.setFileMode(QFileDialog.AnyFile)
     if dialog.exec_():
         fileNames = dialog.selectedFiles()
         filepath=fileNames[0].split(".")
         self.readMapping(fileNames[0])
Esempio n. 4
0
    def _get_file_dialog(self, dialog, widget):
        """ Get file dialog """

        # Check if selected file exists. Set default value if necessary
        file_path = tools_qt.get_text(dialog, widget)
        if file_path is None or file_path == 'null' or not os.path.exists(str(file_path)):
            folder_path = global_vars.plugin_dir
        else:
            folder_path = os.path.dirname(file_path)
        # Open dialog to select file
        os.chdir(folder_path)
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.AnyFile)
        message = "Select file"
        files_path, filter_ = file_dialog.getOpenFileNames(parent=None, caption=tools_qt.tr(message))

        file_text = ""
        if len(files_path) == 1:
            file_text += f"{files_path[0]}"
        else:
            for file in files_path:
                file_text += f"{file}\n\n"
        if files_path:
            tools_qt.set_widget_text(dialog, widget, str(file_text))
        return files_path
Esempio n. 5
0
 def on_importPushButton_clicked(self):
     """
     Imports a property file into dsgtools_admindb
     """
     fd = QFileDialog()
     widgetType = self.getWhoAmI()
     filename = fd.getOpenFileName(caption=self.captionDict[widgetType],
                                   filter=self.filterDict[widgetType])[0]
     filename = filename[0] if isinstance(filename, tuple) else filename
     if filename == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a file to import!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.importSetting(filename)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.widgetName + self.tr(' successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem importing ') + self.widgetName + ': ' +
             ':'.join(e.args))
     self.refresh()
Esempio n. 6
0
 def exportSetup(self):
     """
     Exports current setup's saved state to a file.
     :return: (bool) whether setup was exported.
     """
     if not self.isValid():
         msg = self.tr("Invalid input data: {r}").format(r=self.validate())
         self.raiseWarning(msg)
         return False
     # add check of modified button in here
     s = self.readSetup()
     fd = QFileDialog()
     filename = fd.getSaveFileName(
         caption=self.tr("Export setup - {0}").format(s.name()),
         filter=self.tr("DSGTools Buttons Setup (*.setup)"))
     filename = filename[0] if isinstance(filename, tuple) else filename
     if not filename:
         return False
     with open(filename, "w", encoding="utf-8") as fp:
         fp.write(json.dumps(self.state(), sort_keys=True, indent=4))
     res = os.path.exists(filename)
     if res:
         msg = self.tr('Setup "{0}" exported to "{1}"')\
                   .format(s.name(), filename)
         self.raiseWarning(msg,
                           title=self.tr("Exported workflow"),
                           lvl=Qgis.Success)
     return res
Esempio n. 7
0
    def project_new_clicked(self):

        self.btn_project_new.setChecked(False)

        file_dialog = QFileDialog()
        file_dialog.setWindowTitle('New project')
        file_dialog.setLabelText(QFileDialog.Accept, 'Create')
        file_dialog.setNameFilter('Inp files (*.inp)')
        if file_dialog.exec_():

            inp_file_path = file_dialog.selectedFiles()[0]
            if not inp_file_path.lower().endswith('.inp'):
                inp_file_path += '.inp'

            self.inp_file_path = inp_file_path
            self.params.last_project_dir = os.path.dirname(inp_file_path)

            lay_utils.remove_layers(self.params)

            # Request CRS for layers
            self.crs_selector()
            self.create_layers(None, self.params.crs)

            self.txt_prj_file.setText(self.inp_file_path)

            # Prompt for hydaulic options
            if self.hydraulics_dialog is None:
                self.hydraulics_dialog = HydraulicsDialog(
                    self, self.params, True)
            self.hydraulics_dialog.show()
Esempio n. 8
0
 def _saveToFile(self, sender, startFolder=None):
     filter = "OGC GeoPackage (*.gpkg);;ESRI Shape Files (*.shp);;SpatiaLite (*.sqlite);;Geojson File (*.geojson);;GML ( *.gml);;Comma separated value File (excel) (*.csv);;MapInfo TAB (*.TAB);;Any File (*.*)"
     Fdlg = QFileDialog()
     Fdlg.setFileMode(QFileDialog.AnyFile)
     fName, __ = QFileDialog.getSaveFileName(sender,
                                             "open file",
                                             filter=filter,
                                             directory=startFolder)
     if fName:
         ext = os.path.splitext(fName)[1]
         if "GPKG" in ext.upper():
             flType = "GPKG"
         elif "SHP" in ext.upper():
             flType = "ESRI Shapefile"
         elif "SQLITE" in ext.upper():
             flType = "SQLite"
         elif "GEOJSON" in ext.upper():  #no update possible -> hidden
             flType = "GeoJSON"
         elif "GML" in ext.upper():
             flType = "GML"
         elif 'TAB' in ext.upper():
             flType = 'MapInfo File'
         elif 'CSV' in ext.upper():
             flType = 'CSV'
         else:
             fName = fName + ".shp"
             flType = "ESRI Shapefile"
         return (fName, flType)
     else:
         return None
Esempio n. 9
0
    def getFileName(self, text, filter, filePath):
        """filter: [["Shapefile", "shp"], ["Keyhole Markup Language", "kml"]]"""
        filters = []
        for item in filter:
            filters.append("%s (*.%s)" % (item[0], item[1]))
        fileDlg = QFileDialog(self.iface.mainWindow())
        fileDlg.setNameFilters(filters)
        fileName, selectedFilter = fileDlg.getSaveFileName(self.iface.mainWindow(),
                                           text,
                                           filePath,
                                           ";;".join(filters)
                                           )
        QgsMessageLog.logMessage("selectedFilter: {0}".format(selectedFilter), "VoGis", Qgis.Info)

        #QgsMessageLog.logMessage("{0}".format(fileName), "VoGis", Qgis.Info)
        if fileName is None or fileName == "":
            return "", ""

        QgsMessageLog.logMessage("fileDlg.filters(): {0}".format(fileDlg.nameFilters()), "VoGis", Qgis.Info)
        selectedFilter = fileDlg.nameFilters().index(selectedFilter)
        fileExt = filter[selectedFilter][1]

        QgsMessageLog.logMessage("selectedFilter: {0}".format(selectedFilter), "VoGis", Qgis.Info)
        QgsMessageLog.logMessage("fileExt: {0}".format(fileExt), "VoGis", Qgis.Info)

        if fileName.lower().endswith(fileExt) is False:
            fileName = fileName + "." + fileExt
        return fileName, fileExt
Esempio n. 10
0
    def on_import_config(self):
        s = QSettings("Oslandia", "QGeoloGIS")
        last_dir = s.value("config_last_dir", None)
        if not last_dir:
            last_dir = os.path.dirname(__file__)

        dlg = QDialog(None)
        file_dialog = QFileDialog(
            None,
            "Choose a configuration file to import",
            last_dir,
            "JSON files (*.json)",
            options=QFileDialog.
            DontUseNativeDialog  # transform into an embeddable QWidget
        )
        # when file dialog is done, close the main dialog
        file_dialog.finished.connect(dlg.done)
        overwrite_checkbox = QCheckBox("Overwrite existing layers")
        overwrite_checkbox.setChecked(True)
        vbox = QVBoxLayout()
        vbox.addWidget(file_dialog)
        vbox.addWidget(overwrite_checkbox)
        dlg.setLayout(vbox)

        r = dlg.exec_()
        print(r)
        if r == QDialog.Accepted:
            filename = file_dialog.selectedFiles()[0]
            s.setValue("config_last_dir", os.path.dirname(filename))
            self.__config = import_config(
                filename, overwrite_existing=overwrite_checkbox.isChecked())
            QgsProject.instance().writeEntry("QGeoloGIS", "config",
                                             json.dumps(self.__config))
Esempio n. 11
0
 def on_selectFilePushButton_clicked(self):
     """
     Selects the correct way to choose files according to the type
     """
     fd = QFileDialog()
     fd.setDirectory(QDir.homePath())
     if self.type == 'multi':
         self.fileNameList = fd.getOpenFileNames(caption=self.caption,
                                                 filter=self.filter)
         selectedFiles = ', '.join(self.fileNameList[0])
     elif self.type == 'single':
         selectedFiles = fd.getOpenFileName(caption=self.caption,
                                            filter=self.filter)
         if selectedFiles != '':
             self.fileNameList = selectedFiles
     elif self.type == 'dir':
         selectedFiles = fd.getExistingDirectory(
             directory=os.path.expanduser('~'),
             caption=self.caption,
             options=QFileDialog.ShowDirsOnly)
         if selectedFiles != '':
             self.fileNameList = [selectedFiles]
     selectedFiles = selectedFiles[0] if isinstance(
         selectedFiles, tuple) else selectedFiles
     self.lineEdit.setText(selectedFiles)
     self.filesSelected.emit()
Esempio n. 12
0
    def on_exportPushButton_clicked(self):
        if not self.permissionTreeWidget.currentItem() or (
                self.permissionTreeWidget.currentItem().text(0) != ''
                or self.permissionTreeWidget.currentItem().text(2) != ''):
            QMessageBox.warning(self, self.tr('Warning!'),
                                self.tr('Error! Select a profile to export!'))
            return

        fd = QFileDialog()
        folder = fd.getExistingDirectory(
            caption=self.tr('Select a folder to output'))
        if folder == '':
            # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Error! Select a output!'))
            return
        profileName = self.permissionTreeWidget.currentItem().text(1)
        dbName = self.permissionTreeWidget.currentItem().parent().text(0)
        edgvVersion = self.dbDict[dbName].getDatabaseVersion()
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.permissionManager.exportSetting(profileName, edgvVersion,
                                                 folder)
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('Success!'),
                                self.tr('Permission successfully exported.'))
        except Exception as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(
                self, self.tr('Warning!'),
                self.tr('Error! Problem exporting permission: ') +
                ':'.join(e.args))
Esempio n. 13
0
    def exportCsv(self):
        fileDlg = QFileDialog()
        filePath = fileDlg.getSaveFileName(None,
                                           u"Selecionar arquivo de saída", "",
                                           u"Arquivo CSV (*.csv)")[0]

        if filePath != "" and filePath[-4:].lower() != ".csv":
            filePath += ".csv"

        if filePath != "":
            csvFile = open(filePath, 'w')

        if filePath == "":
            return

        csvFile.write(u'Escala;Nomenclatura;MI\n')

        itemCount = self.mapList.invisibleRootItem().childCount()
        for i in range(itemCount):
            currentItem = self.mapList.invisibleRootItem().child(i)
            for j in range(currentItem.childCount()):
                csvFile.write(u'{};{};{}\n'.format(
                    currentItem.text(0),
                    currentItem.child(j).text(0),
                    currentItem.child(j).text(1)))

        csvFile.close()
Esempio n. 14
0
    def do_export_plan_action(self, count_id):
        plan_creator = PlanCreator(self.layers)
        file_dialog = QFileDialog()
        file_dialog.setDefaultSuffix('*.PDF')
        title = 'Exporter plan de pose'
        path = os.path.join(self.settings.value('config_export_directory'),
                            "{}.pdf".format("plan_de_pose"))
        file = QFileDialog.getSaveFileName(file_dialog, title, path,
                                           "Config file (*.PDF)")[0]

        if not file:
            return

        # Highlight the current sections and installation in the layout
        previous_highlightes_sections = self.layers.highlighted_sections
        self.layers.highlighted_sections = \
            self.layers.get_section_ids_of_count(count_id)
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'highlighted_installation',
            self.layers.get_installation_name_of_count(count_id))

        plan_creator.export_pdf(count_id, file)

        self.layers.highlighted_sections = previous_highlightes_sections
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'highlighted_installation', '')
        self.layers.layers['section'].triggerRepaint()
Esempio n. 15
0
 def qfd(*args):
     """
     QFileDialog.getOpenFileName(qfd, title, path)
     :param args: title, path
     :return:
     """
     return QFileDialog.getOpenFileName(QFileDialog(), *args)
Esempio n. 16
0
    def data_prep_get_output_dir(self):
        dlgx = QFileDialog()
        dlgx.setFileMode(QFileDialog.Directory)

        if dlgx.exec_():
            filenames = dlgx.selectedFiles()
            self.ui.lineEdit_11.setText(str(filenames[0]))
Esempio n. 17
0
 def save_profile_as(self):
     """Save the minimum needs under a new profile name.
     """
     # noinspection PyCallByClass,PyTypeChecker
     file_name_dialog = QFileDialog(self)
     file_name_dialog.setAcceptMode(QFileDialog.AcceptSave)
     file_name_dialog.setNameFilter(self.tr('JSON files (*.json *.JSON)'))
     file_name_dialog.setDefaultSuffix('json')
     dir = os.path.join(QgsApplication.qgisSettingsDirPath(),
                        'inasafe', 'minimum_needs')
     file_name_dialog.setDirectory(expanduser(dir))
     if file_name_dialog.exec_():
         file_name = file_name_dialog.selectedFiles()[0]
     else:
         return
     file_name = basename(file_name)
     file_name = file_name.replace('.json', '')
     minimum_needs = {'resources': []}
     self.mark_current_profile_as_saved()
     for index in range(self.resources_list.count()):
         item = self.resources_list.item(index)
         minimum_needs['resources'].append(item.resource_full)
     minimum_needs['provenance'] = self.provenance.text()
     minimum_needs['profile'] = file_name
     self.minimum_needs.update_minimum_needs(minimum_needs)
     self.minimum_needs.save()
     self.minimum_needs.save_profile(file_name)
     if self.profile_combo.findText(file_name) == -1:
         self.profile_combo.addItem(file_name)
     self.profile_combo.setCurrentIndex(
         self.profile_combo.findText(file_name))
Esempio n. 18
0
    def do_generate_report_action(self, count_id):
        if self.tm.countActiveTasks() > 0:
            push_info(("Veuillez patienter jusqu'à ce que l'importation "
                       "soit terminée."))
            return

        # Show message if there are no data to process
        contains_data = self.layers.count_contains_data(count_id)
        if not contains_data :
            push_info("Installation {}: Il n'y a pas de données à traiter pour "
                "le comptage {}".format(
                self.layers.get_installation_name_of_count(count_id),count_id))
            return

        file_dialog = QFileDialog()
        title = 'Exporter un rapport'
        path = self.settings.value('report_export_directory')
        file_path = QFileDialog.getExistingDirectory(
            file_dialog, title, path)
        print(file_path)

        if not file_path:
            return

        report_creator = ReportCreator(count_id, file_path, self.layers)
        report_creator.run()
        push_info("Installation {} (count={}): Génération du rapport terminée."
         .format(self.layers.get_installation_name_of_count(count_id),count_id))
Esempio n. 19
0
 def on_exportPropertyPushButton_clicked(self):
     """
     Export selected properties.
     """
     exportPropertyList = [self.propertyComboBox.currentText()]
     if exportPropertyList == []:
         QMessageBox.warning(
             self, self.tr('Warning!'),
             self.tr('Warning! Select a profile to export!'))
         return
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder to output'))
     folder = folder[0] if isinstance(folder, tuple) else folder
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a output!'))
         return
     edgvVersion = self.genericDbManager.edgvVersion
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         for exportProperty in exportPropertyList:
             self.genericDbManager.exportSetting(exportProperty,
                                                 edgvVersion, folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.tr('Success! {0} successfully exported.').format(
                 self.widgetName))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem exporting {0}: {1}').format(
                 self.widgetName, ':'.join(e.args)))
Esempio n. 20
0
 def on_importPropertyPushButton_clicked(self):
     """
     Imports a property file into dsgtools_admindb
     """
     fd = QFileDialog()
     widgetType = self.getWhoAmI()
     filename = fd.getOpenFileName(caption=self.captionDict[widgetType],
                                   filter=self.filterDict[widgetType])
     if filename == '':
         QMessageBox.warning(self, self.tr('Warning!'),
                             self.tr('Warning! Select a file to import!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.importSetting(filename)
         settingName = os.path.basename(fullFilePath).split('.')[0]
         self.genericDbManager.installSetting(
             settingName, dbList=[self.abstractDb.db.databaseName()])
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Sucess!'),
             self.tr(
                 'Success! {0} successfully imported and installed in {1}.'
             ).format(widgetType, settingName))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem importing {0}: {1}').format(
                 widgetType, ':'.join(e.args)))
     self.refresh()
Esempio n. 21
0
    def getDialog(self,
                  parent=None,
                  caption='',
                  acceptMode=QFileDialog.AcceptOpen,
                  fileMode=QFileDialog.ExistingFile,
                  filter='',
                  selectedFilter=None,
                  useEncoding=False):
        if useEncoding:
            dialog = QgsEncodingFileDialog(parent, caption, getLastUsedDir(),
                                           filter, getLastUsedEncoding())
        else:
            dialog = QFileDialog(parent, caption, getLastUsedDir(), filter)
        dialog.setFileMode(fileMode)
        dialog.setAcceptMode(acceptMode)

        if selectedFilter is not None:
            dialog.selectNameFilter(selectedFilter[0])

        if not dialog.exec_():
            if useEncoding:
                return ('', None)
            return ''

        # change the selected filter value
        if selectedFilter is not None:
            selectedFilter[0] = dialog.selectedNameFilter()

        # save the last used dir and return the selected files
        files = dialog.selectedFiles()
        if files != '':
            setLastUsedDir(files[0])

            if fileMode != QFileDialog.ExistingFiles:
                files = files[0]
                # append the extension if not already present
                if fileMode == QFileDialog.AnyFile:
                    firstExt = None
                    for ext in FileFilter.getFilterExtensions(
                            dialog.selectedNameFilter()):
                        if FileFilter.filenameMatchesFilterExt(files, ext):
                            firstExt = None
                            break

                        if firstExt is None:
                            firstExt = ext

                    if firstExt is not None:
                        if firstExt.startswith('*'):
                            files += firstExt[1:]

        if useEncoding:
            encoding = dialog.encoding()
            # encoding setted yet by QgsEncodingFileDialog
            #setLastUsedEncoding(encoding)
            return (files, encoding)

        return files
Esempio n. 22
0
    def openOutput(sender=None, startFolder=None):
        fd = QFileDialog()
        filter =  "OGC GeoPackage (*.gpkg);;ESRI Shape File (*.shp);;Comma separated value File (excel) (*.csv);;geojson (*.geojson);;GML File (*.gml);;MapInfo TAB (*.tab);;SpatiaLite (*.sqlite);;KML (google earth) (*.kml);;Any File (*.*)"
        fName = fd.getSaveFileName( sender, "open file", filter=filter, directory=startFolder)

        if fName:
            return fName[0]
        else:
            return None
Esempio n. 23
0
 def connectDatabaseWithGui(self):
     """
     Connects to database using user interface dialog.
     """
     fd = QFileDialog()
     filename = fd.getExistingDirectory(
         caption=self.tr('Select a Path to Shapefiles'))
     filename = filename[0] if isinstance(filename, tuple) else filename
     self.setDatabaseName(filename)
Esempio n. 24
0
    def spi_calc_get_comp_file(self):
        dlgx = QFileDialog()
        dlgx.setFileMode(QFileDialog.AnyFile)
        dlgx.setNameFilters(["CSV files (*.csv)"])
        #dlgx.setFilter("CSV files (*.csv)")

        if dlgx.exec_():
            filenames = dlgx.selectedFiles()
            self.ui.lineEdit_15.setText(str(filenames[0]))
Esempio n. 25
0
    def data_prep_get_input_ppt_file(self):
        dlgx = QFileDialog()
        dlgx.setFileMode(QFileDialog.AnyFile)
        dlgx.setNameFilters(["CSV files (*.csv)"])
        #dlgx.setFilter("CSV files (*.csv)")

        if dlgx.exec_():
            filenames = dlgx.selectedFiles()
            self.ui.lineEdit_10.setText(str(filenames[0]))
Esempio n. 26
0
 def search_gnss(self):
     self.dlg_files = QFileDialog()
     directory = QFileDialog.getOpenFileName(None, "Select a directory", "",
                                             "CSV (*.csv)")  #,
     QgsMessageLog.logMessage(str(directory))
     if not (directory == ""):
         self.ui.gnss_2.setText(directory[0])
         print("ok")
     else:
         print("")
Esempio n. 27
0
 def search_ref(self):
     self.dlg_files = QFileDialog()
     directory = QFileDialog.getOpenFileName(None, "Select a directory", "",
                                             "Shapefile (*.shp)")  #,
     QgsMessageLog.logMessage(str(directory))
     if not (directory == ""):
         self.ui.ref_2.setText(directory[0])
         print("ok")
     else:
         print("")
Esempio n. 28
0
 def connectDatabaseWithGui(self):
     '''
     Connects to database using user interface dialog
     '''
     fd = QFileDialog()
     filename = fd.getOpenFileName(
         caption=self.tr('Select a DSGTools Spatialite file'),
         filter=self.tr('Spatialite file databases (*.sqlite)'))
     filename = filename[0] if isinstance(filename, tuple) else filename
     self.db.setDatabaseName(filename)
Esempio n. 29
0
    def select_output_file(self):

        # Creates the dialog to select the output folder and updates the 'output path' text field

        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.Directory)
        dialog.exec()
        if (dialog.selectedFiles()):
            outputFolder = dialog.selectedFiles()[0]
            self.dlg.output_folder_lineEdit.setText(outputFolder)
    def uploadHeader(self):
        """Import header from ASCII or TXT file.

        This function open a QFileDialog() to select and open an ASC file.
        The beginning of this file (ie. the header) is parsed to get value and
        to fill corresponding widget parameter value.
        The goal is to automate the filling of the parameters to improve
        the user experience

        Example of file header:
        ```
        ncols 144
        nrows 138
        xllcorner 312487.6891250734
        yllcorner 2397321.4964859663
        cellsize 10.0
        NODATA_value -1
        ```
        """

        # Select the file with a QFileDialog()
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        #dlg.setFilter("ASC File (*.asc);; TXT File (*.txt);;All File (*.*)")
        dlg.setNameFilters(
            ["All File (*.*)", "ASC File (*.asc)", "TXT File (*.txt)"])
        dlg.selectNameFilter("All File (*.*)")
        filenames = ''
        if dlg.exec_():
            filenames = dlg.selectedFiles()
        if filenames != '':
            # Open the file and parse header data
            with open(str(filenames[0]), 'r') as infile:
                for line in infile:
                    values = line.strip().split(' ')
                    if values[0] == "ncols":
                        ChloeUtils.wrapperSetValue(self.wrappers["N_COLS"],
                                                   int(values[1]))
                    elif values[0] == "nrows":
                        ChloeUtils.wrapperSetValue(self.wrappers["N_ROWS"],
                                                   float(values[1]))
                    elif values[0] == "xllcorner":
                        ChloeUtils.wrapperSetValue(self.wrappers["XLL_CORNER"],
                                                   float(values[1]))
                    elif values[0] == "yllcorner":
                        ChloeUtils.wrapperSetValue(self.wrappers["YLL_CORNER"],
                                                   float(values[1]))
                    elif values[0] == "cellsize":
                        ChloeUtils.wrapperSetValue(self.wrappers["CELL_SIZE"],
                                                   float(values[1]))
                    elif values[0] == "NODATA_value":
                        ChloeUtils.wrapperSetValue(
                            self.wrappers["NODATA_VALUE"], int(values[1]))
                    else:
                        break