当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QSettings类代码示例

本文整理汇总了Python中PyQt.QtCore.QSettings的典型用法代码示例。如果您正苦于以下问题:Python QSettings类的具体用法?Python QSettings怎么用?Python QSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QSettings类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: chooseOutputFile

    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)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:25,代码来源:dlg_export_vector.py

示例2: showFileSelectionDialog

    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)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:32,代码来源:BatchInputSelectionPanel.py

示例3: getVectorWriter

    def getVectorWriter(self, fields, geomType, crs, options=None):
        """Returns a suitable writer to which features can be added as
        a result of the algorithm. Use this to transparently handle
        output values instead of creating your own method.

        Executing this method might modify the object, adding additional
        information to it, so the writer can be later accessed and
        processed within QGIS. It should be called just once, since a
        new call might result in previous data being replaced, thus
        rendering a previously obtained writer useless.

        @param fields   a list  of QgsField
        @param geomType a suitable geometry type, as it would be passed
                        to a QgsVectorFileWriter constructor
        @param crs      the crs of the layer to create

        @return writer  instance of the vector writer class
        """

        if self.encoding is None:
            settings = QSettings()
            self.encoding = settings.value('/Processing/encoding', 'System', str)

        w = VectorWriter(self.value, self.encoding, fields, geomType,
                         crs, options)
        self.layer = w.layer
        return w
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:27,代码来源:outputs.py

示例4: processAlgorithm

    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""

        # The first thing to do is retrieve the values of the parameters
        # entered by the user
        inputFilename = self.getParameterValue(self.INPUT_LAYER)
        output = self.getOutputValue(self.OUTPUT_LAYER)

        # Input layers vales are always a string with its location.
        # That string can be converted into a QGIS object (a
        # QgsVectorLayer in this case) using the
        # processing.getObjectFromUri() method.
        vectorLayer = dataobjects.getObjectFromUri(inputFilename)

        # And now we can process

        # First we create the output layer. The output value entered by
        # the user is a string containing a filename, so we can use it
        # directly
        settings = QSettings()
        systemEncoding = settings.value("/UI/encoding", "System")
        provider = vectorLayer.dataProvider()
        writer = QgsVectorFileWriter(output, systemEncoding, provider.fields(), provider.geometryType(), provider.crs())

        # Now we take the features from input layer and add them to the
        # output. Method features() returns an iterator, considering the
        # selection that might exist in layer and the configuration that
        # indicates should algorithm use only selected features or all
        # of them
        features = vector.features(vectorLayer)
        for f in features:
            writer.addFeature(f)
开发者ID:dwadler,项目名称:QGIS,代码行数:32,代码来源:ExampleAlgorithm.py

示例5: read

 def read(self):
     qsettings = QSettings()
     value = qsettings.value(self.qname, None)
     if value is not None:
         if isinstance(self.value, bool):
             value = unicode(value).lower() == unicode(True).lower()
         self.value = value
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:7,代码来源:ProcessingConfig.py

示例6: execute

    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')
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:26,代码来源:AddModelFromFileAction.py

示例7: updateSeenPluginsList

 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)
开发者ID:chaosui,项目名称:QGIS,代码行数:8,代码来源:installer_data.py

示例8: markNews

 def markNews(self):
     """ mark all new plugins as new """
     settings = QSettings()
     seenPlugins = settings.value(seenPluginGroup, self.mPlugins.keys(), type=unicode)
     if len(seenPlugins) > 0:
         for i in self.mPlugins.keys():
             if seenPlugins.count(i) == 0 and self.mPlugins[i]["status"] == "not installed":
                 self.mPlugins[i]["status"] = "new"
开发者ID:chaosui,项目名称:QGIS,代码行数:8,代码来源:installer_data.py

示例9: setLastUsedDir

def setLastUsedDir(filePath):
    settings = QSettings()
    fileInfo = QFileInfo(filePath)
    if fileInfo.isDir():
        dirPath = fileInfo.filePath()
    else:
        dirPath = fileInfo.path()
    settings.setValue("/GdalTools/lastUsedDir", dirPath)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:8,代码来源:GdalTools_utils.py

示例10: exportVectorLayer

def exportVectorLayer(layer):
    """Takes a QgsVectorLayer and returns the filename to refer to it,
    which allows external apps which support only file-based layers to
    use it. It performs the necessary export in case the input layer
    is not in a standard format suitable for most applications, it is
    a remote one or db-based (non-file based) one, or if there is a
    selection and it should be used, exporting just the selected
    features.

    Currently, the output is restricted to shapefiles, so anything
    that is not in a shapefile will get exported. It also export to
    a new file if the original one contains non-ascii characters.
    """

    settings = QSettings()
    systemEncoding = settings.value('/UI/encoding', 'System')

    filename = os.path.basename(unicode(layer.source()))
    idx = filename.rfind('.')
    if idx != -1:
        filename = filename[:idx]

    filename = unicode(layer.name())
    validChars = \
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:'
    filename = ''.join(c for c in filename if c in validChars)
    if len(filename) == 0:
        filename = 'layer'
    output = getTempFilenameInTempFolder(filename + '.shp')
    provider = layer.dataProvider()
    useSelection = ProcessingConfig.getSetting(ProcessingConfig.USE_SELECTED)
    if useSelection and layer.selectedFeatureCount() != 0:
        writer = QgsVectorFileWriter(output, systemEncoding,
                                     layer.pendingFields(),
                                     provider.geometryType(), layer.crs())
        selection = layer.selectedFeatures()
        for feat in selection:
            writer.addFeature(feat)
        del writer
        return output
    else:
        isASCII = True
        try:
            unicode(layer.source()).decode('ascii')
        except UnicodeEncodeError:
            isASCII = False
        if not unicode(layer.source()).endswith('shp') or not isASCII:
            writer = QgsVectorFileWriter(
                output, systemEncoding,
                layer.pendingFields(), provider.geometryType(),
                layer.crs()
            )
            for feat in layer.getFeatures():
                writer.addFeature(feat)
            del writer
            return output
        else:
            return unicode(layer.source())
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:58,代码来源:dataobjects.py

示例11: convertUnsupportedFormats

    def convertUnsupportedFormats(self, progress):
        i = 0
        progress.setText(self.tr('Converting outputs'))
        for out in self.outputs:
            if isinstance(out, OutputVector):
                if out.compatible is not None:
                    layer = dataobjects.getObjectFromUri(out.compatible)
                    if layer is None:
                        # For the case of memory layer, if the
                        # getCompatible method has been called
                        continue
                    provider = layer.dataProvider()
                    writer = out.getVectorWriter(
                        provider.fields(),
                        provider.geometryType(), layer.crs()
                    )
                    features = vector.features(layer)
                    for feature in features:
                        writer.addFeature(feature)
            elif isinstance(out, OutputRaster):
                if out.compatible is not None:
                    layer = dataobjects.getObjectFromUri(out.compatible)
                    format = self.getFormatShortNameFromFilename(out.value)
                    orgFile = out.compatible
                    destFile = out.value
                    crsid = layer.crs().authid()
                    settings = QSettings()
                    path = unicode(settings.value('/GdalTools/gdalPath', ''))
                    envval = unicode(os.getenv('PATH'))
                    if not path.lower() in envval.lower().split(os.pathsep):
                        envval += '%s%s' % (os.pathsep, path)
                        os.putenv('PATH', envval)
                    command = 'gdal_translate -of %s -a_srs %s %s %s' % (format, crsid, orgFile, destFile)
                    if os.name == 'nt':
                        command = command.split(" ")
                    else:
                        command = [command]
                    proc = subprocess.Popen(
                        command,
                        shell=True,
                        stdout=subprocess.PIPE,
                        stdin=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        universal_newlines=False,
                    )
                    proc.communicate()

            elif isinstance(out, OutputTable):
                if out.compatible is not None:
                    layer = dataobjects.getObjectFromUri(out.compatible)
                    provider = layer.dataProvider()
                    writer = out.getTableWriter(provider.fields())
                    features = vector.features(layer)
                    for feature in features:
                        writer.addRecord(feature)
            progress.setPercentage(100 * i / float(len(self.outputs)))
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:56,代码来源:GeoAlgorithm.py

示例12: loadAPIFile

    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)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:10,代码来源:console_settings.py

示例13: connect

    def connect(self, parent=None):
        conn_name = self.connectionName()
        settings = QSettings()
        settings.beginGroup(u"/%s/%s" % (self.connectionSettingsKey(), conn_name))

        if not settings.contains("database"):  # non-existent entry?
            raise InvalidDataException(self.tr('There is no defined database connection "%s".') % conn_name)

        from qgis.core import QgsDataSourceURI

        uri = QgsDataSourceURI()

        settingsList = ["service", "host", "port", "database", "username", "password", "authcfg"]
        service, host, port, database, username, password, authcfg = [settings.value(x, "", type=str) for x in settingsList]

        useEstimatedMetadata = settings.value("estimatedMetadata", False, type=bool)
        sslmode = settings.value("sslmode", QgsDataSourceURI.SSLprefer, type=int)

        settings.endGroup()

        if service:
            uri.setConnection(service, database, username, password, sslmode, authcfg)
        else:
            uri.setConnection(host, port, database, username, password, sslmode, authcfg)

        uri.setUseEstimatedMetadata(useEstimatedMetadata)

        try:
            return self.connectToUri(uri)
        except ConnectionError:
            return False
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:31,代码来源:plugin.py

示例14: closeEvent

    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)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:11,代码来源:db_manager.py

示例15: initLexer

    def initLexer(self):
        if self.lexerType == self.LEXER_PYTHON:
            self.lexer = QsciLexerPython()

            colorDefault = QColor('#2e3436')
            colorComment = QColor('#c00')
            colorCommentBlock = QColor('#3465a4')
            colorNumber = QColor('#4e9a06')
            colorType = QColor('#4e9a06')
            colorKeyword = QColor('#204a87')
            colorString = QColor('#ce5c00')

            self.lexer.setDefaultFont(self.defaultFont)
            self.lexer.setDefaultColor(colorDefault)

            self.lexer.setColor(colorComment, 1)
            self.lexer.setColor(colorNumber, 2)
            self.lexer.setColor(colorString, 3)
            self.lexer.setColor(colorString, 4)
            self.lexer.setColor(colorKeyword, 5)
            self.lexer.setColor(colorString, 6)
            self.lexer.setColor(colorString, 7)
            self.lexer.setColor(colorType, 8)
            self.lexer.setColor(colorCommentBlock, 12)
            self.lexer.setColor(colorString, 15)

            self.lexer.setFont(self.italicFont, 1)
            self.lexer.setFont(self.boldFont, 5)
            self.lexer.setFont(self.boldFont, 8)
            self.lexer.setFont(self.italicFont, 12)

            self.api = QsciAPIs(self.lexer)

            settings = QSettings()
            useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI',
                                                True))
            if useDefaultAPI:
                # Load QGIS API shipped with Python console
                self.api.loadPrepared(
                    os.path.join(QgsApplication.pkgDataPath(),
                                 'python', 'qsci_apis', 'pyqgis.pap'))
            else:
                # Load user-defined API files
                apiPaths = settings.value('pythonConsole/userAPI', [])
                for path in apiPaths:
                    self.api.load(path)
                self.api.prepare()
                self.lexer.setAPIs(self.api)
        elif self.lexerType == self.LEXER_R:
            # R lexer
            self.lexer = LexerR()

        self.setLexer(self.lexer)
开发者ID:Antoviscomi,项目名称:QGIS,代码行数:53,代码来源:ScriptEdit.py


注:本文中的PyQt.QtCore.QSettings类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。