Esempio n. 1
0
    def showSelectionDialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = settings.value('/Processing/LastInputPath')
        else:
            path = ''

        if self.isFolder:
            folder = QFileDialog.getExistingDirectory(self,
                                                      self.tr('Select folder'), path)
            if folder:
                self.leText.setText(folder)
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(folder))
        else:
            filenames, selected_filter = QFileDialog.getOpenFileNames(self,
                                                                      self.tr('Select file'), path, '*.' + self.ext)
            if filenames:
                self.leText.setText(u';'.join(filenames))
                settings.setValue('/Processing/LastInputPath',
                                  os.path.dirname(filenames[0]))
Esempio n. 2
0
 def getExistingDirectory(self, parent=None, caption='', useEncoding=False):
     if useEncoding:
         return self.getDialog(parent, caption, QFileDialog.AcceptOpen, QFileDialog.DirectoryOnly, '', None, useEncoding)
     res = QFileDialog.getExistingDirectory(parent, caption, getLastUsedDir(), QFileDialog.ShowDirsOnly)
     if res:
         setLastUsedDir(res)
     return res
Esempio n. 3
0
 def onOpenDialog(self):
     title = u"Output Pfad auswählen"
     directory = QFileDialog.getExistingDirectory(self, title,
         self.options['outputPath'])
     
     self.tool.updateCommonPathList(directory)
     self.fillInDropDown(self.tool.commonPaths)
 def select_directory(self):
     plugin_path = QFileDialog.getExistingDirectory(
         self, 'Select the Directory for your Plugin', self.last_path)
     self.output_directory.setText(plugin_path)
     full_output = os.path.join(plugin_path, self.module_name.text().lower())
     self.lbl_full_output_path.setText(os.path.join(plugin_path, self.module_name.text().lower()))
     self.show_output_info(full_output)
    def showFileDialog(self, seldir):
        settings = QgsSettings()
        text = str(self.text.text())
        if os.path.isdir(text):
            path = text
        elif not seldir and os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        elif settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        if not seldir:
            ret, selected_filter = QFileDialog.getOpenFileNames(
                self, self.tr('Select Files'), path, getFileFilter(self.param)
            )
        else:
            ret = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'), path)

        if ret:
            if seldir:
                settings.setValue('/Processing/LastInputPath', ret)

                files = []
                for pp in Path(ret).rglob("*"):
                    if not pp.is_file():
                        continue

                    p = pp.as_posix()

                    if ((isinstance(self.param, QgsProcessingParameterRasterLayer)
                         or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeRaster)) and
                            not QgsRasterLayer.isValidRasterFileName(p)):
                        continue

                    files.append(p)

                if not files:
                    return

            else:
                files = list(ret)
                settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0])))

            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
                self.textEditingFinished()
            else:
                if isinstance(self.param, QgsProcessingParameterMultipleLayers):
                    self.text.setText(';'.join(str(f) for f in files))
                else:
                    rowdif = len(files) - (self._table().rowCount() - self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, f in enumerate(files):
                        self._table().cellWidget(i + self.row,
                                                 self.col).setValue(f)
Esempio n. 6
0
    def filer(self):
        if self.comboBox.currentText()=='ESRI shape file':
            a = 'Save as ESRI shape file'
            sf = QFileDialog.getExistingDirectory(self, a, QDir.homePath())
            # b = 'ESRI shape files (*.shp)'
        elif self.comboBox.currentText()=='Comma separated value (CSV)':
            a = 'Save as comma separated value (CSV)'
            sf = QFileDialog.getExistingDirectory(self, a, QDir.homePath())
            # b = 'CSV files (*.csv)'
        elif self.comboBox.currentText()=='SQLite database':
            a = 'SQLite database'
            sf = QFileDialog.getOpenFileName(self, a, QDir.homePath())
        elif self.comboBox.currentText()=='Copy complete database':
            a = 'Copy complete database'
            sf = QFileDialog.getSaveFileName(self, a, QDir.homePath())

        self.lineEdit.setText(sf)
Esempio n. 7
0
    def on_directory_button_clicked(self):
        """Show a dialog to choose directory.

        .. versionadded: 3.3
        """
        # noinspection PyCallByClass,PyTypeChecker
        self.output_directory.setText(QFileDialog.getExistingDirectory(
            self, self.tr('Select download directory')))
Esempio n. 8
0
 def open_report_template_path(self):
     """Open File dialog to choose the report template path."""
     # noinspection PyCallByClass,PyTypeChecker
     directory_name = QFileDialog.getExistingDirectory(
         self,
         self.tr('Templates directory'),
         self.leReportTemplatePath.text(),
         QFileDialog.ShowDirsOnly)
     if directory_name:
         self.leReportTemplatePath.setText(directory_name)
Esempio n. 9
0
 def open_user_directory_path(self):
     """Open File dialog to choose the user directory path."""
     # noinspection PyCallByClass,PyTypeChecker
     directory_name = QFileDialog.getExistingDirectory(
         self,
         self.tr('Results directory'),
         self.leUserDirectoryPath.text(),
         QFileDialog.ShowDirsOnly)
     if directory_name:
         self.leUserDirectoryPath.setText(directory_name)
Esempio n. 10
0
    def on_openMsgButton_clicked(self):
        """opens directory search dialog and sets my attribute __dir"""
        l_path = self._start_find_path()

        #l_request = "Select directory which hold result request Dig ALert"
        l_request = self.tr("Selecteer folder met KLIC bericht")
        l_dir_path = QFileDialog.getExistingDirectory(self, l_request, l_path)
        if l_dir_path: # evaluates to true when it contains anything
            self.__dir = str(l_dir_path)
            QSettings().setValue("b4udignl/dir_last_used", str(l_dir_path))
            self._loadMsg()
Esempio n. 11
0
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath", QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'),
                                                   lastDir, QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)
Esempio n. 12
0
 def on_optionMsgDirButton_clicked(self):
     """
     select directory which will be used to start searching
     KLIC messages from when using openMsgButton
     """
     l_path = self.__settings["b4udignl/dir_preferred"]
     l_request = self.tr("Selecteer standaard folder met KLIC berichten")
     l_dir_path = QFileDialog.getExistingDirectory(self, l_request, l_path)
     if l_dir_path: # if l_dir_path is not empty this evaluates to true..
         self.__settings["b4udignl/dir_preferred"] = str(l_dir_path)
         QSettings().setValue("b4udignl/dir_preferred", l_dir_path)
         self.ui.textEditDirPreffered.setText(l_dir_path)
Esempio n. 13
0
    def selectDirectory(self):

        settings = QgsSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            lastDir = str(settings.value('/Processing/LastBatchOutputPath'))
        else:
            lastDir = ''

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Output Directory'), lastDir, QFileDialog.ShowDirsOnly)

        if dirName:
            self.table.cellWidget(self.row, self.col).setValue(dirName)
            settings.setValue('/Processing/LastBatchOutputPath', dirName)
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath", QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self, self.tr('Select Directory'),
                                                   lastDir, QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)
            self.use_temporary = False
            self.skipOutputChanged.emit(False)
            self.destinationChanged.emit()
Esempio n. 15
0
    def selectDirectory(self):
        lastDir = self.leText.text()
        settings = QgsSettings()
        if not lastDir:
            lastDir = settings.value("/Processing/LastOutputPath",
                                     QDir.homePath())

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Select Directory'),
                                                   lastDir,
                                                   QFileDialog.ShowDirsOnly)
        if dirName:
            self.leText.setText(QDir.toNativeSeparators(dirName))
            settings.setValue('/Processing/LastOutputPath', dirName)

        self.skipOutputChanged.emit(False)
Esempio n. 16
0
    def select(self):
        lastDir = ''
        if not self.selectFile:
            selectedPath = QFileDialog.getExistingDirectory(None,
                                                            self.tr('Select directory'), lastDir,
                                                            QFileDialog.ShowDirsOnly)
        else:
            selectedPath, selected_filter = QFileDialog.getOpenFileName(None,
                                                                        self.tr('Select file'), lastDir, self.tr('All files (*.*)')
                                                                        )

        if not selectedPath:
            return

        self.lineEdit.setText(selectedPath)
        self.canFocusOut = True
Esempio n. 17
0
    def selectDirectory(self):

        settings = QgsSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            lastDir = str(settings.value('/Processing/LastBatchOutputPath'))
        else:
            lastDir = ''

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Output Directory'),
                                                   lastDir,
                                                   QFileDialog.ShowDirsOnly)

        if dirName:
            self.table.cellWidget(self.row, self.col).setValue(dirName)
            settings.setValue('/Processing/LastBatchOutputPath', dirName)
Esempio n. 18
0
    def select(self):
        lastDir = ''
        if not self.selectFile:
            selectedPath = QFileDialog.getExistingDirectory(
                None, self.tr('Select directory'), lastDir,
                QFileDialog.ShowDirsOnly)
        else:
            selectedPath, selected_filter = QFileDialog.getOpenFileName(
                None, self.tr('Select file'), lastDir,
                self.tr('All files (*.*)'))

        if not selectedPath:
            return

        self.lineEdit.setText(selectedPath)
        self.canFocusOut = True
Esempio n. 19
0
    def choose_directory(self, line_edit, title):
        """ Show a directory selection dialog.
        This function will show the dialog then set line_edit widget
        text with output from the dialog.

        :param line_edit: Widget whose text should be updated.
        :type line_edit: QLineEdit

        :param title: title of dialog
        :type title: str, QString
        """
        path = line_edit.text()
        # noinspection PyCallByClass,PyTypeChecker
        new_path = QFileDialog.getExistingDirectory(
            self, title, path, QFileDialog.ShowDirsOnly)
        if new_path is not None and os.path.exists(new_path):
            line_edit.setText(new_path)
Esempio n. 20
0
    def addDirectory(self):
        settings = QSettings()
        if settings.contains("/Processing/lastDirectory"):
            path = settings.value("/Processing/lastDirectory")
        else:
            path = ""

        folder = QFileDialog.getExistingDirectory(self, self.tr("Select directory"), path, QFileDialog.ShowDirsOnly)

        if folder == "":
            return

        model = self.lstLayers.model()
        item = QStandardItem(folder)
        model.appendRow(item)

        settings.setValue("/Processing/lastDirectory", os.path.dirname(folder))
    def storyDescriptionLinkClicked(self, url):
        url = url.toString()
        if url == "search":
            dlg = SearchDialog()
            dlg.exec_()
            if dlg.mapstory is not None:
                story = Story.storyFromNumberId(dlg.mapstory)
                if story is None:
                    QMessageBox.warning(iface.mainWindow(), "MapStory", "Cannot get MapStory data.\nCheck that the provided ID is correct.")
                else:
                    self.updateCurrentStory(story)
        elif url == "download":
            outDir = QFileDialog.getExistingDirectory(self,
                                                  self.tr("Select output directory"),
                                                  "."
                                                 )
            if not outDir:
                return

            QDir().mkpath(outDir)

            settings = QSettings()
            systemEncoding = settings.value('/UI/encoding', 'System')
            startProgressBar(len(self.story.storyLayers()), "Download layers for off-line use:")
            for i, layer in enumerate(self.story.storyLayers()):
                filename = os.path.join(outDir, layer.name() + ".shp")
                uri = "%s?srsname=%s&typename=geonode:%s&version=1.0.0&request=GetFeature&service=WFS" % (layer.wfsUrl(), layer.crs(), layer.name())
                qgslayer = QgsVectorLayer(uri, layer.name(), "WFS")
                writer = QgsVectorFileWriter(filename, systemEncoding,
                                             qgslayer.pendingFields(),
                                             qgslayer.dataProvider().geometryType(),
                                             qgslayer.crs())
                for feat in qgslayer.getFeatures():
                    writer.addFeature(feat)
                del writer

                fieldname = self._getTimeField(qgslayer)

                if fieldname is not None:
                    filename = os.path.join(outDir, layer.name() + ".timefield")
                    with open(filename, "w") as f:
                        f.write(fieldname)
                setProgress(i+1)

            closeProgressBar()
            iface.messageBar().pushMessage("MapStory", "Layers have been correctly saved as QGIS project.", level=QgsMessageBar.INFO, duration=3)
Esempio n. 22
0
def get_folder_dialog(dialog, widget):
    """ Get folder dialog """

    # Check if selected folder exists. Set default value if necessary
    folder_path = qt_tools.getWidgetText(dialog, widget)
    if folder_path is None or folder_path == 'null' or not os.path.exists(folder_path):
        folder_path = os.path.expanduser("~")

    # Open dialog to select folder
    os.chdir(folder_path)
    file_dialog = QFileDialog()
    file_dialog.setFileMode(QFileDialog.Directory)
    message = "Select folder"
    folder_path = file_dialog.getExistingDirectory(
        parent=None, caption=global_vars.controller.tr(message), directory=folder_path)
    if folder_path:
        qt_tools.setWidgetText(dialog, widget, str(folder_path))
def selectFolder(line_edit_widget, title, parent, setting_property=None):
    folder = None
    if setting_property:  # Get from settings
        from asistente_ladm_col.app_interface import AppInterface  # Here to avoid circular dependency
        app = AppInterface()
        folder = getattr(app.settings, setting_property,
                         None)  # None if key not found
    if not folder:
        folder = line_edit_widget.text()

    foldername = QFileDialog.getExistingDirectory(parent, title, folder)
    if foldername:
        line_edit_widget.setText(foldername)

        if setting_property and getattr(app.settings, setting_property,
                                        -1) != -1:  # Save to settings
            setattr(app.settings, setting_property, foldername)
Esempio n. 24
0
    def showDirectorySelectionDialog(self):
        settings = QgsSettings()
        if settings.contains('/Processing/LastInputPath'):
            path = str(settings.value('/Processing/LastInputPath'))
        else:
            path = QDir.homePath()

        folder = QFileDialog.getExistingDirectory(self,
                                                  self.tr('Select Directory'),
                                                  path)
        if not folder:
            return

        settings.setValue('/Processing/LastInputPath', folder)

        files = []
        for pp in Path(folder).rglob("*"):
            if not pp.is_file():
                continue

            p = pp.as_posix()

            if isinstance(self.parameterDefinition,
                          QgsProcessingParameterRasterLayer) or (
                              isinstance(self.parameterDefinition,
                                         QgsProcessingParameterMultipleLayers)
                              and self.parameterDefinition.layerType()
                              == QgsProcessing.TypeRaster):
                if not QgsRasterLayer.isValidRasterFileName(p):
                    continue

            files.append(p)

        if not files:
            return

        context = dataobjects.createContext()

        first_row = self.panel.batchRowCount(
        ) if self.panel.batchRowCount() > 1 else 0
        self.panel.addRow(len(files))
        self.panel.tblParameters.setUpdatesEnabled(False)
        for row, file in enumerate(files):
            self.setRowValue(first_row + row, file, context)
        self.panel.tblParameters.setUpdatesEnabled(True)
Esempio n. 25
0
 def toolButtonImport(self):
     self.directoryPhotos = QFileDialog.getExistingDirectory(
         None, 'Select a folder:',
         os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop'),
         QFileDialog.ShowDirsOnly)
     self.selected_folder = self.directoryPhotos
     p = '/'
     if '/' in self.directoryPhotos:
         self.selected_folder = self.directoryPhotos.split('/')[-1]
         p = '/'
     if '\\' in self.directoryPhotos:
         self.selected_folder = self.directoryPhotos.split('\\')[-1]
         p = '\\'
     if '//' in self.directoryPhotos:
         self.selected_folder = self.directoryPhotos.split('//')[-1]
         p = '//'
     self.selected_folder = './' + self.selected_folder + p
     self.dlg.imp.setText(self.directoryPhotos)
Esempio n. 26
0
 def selectDatasource(self):
     """
     Opens dialog for file/directory selection.
     """
     # model of implementation for reimplementation
     fd = QFileDialog()
     fd.setFileMode(QFileDialog.Directory)
     fd.setOption(QFileDialog.ShowDirsOnly, True)
     directory = fd.getExistingDirectory(
         caption=self.selectionWidget.caption)
     if directory:
         if len(directory) > 4:
             # datasource connection name for a shape 'database' is its parent folder
             directory = directory if directory[-4:].lower(
             ) != '.shp' else directory[:-4]
         # set only directories as line text
         self.selectionWidget.dsLineEdit.setText(directory)
     self.selectionWidget.loadDatabase(currentText=directory)
Esempio n. 27
0
    def selezionaCartellaScarico(self):
        """
            # Slot for exposing the same-name function to Javascript. #
            Activate the chooser for the download folder name.
        """
        # If already defined, prompt the user for the change
        if self.download_folder_path != "":
            reply = QMessageBox.question(
                None, 'Cartella di scarico', 'Cartella di scarico attuale: ' +
                self.download_folder_path + '\nSi desidera modificarla?',
                QMessageBox.Yes, QMessageBox.No)
            if reply == QMessageBox.No:
                return

        # Prompt the file chooser
        self.download_folder_path = QFileDialog.getExistingDirectory(None)
        self.set_download_folder()
        self.save_configuration()
Esempio n. 28
0
    def onDownloadTemplate(self, templateName):
        title = self.tr('Vorlage speichern')
        path = self.confHandler.getCurrentPath()
        folder = QFileDialog.getExistingDirectory(self, title, path,
                                                  QFileDialog.ShowDirsOnly)
        if folder:
            templateUrl, filename = self.confHandler.getTemplateUrl(
                templateName)
            savepath = os.path.join(folder, filename)
            filefetcher = FileFetcher(templateUrl, savepath)

            if filefetcher.success:
                msg = self.tr('Vorlage erfolgreich heruntergeladen.')
            else:
                msg = self.tr('Download nicht erfolgreich. Link fuer manuellen Download: _templateUrl_')\
                    .replace('_templateUrl_', templateUrl)
            QMessageBox.information(self, self.tr('Download Vorlage'), msg,
                                    QMessageBox.Ok)
Esempio n. 29
0
    def do_generate_report_action(self, count_id):
        QgsMessageLog.logMessage(
            '{} - Generate report action started'.format(datetime.now()),
            'Comptages', Qgis.Info)

        count = models.Count.objects.get(id=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
        if not models.CountDetail.objects.filter(id_count=count).exists():
            push_info(
                "Installation {}: Il n'y a pas de données à traiter pour "
                "le comptage {}".format(count.id_installation.name, count.id))
            QgsMessageLog.logMessage(
                '{} - Generate report action ended: No data for count {}'.
                format(datetime.now(), count.id), 'Comptages', Qgis.Info)
            return

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

        if not file_path:
            QgsMessageLog.logMessage(
                '{} - Generate report action ended: No file_path given'.format(
                    datetime.now()), 'Comptages', Qgis.Info)
            return
        QgsMessageLog.logMessage(
            '{} - Generate report action can really begin now for count {} with file_path: {}'
            .format(datetime.now(), count.id,
                    file_path), 'Comptages', Qgis.Info)

        self.tm.allTasksFinished.connect(
            partial(self.all_tasks_finished, 'report'))
        self.tm.addTask(
            report_task.ReportTask(
                file_path=file_path,
                count=count,
            ))
Esempio n. 30
0
    def OnBrowseOutput(self):
        """Browse for output directory. Set values and enables the Convert button."""
        sender = 'ColorToAlpha-{}-lastUserOutputFilePath'.format(
            self.sender().objectName())
        # load lastly used directory path
        lastPath = self._settings.value(sender, self.textInput.toPlainText())

        filePath = QFileDialog.getExistingDirectory(
            self, self.tr('Output Directory'), lastPath)
        if not filePath:
            # action canceled
            return

        filePath = os.path.normpath(filePath)
        self.textOutput.setText(filePath)
        self.generateButton.setEnabled(True)

        # remember directory path
        self._settings.setValue(sender, os.path.dirname(filePath))
Esempio n. 31
0
 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", newline='') as f:
         f.write(file_content)
     self.gem_api.common.info('File downloaded as: %s' % file_fullpath)
Esempio n. 32
0
 def on_batchImportPushButton_clicked(self):
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder with permissions: '))
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Error! Select a input folder!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.permissionManager.batchImportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(self, self.tr('Success!'),
                             self.tr('Permissions successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(
             self, self.tr('Warning!'),
             self.tr('Error! Problem importing permission: ') +
             ':'.join(e.args))
Esempio n. 33
0
    def browse_path(self, line_edit: QLineEdit):
        '''
        open a dialog for user input of a path and write it into the given edit

        Parameters
        ----------
        line_edit : QLineEdit
            the line edit to set the user input to
        '''
        path = str(
            QFileDialog.getExistingDirectory(
                self,
                'Verzeichnis wählen',
                line_edit.text()
            )
        )
        if not path:
            return
        line_edit.setText(path)
Esempio n. 34
0
    def addDirectory(self):
        settings = QSettings()
        if settings.contains('/Processing/lastDirectory'):
            path = settings.value('/Processing/lastDirectory')
        else:
            path = ''

        folder = QFileDialog.getExistingDirectory(self,
                                                  self.tr('Select directory'),
                                                  path,
                                                  QFileDialog.ShowDirsOnly)

        if folder == '':
            return

        model = self.lstLayers.model()
        item = QStandardItem(folder)
        model.appendRow(item)

        settings.setValue('/Processing/lastDirectory', os.path.dirname(folder))
    def browseButton_clicked(self, browseButton_id=1):
        """
        :param browseButton_id: ID of clicked browse button.
        :return:
        """
        sender = '{}-lastUsedDir'.format(self.sender().objectName())
        lastUsedDir = self.settings.value(sender, '')

        if self.__source_for_data == 'file':
            ext = '*.vfk'
            if self.__gdal_version >= 2020000:
                ext += ' *.db'
            loaded_file, __ = QFileDialog.getOpenFileName(
                self, u'Načti soubor VFK', lastUsedDir,
                u'Soubory podporované ovladačem VFK GDAL ({})'.format(ext))

            if not loaded_file:
                return

            self.__fileName.append(loaded_file)
            if browseButton_id == 1:
                self.vfkFileLineEdit.setText(self.__fileName[0])
            else:
                self.__vfkLineEdits['vfkL1ineEdit_{}'.format(
                    len(self.__vfkLineEdits))].setText(
                        self.__fileName[browseButton_id - 1])
            self.settings.setValue(sender, os.path.dirname(loaded_file))
        elif self.__source_for_data == 'directory':
            loaded_file = QFileDialog.getExistingDirectory(
                self, u"Vyberte adresář s daty VFK", lastUsedDir)
            if not loaded_file:
                return

            self.__fileName = []
            self.__fileName.append(loaded_file)
            self.vfkFileLineEdit.setText(self.__fileName[0])
            self.settings.setValue(sender, loaded_file)
        else:
            iface.messageBar().pushWarning(u'ERROR', u'Not valid data source')

        self.loadVfkButton.setEnabled(True)
Esempio n. 36
0
    def __import_data(self):
        assert(self.project)
        dir_ = QFileDialog.getExistingDirectory(
            None,
            u"Data directory",
            QgsProject.instance().readEntry("albion", "last_dir", "")[0],
            QFileDialog.ShowDirsOnly | QFileDialog.DontUseNativeDialog
        )
        if not dir_:
            return
        QgsProject.instance().writeEntry("albion", "last_dir", dir_),

        progressMessageBar = self.__iface.messageBar().createMessage(
            "Loading {}...".format(dir_)
        )
        progress = QProgressBar()
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.__iface.messageBar().pushWidget(progressMessageBar)

        self.project.import_data(dir_, ProgressBar(progress))
        #self.project.triangulate()
        self.project.create_section_view_0_90(4)

        self.__iface.messageBar().clearWidgets()

        collar = QgsProject.instance().mapLayersByName("collar")
        if len(collar):
            collar[0].reload()
            collar[0].updateExtents()
            self.__iface.setActiveLayer(collar[0])
            QApplication.instance().processEvents()
            while self.__iface.mapCanvas().isDrawing():
                QApplication.instance().processEvents()
            self.__iface.zoomToActiveLayer()

        self.__iface.actionSaveProject().trigger()

        self.__viewer3d.widget().resetScene(self.project)
        self.__current_section.clear()
        self.__current_section.addItems(self.project.sections())
Esempio n. 37
0
    def __select_output(self):
        if self.rbOutputZip.isChecked():
            file_directory = QFileInfo(
                self.settings.value('outputToZip_Path', '.')).absolutePath()
            outPath, outFilter = QFileDialog.getSaveFileName(
                self, self.tr('Save to file'), file_directory,
                ';;'.join(list(self.FORMATS.keys())),
                list(self.FORMATS.keys())[list(
                    self.FORMATS.values()).index('.zip')])
            if not outPath:
                return
            if not outPath.lower().endswith(self.FORMATS[outFilter]):
                outPath += self.FORMATS[outFilter]
            self.leZipFileName.setText(outPath)
            self.settings.setValue('outputToZip_Path',
                                   QFileInfo(outPath).absoluteFilePath())

        elif self.rbOutputDir.isChecked():
            dir_directory = QFileInfo(
                self.settings.value('outputToDir_Path', '.')).absolutePath()
            outPath = QFileDialog.getExistingDirectory(
                self, self.tr('Save to directory'), dir_directory,
                QFileDialog.ShowDirsOnly)
            if not outPath:
                return
            self.leDirectoryName.setText(outPath)
            self.settings.setValue('outputToDir_Path',
                                   QFileInfo(outPath).absoluteFilePath())

        elif self.rbOutputNGM.isChecked():
            zip_directory = QFileInfo(
                self.settings.value('outputToNGM_Path', '.')).absolutePath()
            outPath, outFilter = QFileDialog.getSaveFileName(
                self, self.tr('Save to file'), zip_directory, 'ngrc')
            if not outPath:
                return
            if not outPath.lower().endswith('ngrc'):
                outPath += '.ngrc'
            self.leTilesFroNGM.setText(outPath)
            self.settings.setValue('outputToNGM_Path',
                                   QFileInfo(outPath).absoluteFilePath())
Esempio n. 38
0
    def OnBrowseInput(self):
        """Browse for input directory. Set values and enables the output directory button."""
        sender = 'ColorToAlpha-{}-lastUserFilePath'.format(
            self.sender().objectName())
        # load lastly used directory path
        lastPath = self._settings.value(sender, '')

        directoryPath = QFileDialog.getExistingDirectory(
            self, self.tr("Directory with GeoTIFF files"), lastPath)

        if not directoryPath:
            # action canceled
            return

        directoryPath = os.path.normpath(directoryPath)
        self.textInput.setText(directoryPath)

        self.outputButton.setEnabled(True)

        # remember directory path
        self._settings.setValue(sender, os.path.dirname(directoryPath))
Esempio n. 39
0
 def newProject(self):
     """Call QGIS actions to create and name a new project."""
     settings = QSettings()
     if settings.contains('/QSWATPlus/LastInputPath'):
         path = settings.value('/QSWATPlus/LastInputPath')
     else:
         path = ''
     title = 'Select parent directory'
     parentDir = QFileDialog.getExistingDirectory(None, title, path)
     if parentDir is not None and os.path.isdir(parentDir):
         projName, ok = QInputDialog.getText(None, 'Project name', 'Please enter the project name, starting with a letter:')
         if not ok:
             return
         if not projName[0].isalpha():
             QSWATUtils.error('Project name must start with a letter', False)
             return
         projDir = QSWATUtils.join(parentDir, projName)
         if os.path.exists(projDir):
             response = QSWATUtils.question('Project directory {0} already exists.  Do you wish to delete it?'.format(projDir), False, False)
             if response != QMessageBox.Yes:
                 return
             shutil.rmtree(projDir, True)
         try: 
             os.mkdir(projDir)
         except Exception:
             QSWATUtils.exceptionError('Failed to create project directory {0}'.format(projDir), False)
             return
         self._iface.newProject()
         projFile = QSWATUtils.join(projDir, projName + '.qgs')
         proj = QgsProject.instance()
         proj.setFileName(projFile)
         QSWATUtils.loginfo('Project file is {0}'.format(projFile))
         self._iface.actionSaveProject().trigger()
         # allow time for project to be created
         time.sleep(2)
         self.initButtons()
         settings.setValue('/QSWATPlus/LastInputPath', str(projDir))
         self._odlg.raise_()
         self.setupProject(proj, False)
         self._gv.writeProjectConfig(0, 0)
Esempio n. 40
0
    def download(self):
        parent_dir = QFileDialog.getExistingDirectory(None, "Open Directory",
                                                      "",
                                                      QFileDialog.ShowDirsOnly)
        if not parent_dir:
            return

        target_dir = os.path.abspath(
            os.path.join(parent_dir, self.project['name']))
        settings = QSettings()

        QApplication.setOverrideCursor(Qt.WaitCursor)
        try:
            self.mc.download_project(self.project_name, target_dir)
            settings.setValue(
                'Mergin/localProjects/{}/path'.format(self.project_name),
                target_dir)
            self.path = target_dir
            self.setIcon(QIcon(os.path.join(icon_path, "folder-solid.svg")))
            QApplication.restoreOverrideCursor()

            msg = "Your project {} has been successfully downloaded. " \
                  "Do you want to open project file?".format(self.project_name)
            btn_reply = QMessageBox.question(None, 'Project download', msg,
                                             QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.Yes)
            if btn_reply == QMessageBox.Yes:
                self.open_project()
        except (URLError, ValueError):
            QApplication.restoreOverrideCursor()
            msg = "Failed to download your project {}.\n" \
                  "Please make sure your Mergin settings are correct".format(self.project_name)
            QMessageBox.critical(None, 'Project download', msg,
                                 QMessageBox.Close)
        except Exception as e:
            QApplication.restoreOverrideCursor()
            msg = "Failed to download your project {}.\n" \
                  "{}".format(self.project_name, str(e))
            QMessageBox.critical(None, 'Project download', msg,
                                 QMessageBox.Close)
    def show_selection_dialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        else:
            path = PluginSettings.last_icon_path()

        if self.is_folder:
            folder = QFileDialog.getExistingDirectory(self, self.dialog_title,
                                                      path)
            if folder:
                self.leText.setText(folder)
                PluginSettings.set_last_icon_path(os.path.dirname(folder))
        else:
            filename = getOpenFileName(self, self.dialog_title, path, self.ext)
            if filename:
                self.leText.setText(filename)
                PluginSettings.set_last_icon_path(os.path.dirname(filename))
Esempio n. 42
0
    def saveAsHtmlGeojson(self):
        '''
        Open a directory dialog and le the user choose the location where to
        write the html and the geojson file.
        '''

        export_name = re.sub(r'\s+', '-', self.vlayer.name())

        dir_path = QFileDialog.getExistingDirectory(
            None, self.tr("Select Directory"))
        html_name = os.path.join(dir_path, '{}.html'.format(export_name))
        # remove all spaces from name
        gjson_name = os.path.join(dir_path, '{}.geojson'.format(export_name))

        output = QgsVectorFileWriter.writeAsVectorFormat(layer=self.vlayer,
                                                         fileEncoding='UTF-8',
                                                         fileName=gjson_name,
                                                         driverName='GeoJSON')

        # change the raw geojson string with the relative file path
        self.opts["elevationControl"]["data"] = os.path.basename(gjson_name)

        geojson_opts = json.dumps(self.opts)
        self.lines[self.dataidx] = '  var opts = {} ;'.format(geojson_opts)

        # write the final file
        try:
            with open(html_name, 'w') as fog:
                fog.writelines(self.lines)
            self.bar.pushMessage(self.tr("Elevation file succesfully saved"),
                                 "",
                                 level=Qgis.Info,
                                 duration=3)
        except:
            self.bar.pushMessage(self.tr("Something went wrong. Try again."),
                                 "",
                                 level=Qgis.Critical,
                                 duration=3)
Esempio n. 43
0
 def on_batchImportPushButton_clicked(self):
     """
     Imports all config files from a folder into dsgtools_admindb. It only works for a single type of config per time.
     """
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder with json files: '))
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a input folder!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchImportSettings(folder)
         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))
Esempio n. 44
0
    def addDirectory(self):
        settings = QgsSettings()
        path = str(settings.value('/Processing/LastInputPath'))

        ret = QFileDialog.getExistingDirectory(self, self.tr('Select File(s)'), path)
        if ret:
            exts = []

            if self.datatype == QgsProcessing.TypeVector:
                exts = QgsVectorFileWriter.supportedFormatExtensions()
            elif self.datatype == QgsProcessing.TypeRaster:
                for t in QgsProviderRegistry.instance().fileRasterFilters().split(';;')[1:]:
                    for e in t[t.index('(') + 1:-1].split(' '):
                        if e != "*.*" and e.startswith("*."):
                            exts.append(e[2:])

            files = []
            for pp in Path(ret).rglob("*"):
                if not pp.is_file():
                    continue

                if exts and pp.suffix[1:] not in exts:
                    continue

                p = pp.as_posix()

                files.append(p)

            settings.setValue('/Processing/LastInputPath', ret)

            for filename in files:
                item = QStandardItem(filename)
                item.setData(filename, Qt.UserRole)
                item.setCheckState(Qt.Checked)
                item.setCheckable(True)
                item.setDropEnabled(False)
                self.model.appendRow(item)
Esempio n. 45
0
 def on_batchExportPushButton_clicked(self):
     """
     Exports all configs from dsgtools_admindb.
     """
     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
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchExportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.widgetName + self.tr(' successfully exported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem exporting ') + self.widgetName + ': ' +
             ':'.join(e.args))
Esempio n. 46
0
 def on_exportPushButton_clicked(self):
     """
     Export selected properties.
     """
     exportPropertyList = self.selectConfig()
     if exportPropertyList is None:
         # user cancelled
         return
     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.widgetName + self.tr(' successfully exported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem exporting ') + self.widgetName + ': ' +
             ':'.join(e.args))
Esempio n. 47
0
def get_new_qgis_project_filepath(project_name=None):
    """
    Get path for a new QGIS project. If name is not None, only ask for a directory.
    :name: filename of new project
    :return: string with file path, or None on cancellation
    """
    settings = QSettings()
    last_dir = settings.value("Mergin/lastUsedDownloadDir",
                              str(pathlib.Path.home()))
    if project_name is not None:
        dest_dir = QFileDialog.getExistingDirectory(None,
                                                    "Destination directory",
                                                    last_dir,
                                                    QFileDialog.ShowDirsOnly)
        project_file = os.path.abspath(os.path.join(dest_dir, project_name))
    else:
        project_file, filters = QFileDialog.getSaveFileName(
            None, "Save QGIS project", "", "QGIS projects (*.qgz *.qgs)")
    if project_file:
        if not (project_file.endswith(".qgs")
                or project_file.endswith(".qgz")):
            project_file += ".qgz"
        return project_file
    return None
Esempio n. 48
0
    def browseDir(self):
        """Open the browser so the user selects the output directory."""

        settings = QSettings()
        if self.dlg.formatBox.currentIndex() == 1 : # if extension is pdf
            dir = settings.value('/UI/lastSaveAsPdfFile')
        elif self.dlg.formatBox.currentIndex() == 3 : # if extension is svg
            dir = settings.value('/UI/lastSaveAsSvgFile')
        else:
            dir = settings.value('/UI/lastSaveAsImageDir')

        folderDialog = QFileDialog.getExistingDirectory(
            None,
            '',
            dir,
            QFileDialog.ShowDirsOnly,
            # QFileDialog.DontResolveSymlinks
            )

        #Do not alter potential folder path if the dialog was canceled
        if folderDialog == '':
            self.dlg.path.setText(self.dlg.path.text())
        else:
            self.dlg.path.setText(folderDialog)
Esempio n. 49
0
 def selectDirectory(self):
     lastDir = ''
     dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'),
                                                lastDir, QFileDialog.ShowDirsOnly)
     self.leText.setText(dirName)
Esempio n. 50
0
 def browseUMNPath(self):
     path = self.leUMNPath.text()
     path = QFileDialog.getExistingDirectory(self, u"UMN-Pfad wählen", path)
     if path != "":
         self.leUMNPath.setText(path)
def askForFolder(parent, name="HeatmapPath"):
    path = getSetting(LAST_PATH, name)
    folder =  QFileDialog.getExistingDirectory(parent, "Select folder to store chart", path)
    if folder:
        setSetting(LAST_PATH, name, folder)
    return folder
 def selectAnimationFolder(self):
     prev_directory = TimeManagerProjectHandler.plugin_setting(conf.LAST_ANIMATION_PATH_TAG)
     if prev_directory:
         self.animationDialog.lineEdit.setText(QFileDialog.getExistingDirectory(directory=prev_directory))
     else:
         self.animationDialog.lineEdit.setText(QFileDialog.getExistingDirectory())
Esempio n. 53
0
    def loadOutDir(self):
        #newname = QFileDialog.getExistingDirectory(None, "Output Maps Directory", self.dlg.ui.leOutDir.displayText())
        newname = QFileDialog.getExistingDirectory(None, "Output Maps Directory")

        if newname != None:
            self.dlg.ui.leOutDir.setText(newname)
 def setDir(self):
     dirpath = QFileDialog.getExistingDirectory()
     if dirpath == None: return
     self.ui.startDirTxt.setText(dirpath)
 def browseForTemplateRoot(self):
     startingDir = str(self.settings.value("SelectorTools/TemplateSelector/templateRoot", os.path.expanduser("~"), type=str))
     d = str(QFileDialog.getExistingDirectory(None, 'Select Root of Template Folder Structure', startingDir))
     if d != os.sep and d.lower() != 'c:\\' and d != '':
         self.ui.templateRootLineEdit.setText(d)
 def browseForProjectRoot(self):
     startingDir = str(self.settings.value("SelectorTools/ProjectSelector/projectRoot", os.path.expanduser("~"), type=str))
     d = str(QFileDialog.getExistingDirectory(None, 'Select Projects Folder', startingDir))
     if d != os.sep and d.lower() != 'c:\\' and d != '':
         self.ui.projectsFolderLineEdit.setText(d)
Esempio n. 57
0
 def selectFolder(self):
     folder = QFileDialog.getExistingDirectory(self, "Select folder")
     if folder:
         self.folderBox.setText(folder)
 def setDirectory(self):
     folder = QFileDialog.getExistingDirectory(self, "Select Directory")
     self.folderEdit.setText(folder)