コード例 #1
0
    def saveToSpatialite(self):
        fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile')

        settings = QSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        encoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(
            self, self.tr('Save Spatialite'), path, fileFilter, encoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setConfirmOverwrite(False)

        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = unicode(fileDialog.encoding())
            self.output.encoding = encoding
            fileName = unicode(files[0])
            selectedFileFilter = unicode(fileDialog.selectedNameFilter())
            if not fileName.lower().endswith(
                    tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    fileName += ext.group(1)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(fileName))
            settings.setValue('/Processing/encoding', encoding)

            uri = QgsDataSourceURI()
            uri.setDatabase(fileName)
            uri.setDataSource('', self.output.name.lower(), 'the_geom')
            self.leText.setText("spatialite:" + uri.uri())
コード例 #2
0
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename = QFileDialog.getOpenFileName(self.toolbox,
                                               self.tr('Open model', 'AddModelFromFileAction'), lastDir,
                                               self.tr('Processing model files (*.model *.MODEL)', 'AddModelFromFileAction'))
        if filename:
            try:
                settings.setValue('Processing/lastModelsDir',
                                  QFileInfo(filename).absoluteDir().absolutePath())

                ModelerAlgorithm.fromFile(filename)
            except WrongModelException:
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('The selected file does not contain a valid model', 'AddModelFromFileAction'))
                return
            except:
                QMessageBox.warning(self.toolbox,
                                    self.tr('Error reading model', 'AddModelFromFileAction'),
                                    self.tr('Cannot read file', 'AddModelFromFileAction'))
                return
            destFilename = os.path.join(ModelerUtils.modelsFolder(), os.path.basename(filename))
            shutil.copyfile(filename, destFilename)
            self.toolbox.updateProvider('model')
コード例 #3
0
    def selectFile(self):
        fileFilter = self.output.getFileFilter(self.alg)

        settings = QSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        encoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(
            self, self.tr('Save file'), path, fileFilter, encoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setConfirmOverwrite(True)

        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = unicode(fileDialog.encoding())
            self.output.encoding = encoding
            fileName = unicode(files[0])
            selectedFileFilter = unicode(fileDialog.selectedNameFilter())
            if not fileName.lower().endswith(
                    tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    fileName += ext.group(1)
            self.leText.setText(fileName)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(fileName))
            settings.setValue('/Processing/encoding', encoding)
コード例 #4
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 = 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]))
コード例 #5
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 = 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]))
コード例 #6
0
    def selectFile(self):
        fileFilter = self.output.getFileFilter(self.alg)

        settings = QSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        encoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(self, self.tr('Save file'), path,
                                           fileFilter, encoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setConfirmOverwrite(True)

        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = unicode(fileDialog.encoding())
            self.output.encoding = encoding
            fileName = unicode(files[0])
            selectedFileFilter = unicode(fileDialog.selectedNameFilter())
            if not fileName.lower().endswith(
                    tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    fileName += ext.group(1)
            self.leText.setText(fileName)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(fileName))
            settings.setValue('/Processing/encoding', encoding)
コード例 #7
0
ファイル: installer_data.py プロジェクト: chaosui/QGIS
    def load(self):
        """ populate the mRepositories dict"""
        self.mRepositories = {}
        settings = QSettings()
        settings.beginGroup(reposGroup)
        # first, update repositories in QSettings if needed
        officialRepoPresent = False
        for key in settings.childGroups():
            url = settings.value(key + "/url", "", type=unicode)
            if url == officialRepo[1]:
                officialRepoPresent = True
            if url == officialRepo[2]:
                settings.setValue(key + "/url", officialRepo[1])  # correct a depreciated url
                officialRepoPresent = True
        if not officialRepoPresent:
            settings.setValue(officialRepo[0] + "/url", officialRepo[1])

        for key in settings.childGroups():
            self.mRepositories[key] = {}
            self.mRepositories[key]["url"] = settings.value(key + "/url", "", type=unicode)
            self.mRepositories[key]["authcfg"] = settings.value(key + "/authcfg", "", type=unicode)
            self.mRepositories[key]["enabled"] = settings.value(key + "/enabled", True, type=bool)
            self.mRepositories[key]["valid"] = settings.value(key + "/valid", True, type=bool)
            self.mRepositories[key]["Relay"] = Relay(key)
            self.mRepositories[key]["xmlData"] = None
            self.mRepositories[key]["state"] = 0
            self.mRepositories[key]["error"] = ""
        settings.endGroup()
コード例 #8
0
 def execute(self):
     settings = QSettings()
     lastDir = settings.value('Processing/lastScriptsDir', '')
     filename = QFileDialog.getOpenFileName(
         self.toolbox, self.tr('Script files', 'AddScriptFromFileAction'),
         lastDir,
         self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction'))
     if filename:
         try:
             settings.setValue(
                 'Processing/lastScriptsDir',
                 QFileInfo(filename).absoluteDir().absolutePath())
             script = ScriptAlgorithm(filename)
         except WrongScriptException:
             QMessageBox.warning(
                 self.toolbox,
                 self.tr('Error reading script', 'AddScriptFromFileAction'),
                 self.tr(
                     'The selected file does not contain a valid script',
                     'AddScriptFromFileAction'))
             return
         destFilename = os.path.join(ScriptUtils.scriptsFolder(),
                                     os.path.basename(filename))
         with open(destFilename, 'w') as f:
             f.write(script.script)
         self.toolbox.updateProvider('script')
コード例 #9
0
    def showFileSelectionDialog(self):
        settings = QSettings()
        text = unicode(self.text.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 = unicode(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        ret = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path,
                                           self.tr('All files(*.*);;') + self.param.getFileFilter())
        if ret:
            files = list(ret)
            settings.setValue('/Processing/LastInputPath',
                              os.path.dirname(unicode(files[0])))
            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(unicode(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).setText(f)
コード例 #10
0
    def execute(self):
        settings = QSettings()
        lastDir = settings.value('Processing/lastModelsDir', '')
        filename = QFileDialog.getOpenFileName(
            self.toolbox, self.tr('Open model', 'AddModelFromFileAction'),
            lastDir,
            self.tr('Processing model files (*.model *.MODEL)',
                    'AddModelFromFileAction'))
        if filename:
            try:
                settings.setValue(
                    'Processing/lastModelsDir',
                    QFileInfo(filename).absoluteDir().absolutePath())

                ModelerAlgorithm.fromFile(filename)
            except WrongModelException:
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('The selected file does not contain a valid model',
                            'AddModelFromFileAction'))
                return
            except:
                QMessageBox.warning(
                    self.toolbox,
                    self.tr('Error reading model', 'AddModelFromFileAction'),
                    self.tr('Cannot read file', 'AddModelFromFileAction'))
                return
            destFilename = os.path.join(ModelerUtils.modelsFolder(),
                                        os.path.basename(filename))
            shutil.copyfile(filename, destFilename)
            self.toolbox.updateProvider('model')
コード例 #11
0
    def showFileSelectionDialog(self):
        settings = QSettings()
        text = unicode(self.text.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 = unicode(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        ret = QFileDialog.getOpenFileNames(
            self, self.tr('Open file'), path,
            self.tr('All files(*.*);;') + self.param.getFileFilter())
        if ret:
            files = list(ret)
            settings.setValue('/Processing/LastInputPath',
                              os.path.dirname(unicode(files[0])))
            for i, filename in enumerate(files):
                files[i] = dataobjects.getRasterSublayer(filename, self.param)
            if len(files) == 1:
                self.text.setText(files[0])
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(unicode(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).setText(f)
コード例 #12
0
ファイル: dlg_export_vector.py プロジェクト: Antoviscomi/QGIS
    def chooseOutputFile(self):
        # get last used dir
        settings = QSettings()
        lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".")

        # get selected filter
        selectedFilter = self.cboFileFormat.itemData(self.cboFileFormat.currentIndex())

        # ask for a filename
        filename = QFileDialog.getSaveFileName(self, self.tr("Choose where to save the file"), lastUsedDir,
                                               selectedFilter)
        if filename == "":
            return

        filterString = qgis.core.QgsVectorFileWriter.filterForDriver(selectedFilter)
        ext = filterString[filterString.find('.'):]
        ext = ext[:ext.find(' ')]

        if not filename.lower().endswith(ext):
            filename += ext

        # store the last used dir
        settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath())

        self.editOutputFile.setText(filename)
コード例 #13
0
    def saveToSpatialite(self):
        fileFilter = self.output.tr('Spatialite files(*.sqlite)', 'OutputFile')

        settings = QSettings()
        if settings.contains('/Processing/LastOutputPath'):
            path = settings.value('/Processing/LastOutputPath')
        else:
            path = ProcessingConfig.getSetting(ProcessingConfig.OUTPUT_FOLDER)

        encoding = settings.value('/Processing/encoding', 'System')
        fileDialog = QgsEncodingFileDialog(self, self.tr('Save Spatialite'),
                                           path, fileFilter, encoding)
        fileDialog.setFileMode(QFileDialog.AnyFile)
        fileDialog.setAcceptMode(QFileDialog.AcceptSave)
        fileDialog.setConfirmOverwrite(False)

        if fileDialog.exec_() == QDialog.Accepted:
            files = fileDialog.selectedFiles()
            encoding = unicode(fileDialog.encoding())
            self.output.encoding = encoding
            fileName = unicode(files[0])
            selectedFileFilter = unicode(fileDialog.selectedNameFilter())
            if not fileName.lower().endswith(
                    tuple(re.findall("\*(\.[a-z]{1,10})", fileFilter))):
                ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter)
                if ext:
                    fileName += ext.group(1)
            settings.setValue('/Processing/LastOutputPath',
                              os.path.dirname(fileName))
            settings.setValue('/Processing/encoding', encoding)

            uri = QgsDataSourceURI()
            uri.setDatabase(fileName)
            uri.setDataSource('', self.output.name.lower(), 'the_geom')
            self.leText.setText("spatialite:" + uri.uri())
コード例 #14
0
ファイル: dlg_export_vector.py プロジェクト: ravirbdgtc/QGIS
    def chooseOutputFile(self):
        # get last used dir
        settings = QSettings()
        lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".")

        # get selected filter
        selectedFilter = self.cboFileFormat.itemData(
            self.cboFileFormat.currentIndex())

        # ask for a filename
        filename = QFileDialog.getSaveFileName(
            self, self.tr("Choose where to save the file"), lastUsedDir,
            selectedFilter)
        if filename == "":
            return

        filterString = qgis.core.QgsVectorFileWriter.filterForDriver(
            selectedFilter)
        ext = filterString[filterString.find('.'):]
        ext = ext[:ext.find(' ')]

        if not filename.lower().endswith(ext):
            filename += ext

        # store the last used dir
        settings.setValue(self.lastUsedVectorDirSettingsKey,
                          QFileInfo(filename).filePath())

        self.editOutputFile.setText(filename)
コード例 #15
0
class NewConnectionDialog(QDialog, BASE_CLASS):
    """Dialogue to add a new CSW entry"""
    def __init__(self, conn_name=None):
        """init"""

        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = QSettings()
        self.conn_name = None
        self.conn_name_orig = conn_name

    def accept(self):
        """add CSW entry"""

        conn_name = self.leName.text().strip()
        conn_url = self.leURL.text().strip()

        if any([conn_name == '', conn_url == '']):
            QMessageBox.warning(self, self.tr('Save connection'),
                                self.tr('Both Name and URL must be provided'))
            return

        if '/' in conn_name:
            QMessageBox.warning(self, self.tr('Save connection'),
                                self.tr('Name cannot contain \'/\''))
            return

        if conn_name is not None:
            key = '/MetaSearch/%s' % conn_name
            keyurl = '%s/url' % key
            key_orig = '/MetaSearch/%s' % self.conn_name_orig

            # warn if entry was renamed to an existing connection
            if all([
                    self.conn_name_orig != conn_name,
                    self.settings.contains(keyurl)
            ]):
                res = QMessageBox.warning(self, self.tr('Save connection'),
                                          self.tr('Overwrite %s?') % conn_name,
                                          QMessageBox.Ok | QMessageBox.Cancel)
                if res == QMessageBox.Cancel:
                    return

            # on rename delete original entry first
            if all([
                    self.conn_name_orig is not None,
                    self.conn_name_orig != conn_name
            ]):
                self.settings.remove(key_orig)

            self.settings.setValue(keyurl, conn_url)
            self.settings.setValue('/MetaSearch/selected', conn_name)

            QDialog.accept(self)

    def reject(self):
        """back out of dialogue"""

        QDialog.reject(self)
コード例 #16
0
ファイル: installer_data.py プロジェクト: chaosui/QGIS
 def updateSeenPluginsList(self):
     """ update the list of all seen plugins """
     settings = QSettings()
     seenPlugins = settings.value(seenPluginGroup, self.mPlugins.keys(), type=unicode)
     for i in self.mPlugins.keys():
         if seenPlugins.count(i) == 0:
             seenPlugins += [i]
     settings.setValue(seenPluginGroup, seenPlugins)
コード例 #17
0
ファイル: GdalTools_utils.py プロジェクト: ravirbdgtc/QGIS
def setLastUsedDir(filePath):
    settings = QSettings()
    fileInfo = QFileInfo(filePath)
    if fileInfo.isDir():
        dirPath = fileInfo.filePath()
    else:
        dirPath = fileInfo.path()
    settings.setValue("/GdalTools/lastUsedDir", dirPath)
コード例 #18
0
ファイル: GdalTools_utils.py プロジェクト: Antoviscomi/QGIS
def setLastUsedDir(filePath):
    settings = QSettings()
    fileInfo = QFileInfo(filePath)
    if fileInfo.isDir():
        dirPath = fileInfo.filePath()
    else:
        dirPath = fileInfo.path()
    settings.setValue("/GdalTools/lastUsedDir", dirPath)
コード例 #19
0
class NewConnectionDialog(QDialog, BASE_CLASS):

    """Dialogue to add a new CSW entry"""

    def __init__(self, conn_name=None):
        """init"""

        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = QSettings()
        self.conn_name = None
        self.conn_name_orig = conn_name

    def accept(self):
        """add CSW entry"""

        conn_name = self.leName.text().strip()
        conn_url = self.leURL.text().strip()

        if any([conn_name == '', conn_url == '']):
            QMessageBox.warning(self, self.tr('Save connection'),
                                self.tr('Both Name and URL must be provided'))
            return

        if '/' in conn_name:
            QMessageBox.warning(self, self.tr('Save connection'),
                                self.tr('Name cannot contain \'/\''))
            return

        if conn_name is not None:
            key = '/MetaSearch/%s' % conn_name
            keyurl = '%s/url' % key
            key_orig = '/MetaSearch/%s' % self.conn_name_orig

            # warn if entry was renamed to an existing connection
            if all([self.conn_name_orig != conn_name,
                    self.settings.contains(keyurl)]):
                res = QMessageBox.warning(self, self.tr('Save connection'),
                                          self.tr('Overwrite %s?') % conn_name,
                                          QMessageBox.Ok | QMessageBox.Cancel)
                if res == QMessageBox.Cancel:
                    return

            # on rename delete original entry first
            if all([self.conn_name_orig is not None,
                    self.conn_name_orig != conn_name]):
                self.settings.remove(key_orig)

            self.settings.setValue(keyurl, conn_url)
            self.settings.setValue('/MetaSearch/selected', conn_name)

            QDialog.accept(self)

    def reject(self):
        """back out of dialogue"""

        QDialog.reject(self)
コード例 #20
0
    def loadAPIFile(self):
        settings = QSettings()
        lastDirPath = settings.value("pythonConsole/lastDirAPIPath", "", type=str)
        fileAPI = QFileDialog.getOpenFileName(
            self, "Open API File", lastDirPath, "API file (*.api)")
        if fileAPI:
            self.addAPI(fileAPI)

            lastDirPath = QFileInfo(fileAPI).path()
            settings.setValue("pythonConsole/lastDirAPIPath", fileAPI)
コード例 #21
0
 def updateSeenPluginsList(self):
     """ update the list of all seen plugins """
     settings = QSettings()
     seenPlugins = settings.value(seenPluginGroup,
                                  self.mPlugins.keys(),
                                  type=unicode)
     for i in self.mPlugins.keys():
         if seenPlugins.count(i) == 0:
             seenPlugins += [i]
     settings.setValue(seenPluginGroup, seenPlugins)
コード例 #22
0
ファイル: CheckValidity.py プロジェクト: ravirbdgtc/QGIS
    def processAlgorithm(self, progress):
        settings = QSettings()
        initial_method_setting = settings.value(settings_method_key, 1)

        method = self.getParameterValue(self.METHOD)
        if method != 0:
            settings.setValue(settings_method_key, method)
        try:
            self.doCheck(progress)
        finally:
            settings.setValue(settings_method_key, initial_method_setting)
コード例 #23
0
ファイル: db_manager.py プロジェクト: Antoviscomi/QGIS
    def closeEvent(self, e):
        self.unregisterAllActions()
        # clear preview, this will delete the layer in preview tab
        self.preview.loadPreview(None)

        # save the window state
        settings = QSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry())

        QMainWindow.closeEvent(self, e)
コード例 #24
0
    def closeEvent(self, e):
        self.unregisterAllActions()
        # clear preview, this will delete the layer in preview tab
        self.preview.loadPreview(None)

        # save the window state
        settings = QSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState",
                          self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry",
                          self.saveGeometry())

        QMainWindow.closeEvent(self, e)
コード例 #25
0
    def selectDirectory(self):

        settings = QSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            lastDir = unicode(settings.value('/Processing/LastBatchOutputPath'))
        else:
            lastDir = ''

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly)

        if dirName:
            self.table.cellWidget(self.row, self.col).setValue(dirName)
            settings.setValue('/Processing/LastBatchOutputPath', dirName)
コード例 #26
0
ファイル: dlg_import_vector.py プロジェクト: boggins/QGIS
    def chooseInputFile(self):
        vectorFormats = qgis.core.QgsProviderRegistry.instance().fileVectorFilters()
        # get last used dir and format
        settings = QSettings()
        lastDir = settings.value("/db_manager/lastUsedDir", "")
        lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "")
        # ask for a filename
        (filename, lastVectorFormat) = QFileDialog.getOpenFileNameAndFilter(self, self.tr("Choose the file to import"),
                                                                            lastDir, vectorFormats, lastVectorFormat)
        if filename == "":
            return
        # store the last used dir and format
        settings.setValue("/db_manager/lastUsedDir", QFileInfo(filename).filePath())
        settings.setValue("/UI/lastVectorFileFilter", lastVectorFormat)

        self.cboInputLayer.setEditText(filename)
コード例 #27
0
    def checkRIsInstalled(ignoreRegistrySettings=False):
        if isWindows():
            path = RUtils.RFolder()
            if path == '':
                return RUtils.tr(
                    'R folder is not configured.\nPlease configure '
                    'it before running R scripts.')

        R_INSTALLED = 'R_INSTALLED'
        settings = QSettings()
        if not ignoreRegistrySettings:
            if settings.contains(R_INSTALLED):
                return
        if isWindows():
            if ProcessingConfig.getSetting(RUtils.R_USE64):
                execDir = 'x64'
            else:
                execDir = 'i386'
            command = [
                RUtils.RFolder() + os.sep + 'bin' + os.sep + execDir + os.sep +
                'R.exe', '--version'
            ]
        else:
            command = ['R --version']
        proc = subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stdin=open(os.devnull),
            stderr=subprocess.STDOUT,
            universal_newlines=True,
        ).stdout

        for line in iter(proc.readline, ''):
            if 'R version' in line:
                settings.setValue(R_INSTALLED, True)
                return
        html = RUtils.tr(
            '<p>This algorithm requires R to be run. Unfortunately, it '
            'seems that R is not installed in your system, or it is not '
            'correctly configured to be used from QGIS</p>'
            '<p><a href="http://docs.qgis.org/testing/en/docs/user_manual/processing/3rdParty.html">Click here</a> '
            'to know more about how to install and configure R to be used with QGIS</p>'
        )

        return html
コード例 #28
0
    def selectDirectory(self):

        settings = QSettings()
        if settings.contains('/Processing/LastBatchOutputPath'):
            lastDir = unicode(
                settings.value('/Processing/LastBatchOutputPath'))
        else:
            lastDir = ''

        dirName = QFileDialog.getExistingDirectory(self,
                                                   self.tr('Select directory'),
                                                   lastDir,
                                                   QFileDialog.ShowDirsOnly)

        if dirName:
            self.table.cellWidget(self.row, self.col).setValue(dirName)
            settings.setValue('/Processing/LastBatchOutputPath', dirName)
コード例 #29
0
ファイル: ModelerDialog.py プロジェクト: Antoviscomi/QGIS
    def closeEvent(self, evt):
        settings = QSettings()
        settings.setValue("/Processing/splitterModeler", self.splitter.saveState())
        settings.setValue("/Processing/geometryModeler", self.saveGeometry())

        if self.hasChanged:
            ret = QMessageBox.question(
                self, self.tr('Unsaved changes'),
                self.tr('There are unsaved changes in model. Continue?'),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

            if ret == QMessageBox.Yes:
                evt.accept()
            else:
                evt.ignore()
        else:
            evt.accept()
コード例 #30
0
ファイル: ModelerDialog.py プロジェクト: ravirbdgtc/QGIS
    def closeEvent(self, evt):
        settings = QSettings()
        settings.setValue("/Processing/splitterModeler",
                          self.splitter.saveState())
        settings.setValue("/Processing/geometryModeler", self.saveGeometry())

        if self.hasChanged:
            ret = QMessageBox.question(
                self, self.tr('Unsaved changes'),
                self.tr('There are unsaved changes in model. Continue?'),
                QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

            if ret == QMessageBox.Yes:
                evt.accept()
            else:
                evt.ignore()
        else:
            evt.accept()
コード例 #31
0
    def addFile(self):
        settings = QSettings()
        if settings.contains("/Processing/LastInputPath"):
            path = settings.value("/Processing/LastInputPath")
        else:
            path = ""

        files = QFileDialog.getOpenFileNames(self, self.tr("Select file(s)"), path, self.tr("All files (*.*)"))

        if len(files) == 0:
            return

        model = self.lstLayers.model()
        for filePath in files:
            item = QStandardItem(filePath)
            model.appendRow(item)

        settings.setValue("/Processing/LastInputPath", os.path.dirname(files[0]))
コード例 #32
0
    def chooseInputFile(self):
        vectorFormats = qgis.core.QgsProviderRegistry.instance(
        ).fileVectorFilters()
        # get last used dir and format
        settings = QSettings()
        lastDir = settings.value("/db_manager/lastUsedDir", "")
        lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "")
        # ask for a filename
        (filename, lastVectorFormat) = QFileDialog.getOpenFileNameAndFilter(
            self, self.tr("Choose the file to import"), lastDir, vectorFormats,
            lastVectorFormat)
        if filename == "":
            return
        # store the last used dir and format
        settings.setValue("/db_manager/lastUsedDir",
                          QFileInfo(filename).filePath())
        settings.setValue("/UI/lastVectorFileFilter", lastVectorFormat)

        self.cboInputLayer.setEditText(filename)
コード例 #33
0
ファイル: RUtils.py プロジェクト: Clayton-Davis/QGIS
    def checkRIsInstalled(ignoreRegistrySettings=False):
        if isWindows():
            path = RUtils.RFolder()
            if path == '':
                return RUtils.tr('R folder is not configured.\nPlease configure '
                                 'it before running R scripts.')

        R_INSTALLED = 'R_INSTALLED'
        settings = QSettings()
        if not ignoreRegistrySettings:
            if settings.contains(R_INSTALLED):
                return
        if isWindows():
            if ProcessingConfig.getSetting(RUtils.R_USE64):
                execDir = 'x64'
            else:
                execDir = 'i386'
            command = [RUtils.RFolder() + os.sep + 'bin' + os.sep + execDir
                       + os.sep + 'R.exe', '--version']
        else:
            command = ['R --version']
        proc = subprocess.Popen(
            command,
            shell=True,
            stdout=subprocess.PIPE,
            stdin=open(os.devnull),
            stderr=subprocess.STDOUT,
            universal_newlines=True,
        ).stdout

        for line in iter(proc.readline, ''):
            if 'R version' in line:
                settings.setValue(R_INSTALLED, True)
                return
        html = RUtils.tr(
            '<p>This algorithm requires R to be run. Unfortunately, it '
            'seems that R is not installed in your system, or it is not '
            'correctly configured to be used from QGIS</p>'
            '<p><a href="http://docs.qgis.org/testing/en/docs/user_manual/processing/3rdParty.html">Click here</a> '
            'to know more about how to install and configure R to be used with QGIS</p>')

        return html
コード例 #34
0
 def execute(self):
     settings = QSettings()
     lastDir = settings.value('Processing/lastScriptsDir', '')
     filename = QFileDialog.getOpenFileName(self.toolbox,
                                            self.tr('Script files', 'AddScriptFromFileAction'), lastDir,
                                            self.tr('Script files (*.py *.PY)', 'AddScriptFromFileAction'))
     if filename:
         try:
             settings.setValue('Processing/lastScriptsDir',
                               QFileInfo(filename).absoluteDir().absolutePath())
             script = ScriptAlgorithm(filename)
         except WrongScriptException:
             QMessageBox.warning(self.toolbox,
                                 self.tr('Error reading script', 'AddScriptFromFileAction'),
                                 self.tr('The selected file does not contain a valid script', 'AddScriptFromFileAction'))
             return
         destFilename = os.path.join(ScriptUtils.scriptsFolder(), os.path.basename(filename))
         with open(destFilename, 'w') as f:
             f.write(script.script)
         self.toolbox.updateProvider('script')
コード例 #35
0
    def addFile(self):
        settings = QSettings()
        if settings.contains('/Processing/LastInputPath'):
            path = settings.value('/Processing/LastInputPath')
        else:
            path = ''

        files = QFileDialog.getOpenFileNames(self, self.tr('Select file(s)'),
                                             path, self.tr('All files (*.*)'))

        if len(files) == 0:
            return

        model = self.lstLayers.model()
        for filePath in files:
            item = QStandardItem(filePath)
            model.appendRow(item)

        settings.setValue('/Processing/LastInputPath',
                          os.path.dirname(files[0]))
コード例 #36
0
ファイル: console.py プロジェクト: Antoviscomi/QGIS
def show_console():
    """ called from QGIS to open the console """
    global _console
    if _console is None:
        parent = iface.mainWindow() if iface else None
        _console = PythonConsole(parent)
        _console.show()  # force show even if it was restored as hidden
        # set focus to the console so the user can start typing
        # defer the set focus event so it works also whether the console not visible yet
        QTimer.singleShot(0, _console.activate)
    else:
        _console.setVisible(not _console.isVisible())
        # set focus to the console so the user can start typing
        if _console.isVisible():
            _console.activate()
    ## Shows help on first launch of the console
    settings = QSettings()
    if settings.value('pythonConsole/contextHelpOnFirstLaunch', True, type=bool):
        QgsContextHelp.run("PythonConsole")
        settings.setValue('pythonConsole/contextHelpOnFirstLaunch', False)
コード例 #37
0
    def showSelectionDialog(self):
        settings = QSettings()
        text = unicode(self.cmbText.currentText())
        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 = unicode(settings.value('/Processing/LastInputPath'))
        else:
            path = ''

        filename = QFileDialog.getOpenFileName(
            self, self.tr('Select file'), path,
            self.tr('All files (*.*);;') + self.param.getFileFilter())
        if filename:
            settings.setValue('/Processing/LastInputPath',
                              os.path.dirname(unicode(filename)))
            filename = dataobjects.getRasterSublayer(filename, self.param)
            self.cmbText.addItem(filename, filename)
            self.cmbText.setCurrentIndex(self.cmbText.count() - 1)
コード例 #38
0
ファイル: installer.py プロジェクト: ravirbdgtc/QGIS
    def __init__(self):
        """ Initialize data objects, starts fetching if appropriate, and warn about/removes obsolete plugins """

        QObject.__init__(self)  # initialize QObject in order to to use self.tr()
        repositories.load()
        plugins.getAllInstalled()

        if repositories.checkingOnStart() and repositories.timeForChecking() and repositories.allEnabled():
            # start fetching repositories
            self.statusLabel = QLabel(self.tr("Looking for new plugins...") + " ", iface.mainWindow().statusBar())
            iface.mainWindow().statusBar().insertPermanentWidget(0, self.statusLabel)
            self.statusLabel.linkActivated.connect(self.showPluginManagerWhenReady)
            repositories.checkingDone.connect(self.checkingDone)
            for key in repositories.allEnabled():
                repositories.requestFetching(key)
        else:
            # no fetching at start, so mark all enabled repositories as requesting to be fetched.
            for key in repositories.allEnabled():
                repositories.setRepositoryData(key, "state", 3)

        # look for obsolete plugins (the user-installed one is newer than core one)
        for key in plugins.obsoletePlugins:
            plugin = plugins.localCache[key]
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Warning)
            msg.setWindowTitle(self.tr("QGIS Python Plugin Installer"))
            msg.addButton(self.tr("Uninstall (recommended)"), QMessageBox.AcceptRole)
            msg.addButton(self.tr("I will uninstall it later"), QMessageBox.RejectRole)
            msg.setText("%s <b>%s</b><br/><br/>%s" % (self.tr("Obsolete plugin:"), plugin["name"], self.tr("QGIS has detected an obsolete plugin that masks its more recent version shipped with this copy of QGIS. This is likely due to files associated with a previous installation of QGIS. Do you want to remove the old plugin right now and unmask the more recent version?")))
            msg.exec_()
            if not msg.result():
                # uninstall, update utils and reload if enabled
                self.uninstallPlugin(key, quiet=True)
                updateAvailablePlugins()
                settings = QSettings()
                if settings.value("/PythonPlugins/" + key, False, type=bool):
                    settings.setValue("/PythonPlugins/watchDog/" + key, True)
                    loadPlugin(key)
                    startPlugin(key)
                    settings.remove("/PythonPlugins/watchDog/" + key)
コード例 #39
0
    def load(self):
        """ populate the mRepositories dict"""
        self.mRepositories = {}
        settings = QSettings()
        settings.beginGroup(reposGroup)
        # first, update repositories in QSettings if needed
        officialRepoPresent = False
        for key in settings.childGroups():
            url = settings.value(key + "/url", "", type=unicode)
            if url == officialRepo[1]:
                officialRepoPresent = True
            if url == officialRepo[2]:
                settings.setValue(key + "/url",
                                  officialRepo[1])  # correct a depreciated url
                officialRepoPresent = True
        if not officialRepoPresent:
            settings.setValue(officialRepo[0] + "/url", officialRepo[1])

        for key in settings.childGroups():
            self.mRepositories[key] = {}
            self.mRepositories[key]["url"] = settings.value(key + "/url",
                                                            "",
                                                            type=unicode)
            self.mRepositories[key]["authcfg"] = settings.value(key +
                                                                "/authcfg",
                                                                "",
                                                                type=unicode)
            self.mRepositories[key]["enabled"] = settings.value(key +
                                                                "/enabled",
                                                                True,
                                                                type=bool)
            self.mRepositories[key]["valid"] = settings.value(key + "/valid",
                                                              True,
                                                              type=bool)
            self.mRepositories[key]["Relay"] = Relay(key)
            self.mRepositories[key]["xmlData"] = None
            self.mRepositories[key]["state"] = 0
            self.mRepositories[key]["error"] = ""
        settings.endGroup()
コード例 #40
0
ファイル: console.py プロジェクト: Clayton-Davis/QGIS
def show_console():
    """ called from QGIS to open the console """
    global _console
    if _console is None:
        parent = iface.mainWindow() if iface else None
        _console = PythonConsole(parent)
        _console.show()  # force show even if it was restored as hidden
        # set focus to the console so the user can start typing
        # defer the set focus event so it works also whether the console not visible yet
        QTimer.singleShot(0, _console.activate)
    else:
        _console.setVisible(not _console.isVisible())
        # set focus to the console so the user can start typing
        if _console.isVisible():
            _console.activate()
    ## Shows help on first launch of the console
    settings = QSettings()
    if settings.value('pythonConsole/contextHelpOnFirstLaunch',
                      True,
                      type=bool):
        QgsContextHelp.run("PythonConsole")
        settings.setValue('pythonConsole/contextHelpOnFirstLaunch', False)
コード例 #41
0
def getObjectFromUri(uri, forceLoad=True):
    """Returns an object (layer/table) given a source definition.

    if forceLoad is true, it tries to load it if it is not currently open
    Otherwise, it will return the object only if it is loaded in QGIS.
    """

    if uri is None:
        return None
    if uri in _loadedLayers:
        return _loadedLayers[uri]
    layers = getRasterLayers()
    for layer in layers:
        if normalizeLayerSource(layer.source()) == normalizeLayerSource(uri):
            return layer
    layers = getVectorLayers()
    for layer in layers:
        if normalizeLayerSource(layer.source()) == normalizeLayerSource(uri):
            return layer
    tables = getTables()
    for table in tables:
        if normalizeLayerSource(table.source()) == normalizeLayerSource(uri):
            return table
    if forceLoad:
        settings = QSettings()
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')

        # If is not opened, we open it
        for provider in ['ogr', 'postgres', 'spatialite', 'virtual']:
            layer = QgsVectorLayer(uri, uri, provider)
            if layer.isValid():
                if prjSetting:
                    settings.setValue('/Projections/defaultBehaviour', prjSetting)
                _loadedLayers[normalizeLayerSource(layer.source())] = layer
                return layer
        layer = QgsRasterLayer(uri, uri)
        if layer.isValid():
            if prjSetting:
                settings.setValue('/Projections/defaultBehaviour', prjSetting)
            _loadedLayers[normalizeLayerSource(layer.source())] = layer
            return layer
        if prjSetting:
            settings.setValue('/Projections/defaultBehaviour', prjSetting)
    else:
        return None
コード例 #42
0
def load(fileName, name=None, crs=None, style=None):
    """Loads a layer/table into the current project, given its file.
    """

    if fileName is None:
        return
    prjSetting = None
    settings = QSettings()
    if crs is not None:
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')
    if name is None:
        name = os.path.split(fileName)[1]
    qgslayer = QgsVectorLayer(fileName, name, 'ogr')
    if qgslayer.isValid():
        if crs is not None and qgslayer.crs() is None:
            qgslayer.setCrs(crs, False)
        if style is None:
            if qgslayer.geometryType() == QGis.Point:
                style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POINT_STYLE)
            elif qgslayer.geometryType() == QGis.Line:
                style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_LINE_STYLE)
            else:
                style = ProcessingConfig.getSetting(ProcessingConfig.VECTOR_POLYGON_STYLE)
        qgslayer.loadNamedStyle(style)
        QgsMapLayerRegistry.instance().addMapLayers([qgslayer])
    else:
        qgslayer = QgsRasterLayer(fileName, name)
        if qgslayer.isValid():
            if crs is not None and qgslayer.crs() is None:
                qgslayer.setCrs(crs, False)
            if style is None:
                style = ProcessingConfig.getSetting(ProcessingConfig.RASTER_STYLE)
            qgslayer.loadNamedStyle(style)
            QgsMapLayerRegistry.instance().addMapLayers([qgslayer])
            iface.legendInterface().refreshLayerSymbology(qgslayer)
        else:
            if prjSetting:
                settings.setValue('/Projections/defaultBehaviour', prjSetting)
            raise RuntimeError('Could not load layer: ' + unicode(fileName)
                               + '\nCheck the processing framework log to look for errors')
    if prjSetting:
        settings.setValue('/Projections/defaultBehaviour', prjSetting)

    return qgslayer
コード例 #43
0
ファイル: installer.py プロジェクト: ravirbdgtc/QGIS
 def editRepository(self, reposName):
     """ edit repository connection """
     if not reposName:
         return
     reposName = reposName.decode('utf-8')
     checkState = {False: Qt.Unchecked, True: Qt.Checked}
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editName.setText(reposName)
     dlg.editURL.setText(repositories.all()[reposName]["url"])
     dlg.editAuthCfg.setText(repositories.all()[reposName]["authcfg"])
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(checkState[repositories.all()[reposName]["enabled"]])
     if repositories.all()[reposName]["valid"]:
         dlg.checkBoxEnabled.setEnabled(True)
         dlg.labelInfo.setText("")
     else:
         dlg.checkBoxEnabled.setEnabled(False)
         dlg.labelInfo.setText(self.tr("This repository is blocked due to incompatibility with your QGIS version"))
         dlg.labelInfo.setFrameShape(QFrame.Box)
     if not dlg.exec_():
         return  # nothing to do if cancelled
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"] and dlg.editURL.text().strip() != repositories.all()[reposName]["url"]:
             iface.pluginManagerInterface().pushMessage(self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING)
             return
     # delete old repo from QSettings and create new one
     settings = QSettings()
     settings.beginGroup(reposGroup)
     settings.remove(reposName)
     newName = dlg.editName.text()
     if newName in repositories.all() and newName != reposName:
         newName = newName + "(2)"
     settings.setValue(newName + "/url", dlg.editURL.text().strip())
     settings.setValue(newName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(newName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     if dlg.editAuthCfg.text().strip() != repositories.all()[reposName]["authcfg"]:
         repositories.all()[reposName]["authcfg"] = dlg.editAuthCfg.text().strip()
     if dlg.editURL.text().strip() == repositories.all()[reposName]["url"] and dlg.checkBoxEnabled.checkState() == checkState[repositories.all()[reposName]["enabled"]]:
         repositories.rename(reposName, newName)
         self.exportRepositoriesToManager()
         return  # nothing else to do if only repository name was changed
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
コード例 #44
0
ファイル: installer.py プロジェクト: ravirbdgtc/QGIS
 def addRepository(self):
     """ add new repository connection """
     dlg = QgsPluginInstallerRepositoryDialog(iface.mainWindow())
     dlg.editParams.setText(repositories.urlParams())
     dlg.checkBoxEnabled.setCheckState(Qt.Checked)
     if not dlg.exec_():
         return
     for i in repositories.all().values():
         if dlg.editURL.text().strip() == i["url"]:
             iface.pluginManagerInterface().pushMessage(self.tr("Unable to add another repository with the same URL!"), QgsMessageBar.WARNING)
             return
     settings = QSettings()
     settings.beginGroup(reposGroup)
     reposName = dlg.editName.text()
     reposURL = dlg.editURL.text().strip()
     if reposName in repositories.all():
         reposName = reposName + "(2)"
     # add to settings
     settings.setValue(reposName + "/url", reposURL)
     settings.setValue(reposName + "/authcfg", dlg.editAuthCfg.text().strip())
     settings.setValue(reposName + "/enabled", bool(dlg.checkBoxEnabled.checkState()))
     # refresh lists and populate widgets
     plugins.removeRepository(reposName)
     self.reloadAndExportData()
コード例 #45
0
ファイル: GdalTools_utils.py プロジェクト: Antoviscomi/QGIS
def setHelpPath(path):
    settings = QSettings()
    settings.setValue("/GdalTools/helpPath", path)
コード例 #46
0
class AlgorithmDialogBase(BASE, WIDGET):

    def __init__(self, alg):
        super(AlgorithmDialogBase, self).__init__(iface.mainWindow())
        self.setupUi(self)

        self.settings = QSettings()
        self.restoreGeometry(self.settings.value("/Processing/dialogBase", QByteArray()))

        self.executed = False
        self.mainWidget = None
        self.alg = alg

        # Rename OK button to Run
        self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok)
        self.btnRun.setText(self.tr('Run'))

        self.btnClose = self.buttonBox.button(QDialogButtonBox.Close)

        self.setWindowTitle(AlgorithmClassification.getDisplayName(self.alg))

        desktop = QDesktopWidget()
        if desktop.physicalDpiX() > 96:
            self.textHelp.setZoomFactor(desktop.physicalDpiX() / 96)

        algHelp = self.alg.shortHelp()
        if algHelp is None:
            self.textShortHelp.setVisible(False)
        else:
            self.textShortHelp.document().setDefaultStyleSheet('''.summary { margin-left: 10px; margin-right: 10px; }
                                                    h2 { color: #555555; padding-bottom: 15px; }
                                                    a { text-decoration: none; color: #3498db; font-weight: bold; }
                                                    p { color: #666666; }
                                                    b { color: #333333; }
                                                    dl dd { margin-bottom: 5px; }''')
            self.textShortHelp.setHtml(algHelp)

        self.textShortHelp.setOpenLinks(False)

        def linkClicked(url):
            webbrowser.open(url.toString())
        self.textShortHelp.anchorClicked.connect(linkClicked)

        self.textHelp.page().setNetworkAccessManager(QgsNetworkAccessManager.instance())

        isText, algHelp = self.alg.help()
        if algHelp is not None:
            algHelp = algHelp if isText else QUrl(algHelp)
            try:
                if isText:
                    self.textHelp.setHtml(algHelp)
                else:
                    self.textHelp.settings().clearMemoryCaches()
                    self.textHelp.load(algHelp)
            except:
                self.tabWidget.removeTab(2)
        else:
            self.tabWidget.removeTab(2)

        self.showDebug = ProcessingConfig.getSetting(
            ProcessingConfig.SHOW_DEBUG_IN_DIALOG)

    def closeEvent(self, evt):
        self.settings.setValue("/Processing/dialogBase", self.saveGeometry())
        super(AlgorithmDialogBase, self).closeEvent(evt)

    def setMainWidget(self):
        self.tabWidget.widget(0).layout().addWidget(self.mainWidget)

    def error(self, msg):
        QApplication.restoreOverrideCursor()
        self.setInfo(msg, True)
        self.resetGUI()
        self.tabWidget.setCurrentIndex(1)

    def resetGUI(self):
        QApplication.restoreOverrideCursor()
        self.lblProgress.setText('')
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)
        self.btnRun.setEnabled(True)
        self.btnClose.setEnabled(True)

    def setInfo(self, msg, error=False):
        if error:
            self.txtLog.append('<span style="color:red"><br>%s<br></span>' % msg)
        else:
            self.txtLog.append(msg)
        QCoreApplication.processEvents()

    def setCommand(self, cmd):
        if self.showDebug:
            self.setInfo('<code>%s<code>' % cmd)
        QCoreApplication.processEvents()

    def setDebugInfo(self, msg):
        if self.showDebug:
            self.setInfo('<span style="color:blue">%s</span>' % msg)
        QCoreApplication.processEvents()

    def setConsoleInfo(self, msg):
        if self.showDebug:
            self.setCommand('<span style="color:darkgray">%s</span>' % msg)
        QCoreApplication.processEvents()

    def setPercentage(self, value):
        if self.progressBar.maximum() == 0:
            self.progressBar.setMaximum(100)
        self.progressBar.setValue(value)
        QCoreApplication.processEvents()

    def setText(self, text):
        self.lblProgress.setText(text)
        self.setInfo(text, False)
        QCoreApplication.processEvents()

    def setParamValues(self):
        pass

    def setParamValue(self, param, widget, alg=None):
        pass

    def accept(self):
        pass

    def finish(self):
        pass

    class InvalidParameterValue(Exception):

        def __init__(self, param, widget):
            (self.parameter, self.widget) = (param, widget)
コード例 #47
0
ファイル: GdalTools_utils.py プロジェクト: ravirbdgtc/QGIS
def setGdalBinPath(path):
    settings = QSettings()
    settings.setValue("/GdalTools/gdalPath", path)
コード例 #48
0
ファイル: GdalTools_utils.py プロジェクト: ravirbdgtc/QGIS
 def setFilter(self, typeName, aFilter):
     settings = QSettings()
     settings.setValue("/GdalTools/" + typeName + "FileFilter", aFilter)
コード例 #49
0
ファイル: GdalTools_utils.py プロジェクト: Antoviscomi/QGIS
def setLastUsedEncoding(encoding):
    settings = QSettings()
    settings.setValue("/UI/encoding", encoding)
コード例 #50
0
class ManageConnectionsDialog(QDialog, BASE_CLASS):

    """manage connections"""

    def __init__(self, mode):
        """init dialog"""

        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = QSettings()
        self.filename = None
        self.mode = mode  # 0 - save, 1 - load
        self.btnBrowse.clicked.connect(self.select_file)
        self.manage_gui()

    def manage_gui(self):
        """manage interface"""

        if self.mode == 1:
            self.label.setText(self.tr('Load from file'))
            self.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Load'))
        else:
            self.label.setText(self.tr('Save to file'))
            self.buttonBox.button(QDialogButtonBox.Ok).setText(self.tr('Save'))
            self.populate()

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    def select_file(self):
        """select file ops"""

        label = self.tr('eXtensible Markup Language (*.xml *.XML)')

        if self.mode == 0:
            slabel = self.tr('Save connections')
            self.filename = QFileDialog.getSaveFileName(self, slabel,
                                                        '.', label)
        else:
            slabel = self.tr('Load connections')
            self.filename = QFileDialog.getOpenFileName(self, slabel,
                                                        '.', label)

        if not self.filename:
            return

        # ensure the user never omitted the extension from the file name
        if not self.filename.lower().endswith('.xml'):
            self.filename = '%s.xml' % self.filename

        self.leFileName.setText(self.filename)

        if self.mode == 1:
            self.populate()

        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(True)

    def populate(self):
        """populate connections list from settings"""

        if self.mode == 0:
            self.settings.beginGroup('/MetaSearch/')
            keys = self.settings.childGroups()
            for key in keys:
                item = QListWidgetItem(self.listConnections)
                item.setText(key)
            self.settings.endGroup()

        else:  # populate connections list from file
            doc = get_connections_from_file(self, self.filename)
            if doc is None:
                self.filename = None
                self.leFileName.clear()
                self.listConnections.clear()
                return

            for csw in doc.findall('csw'):
                item = QListWidgetItem(self.listConnections)
                item.setText(csw.attrib.get('name'))

    def save(self, connections):
        """save connections ops"""

        doc = etree.Element('qgsCSWConnections')
        doc.attrib['version'] = '1.0'

        for conn in connections:
            url = self.settings.value('/MetaSearch/%s/url' % conn)
            if url is not None:
                connection = etree.SubElement(doc, 'csw')
                connection.attrib['name'] = conn
                connection.attrib['url'] = url

        # write to disk
        with open(self.filename, 'w') as fileobj:
            fileobj.write(prettify_xml(etree.tostring(doc)))
        QMessageBox.information(self, self.tr('Save Connections'),
                                self.tr('Saved to %s') % self.filename)
        self.reject()

    def load(self, items):
        """load connections"""

        self.settings.beginGroup('/MetaSearch/')
        keys = self.settings.childGroups()
        self.settings.endGroup()

        exml = etree.parse(self.filename).getroot()

        for csw in exml.findall('csw'):
            conn_name = csw.attrib.get('name')

            # process only selected connections
            if conn_name not in items:
                continue

            # check for duplicates
            if conn_name in keys:
                label = self.tr('File %s exists. Overwrite?') % conn_name
                res = QMessageBox.warning(self, self.tr('Loading Connections'),
                                          label,
                                          QMessageBox.Yes | QMessageBox.No)
                if res != QMessageBox.Yes:
                    continue

            # no dups detected or overwrite is allowed
            url = '/MetaSearch/%s/url' % conn_name
            self.settings.setValue(url, csw.attrib.get('url'))

    def accept(self):
        """accept connections"""

        selection = self.listConnections.selectedItems()
        if len(selection) == 0:
            return

        items = []
        for sel in selection:
            items.append(sel.text())

        if self.mode == 0:  # save
            self.save(items)
        else:  # load
            self.load(items)

        self.filename = None
        self.leFileName.clear()
        self.listConnections.clear()
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)

    def reject(self):
        """back out of manage connections dialogue"""

        QDialog.reject(self)
コード例 #51
0
ファイル: GdalTools_utils.py プロジェクト: Antoviscomi/QGIS
 def setFilter(self, typeName, aFilter):
     settings = QSettings()
     settings.setValue("/GdalTools/" + typeName + "FileFilter", aFilter)
コード例 #52
0
ファイル: GdalTools_utils.py プロジェクト: ravirbdgtc/QGIS
def setHelpPath(path):
    settings = QSettings()
    settings.setValue("/GdalTools/helpPath", path)
コード例 #53
0
ファイル: GdalTools_utils.py プロジェクト: Antoviscomi/QGIS
def setGdalBinPath(path):
    settings = QSettings()
    settings.setValue("/GdalTools/gdalPath", path)
コード例 #54
0
ファイル: GdalTools_utils.py プロジェクト: ravirbdgtc/QGIS
def setLastUsedEncoding(encoding):
    settings = QSettings()
    settings.setValue("/UI/encoding", encoding)
コード例 #55
0
ファイル: console_settings.py プロジェクト: Antoviscomi/QGIS
    def saveSettings(self):
        settings = QSettings()
        settings.setValue("pythonConsole/preloadAPI", self.preloadAPI.isChecked())
        settings.setValue("pythonConsole/autoSaveScript", self.autoSaveScript.isChecked())

        fontFamilyText = self.fontComboBox.currentText()
        settings.setValue("pythonConsole/fontfamilytext", fontFamilyText)
        fontFamilyTextEditor = self.fontComboBoxEditor.currentText()
        settings.setValue("pythonConsole/fontfamilytextEditor", fontFamilyTextEditor)

        fontSize = self.spinBox.value()
        fontSizeEditor = self.spinBoxEditor.value()

        for i in range(0, self.tableWidget.rowCount()):
            text = self.tableWidget.item(i, 1).text()
            self.listPath.append(text)
        settings.setValue("pythonConsole/fontsize", fontSize)
        settings.setValue("pythonConsole/fontsizeEditor", fontSizeEditor)
        settings.setValue("pythonConsole/userAPI", self.listPath)

        settings.setValue("pythonConsole/autoCompThreshold", self.autoCompThreshold.value())
        settings.setValue("pythonConsole/autoCompThresholdEditor", self.autoCompThresholdEditor.value())

        settings.setValue("pythonConsole/autoCompleteEnabledEditor", self.groupBoxAutoCompletionEditor.isChecked())
        settings.setValue("pythonConsole/autoCompleteEnabled", self.groupBoxAutoCompletion.isChecked())

        settings.setValue("pythonConsole/usePreparedAPIFile", self.groupBoxPreparedAPI.isChecked())
        settings.setValue("pythonConsole/preparedAPIFile", self.lineEdit.text())

        if self.autoCompFromAPIEditor.isChecked():
            settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromAPI')
        elif self.autoCompFromDocEditor.isChecked():
            settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDoc')
        elif self.autoCompFromDocAPIEditor.isChecked():
            settings.setValue("pythonConsole/autoCompleteSourceEditor", 'fromDocAPI')

        if self.autoCompFromAPI.isChecked():
            settings.setValue("pythonConsole/autoCompleteSource", 'fromAPI')
        elif self.autoCompFromDoc.isChecked():
            settings.setValue("pythonConsole/autoCompleteSource", 'fromDoc')
        elif self.autoCompFromDocAPI.isChecked():
            settings.setValue("pythonConsole/autoCompleteSource", 'fromDocAPI')

        settings.setValue("pythonConsole/enableObjectInsp", self.enableObjectInspector.isChecked())
        settings.setValue("pythonConsole/autoCloseBracket", self.autoCloseBracket.isChecked())
        settings.setValue("pythonConsole/autoCloseBracketEditor", self.autoCloseBracketEditor.isChecked())
        settings.setValue("pythonConsole/autoInsertionImport", self.autoInsertionImport.isChecked())
        settings.setValue("pythonConsole/autoInsertionImportEditor", self.autoInsertionImportEditor.isChecked())

        settings.setValue("pythonConsole/defaultFontColor", self.defaultFontColor.color())
        settings.setValue("pythonConsole/defaultFontColorEditor", self.defaultFontColorEditor.color())
        settings.setValue("pythonConsole/classFontColor", self.classFontColor.color())
        settings.setValue("pythonConsole/classFontColorEditor", self.classFontColorEditor.color())
        settings.setValue("pythonConsole/keywordFontColor", self.keywordFontColor.color())
        settings.setValue("pythonConsole/keywordFontColorEditor", self.keywordFontColorEditor.color())
        settings.setValue("pythonConsole/decorFontColor", self.decorFontColor.color())
        settings.setValue("pythonConsole/decorFontColorEditor", self.decorFontColorEditor.color())
        settings.setValue("pythonConsole/methodFontColor", self.methodFontColor.color())
        settings.setValue("pythonConsole/methodFontColorEditor", self.methodFontColorEditor.color())
        settings.setValue("pythonConsole/commentFontColor", self.commentFontColor.color())
        settings.setValue("pythonConsole/commentFontColorEditor", self.commentFontColorEditor.color())
        settings.setValue("pythonConsole/commentBlockFontColor", self.commentBlockFontColor.color())
        settings.setValue("pythonConsole/commentBlockFontColorEditor", self.commentBlockFontColorEditor.color())
        settings.setValue("pythonConsole/paperBackgroundColor", self.paperBackgroundColor.color())
        settings.setValue("pythonConsole/paperBackgroundColorEditor", self.paperBackgroundColorEditor.color())
        settings.setValue("pythonConsole/cursorColor", self.cursorColor.color())
        settings.setValue("pythonConsole/cursorColorEditor", self.cursorColorEditor.color())
        settings.setValue("pythonConsole/caretLineColor", self.caretLineColor.color())
        settings.setValue("pythonConsole/caretLineColorEditor", self.caretLineColorEditor.color())
        settings.setValue("pythonConsole/stderrFontColor", self.stderrFontColor.color())

        settings.setValue("pythonConsole/singleQuoteFontColor", self.singleQuoteFontColor.color())
        settings.setValue("pythonConsole/singleQuoteFontColorEditor", self.singleQuoteFontColorEditor.color())
        settings.setValue("pythonConsole/doubleQuoteFontColor", self.doubleQuoteFontColor.color())
        settings.setValue("pythonConsole/doubleQuoteFontColorEditor", self.doubleQuoteFontColorEditor.color())
        settings.setValue("pythonConsole/tripleSingleQuoteFontColor", self.tripleSingleQuoteFontColor.color())
        settings.setValue("pythonConsole/tripleSingleQuoteFontColorEditor", self.tripleSingleQuoteFontColorEditor.color())
        settings.setValue("pythonConsole/tripleDoubleQuoteFontColor", self.tripleDoubleQuoteFontColor.color())
        settings.setValue("pythonConsole/tripleDoubleQuoteFontColorEditor", self.tripleDoubleQuoteFontColorEditor.color())
コード例 #56
0
ファイル: plugin.py プロジェクト: MrBenjaminLeb/QGIS
 def addConnection(self, conn_name, uri):
     settings = QSettings()
     settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))
     settings.setValue("sqlitepath", uri.database())
     return True