Python PyQt4.QtCore 模块,QSettings() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt4.QtCore.QSettings()

项目:AGT    作者:narimanInrap    | 项目源码 | 文件源码
def saveFileDialog(parent, filExt = '.shp'): 
        """Shows a save file dialog and returns the selected file path."""

        settings = QtCore.QSettings()
        key = '/UI/lastShapefileDir'
        outDir = settings.value(key)
        if filExt == '.shp':
            filter = 'Shapefiles (*.shp)'
        elif filExt == '.tif':
            filter = 'Tagged image files (*.tif)'
        else:
            filter = '*' + filExt

        SaveOutPutShapeMsg = QtGui.QApplication.translate("Utility","Save output file", None, QtGui.QApplication.UnicodeUTF8) 
        outFilePath = QtGui.QFileDialog.getSaveFileName(parent, SaveOutPutShapeMsg, outDir, filter)
        outFilePath = unicode(outFilePath)
        if outFilePath:
            root, ext = splitext(outFilePath)
            if ext.upper() != filExt.upper():
                outFilePath = root + filExt
            outDir = dirname(outFilePath)
            settings.setValue(key, outDir)
        return outFilePath
项目:j3dview    作者:blank63    | 项目源码 | 文件源码
def readSettings(self):
        settings = QtCore.QSettings()

        geometry = settings.value('geometry')
        if geometry is not None:
            self.restoreGeometry(geometry)

        state = settings.value('state')
        if state is not None:
            self.restoreState(state) #FIXME: Use versioning

        settings.beginGroup('view_settings')
        self.viewer.z_near = settings.value('z_near',25,float)
        self.viewer.z_far = settings.value('z_far',12800,float)
        self.viewer.fov = settings.value('fov',22.5,float)
        self.viewer.movement_speed = settings.value('movement_speed',10,float)
        self.viewer.rotation_speed = settings.value('rotation_speed',1,float)
        settings.endGroup()
项目:GeoWrap    作者:MACBIO    | 项目源码 | 文件源码
def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GeometryWrapper_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)


        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Geometry Wrapper')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GeometryWrapper')
        self.toolbar.setObjectName(u'GeometryWrapper')

        # listen for browse button 
        self.dlg = GeometryWrapperDialog()
        self.dlg.inButton.clicked.connect(self.setInDataset) 

    # noinspection PyMethodMayBeStatic
项目:NOFAInsert    作者:NINAnor    | 项目源码 | 文件源码
def con_info(self):
        """
        Returns a connection information from QSettings.

        :returns: A connection information dictionary.
        :rtype: dict
        """

        _con_info = {}

        for con_str in self.con_str_tpl:
            _con_info[con_str] = self.settings.value(con_str, u'')

        self.username = _con_info[self.usr_str]

        return _con_info
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def openFileDialog( self ):
        settings = QSettings()
        path = QFileDialog.getSaveFileName( self, QApplication.translate( "ExportAutoFields", "Create a JSON file" ),
            settings.value( self.autoFieldManager.settingsPrefix + "/export/dir", "", type=str ), "JSON files (*.json)" )
        if path:
            if not path.endswith( '.json' ):
                path += '.json'
            self.txtExportFile.setText( path )
            settings.setValue( self.autoFieldManager.settingsPrefix + "/export/dir", os.path.dirname( path ) )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def test01CreateEnabledAutoField( self ):
        """ QSettings should be properly stored, AutoField should be enabled """
        self.msg.show( "Info! Test 1 started", 'info', True )

        self.autoFieldManager.createAutoField(
            layer=self.layer, 
            fieldName=u'f1', 
            expression=u'$x'
        )

        dictTmpProperties = self.readStoredSettings( self.layer, u'f1' )      
        dictExpectedProperties = {
            'layer':self.layerPath,
            'field':u'f1',
            'expression':u'$x',
            'layer2':"",
            'field2':"",
            'enabled':True
        }

        self.assertEqual( dictTmpProperties, dictExpectedProperties )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def checkAndEnableAutoFieldsForLayers( self, mapLayers ):
        """ After a notification on layers being added, check and enable AutoFields if needed.
            1. Check if added layers are part of currently disabled AutoFields
            2. Enable it in Dict
            3. Enable it in QSettings
            4. Connect its SIGNALS / SLOTS
        """
        for layer in mapLayers:
            for autoFieldId in self.dictAutoFields:
                if self.dictAutoFields[autoFieldId]['enabled'] == False: # Don't check enabled AutoFields
                    if self.compareLayersPublicSources( layer.publicSource(), self.dictAutoFields[autoFieldId]['layer'] ): #1
                        self.dictAutoFields[autoFieldId]['layerId'] = layer.id()
                        if self.validateAutoField( self.dictAutoFields[autoFieldId] ):
                            self.dictAutoFields[autoFieldId]['enabled'] = True #2
                            self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                            self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )#4   
                            self.autoFieldEnabled.emit( autoFieldId )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def checkAndEnableAutoFieldsForLayerFields( self, layerId, fields ):
        """ After a notification on fields being added, check and enable AutoFields if needed.
            1. Check if added fields are part of currently disabled AutoFields
            2. Enable it in Dict
            3. Enable it in QSettings
            4. Connect its SIGNALS / SLOTS 
        """
        for autoFieldId in self.dictAutoFields: 
            if self.dictAutoFields[autoFieldId]['enabled'] == False: # Don't check enabled AutoFields
                if 'layerId' in self.dictAutoFields[autoFieldId]: 
                    if layerId == self.dictAutoFields[autoFieldId]['layerId']: #1
                        for field in fields:
                            if field.name() == self.dictAutoFields[autoFieldId]['field']: 
                                if self.validateAutoField( self.dictAutoFields[autoFieldId] ):
                                    self.dictAutoFields[autoFieldId]['enabled'] = True #2
                                    self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                                    self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )#4   
                                    self.autoFieldEnabled.emit( autoFieldId )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def checkAndDisableAutoFieldsForLayer( self, layerId ):
        """ After a notification on fields being removed, check and disable AutoFields if needed.
            1. Check if any field is missing in AutoFields set for this layer.
            2. Disable it in Dict
            3. Disable it in QSettings
            4. Disconnect its SIGNAL / SLOTS   
         """
        for autoFieldId in self.dictAutoFields:
            if self.dictAutoFields[autoFieldId]['enabled'] == True: # Don't check disabled AutoFields
                if layerId == self.dictAutoFields[autoFieldId]['layerId']:       
                    layer = QgsMapLayerRegistry.instance().mapLayer( layerId )    
                    if layer.fieldNameIndex( self.dictAutoFields[autoFieldId]['field'] ) == -1: #1
                        self.dictAutoFields[autoFieldId]['enabled'] = False #2
                        self.writeAutoField( autoFieldId, self.dictAutoFields[autoFieldId] ) #3
                        self.eventManager.removeEventsForAutoField( autoFieldId, layer, self.dictAutoFields[autoFieldId]['expression'] ) #4
                        self.autoFieldDisabled.emit( autoFieldId )
项目:AGT    作者:narimanInrap    | 项目源码 | 文件源码
def openFileDialog(parent, fileFilter, message):
        """Shows an open file dialog and returns the selected file path."""

        settings = QtCore.QSettings()
        key = '/UI/lastShapefileDir'
        workDir = settings.value(key)
        filter = fileFilter
        OpenInputShapeMsg = QtGui.QApplication.translate("Utility", message, None, QtGui.QApplication.UnicodeUTF8) 
        inFilePath = QtGui.QFileDialog.getOpenFileName(parent, OpenInputShapeMsg, workDir, filter)
        inFilePath = unicode(inFilePath)
        if inFilePath:
            #  root, ext = splitext(inFilePath)
            # if ext.upper() != '.SHP':
            #    inFilePath = '%s.shp' % inFilePath
            workDir = dirname(inFilePath)
            settings.setValue(key, workDir)
        return inFilePath

    # Adopted from 'fTools Plugin', Copyright (C) 2009  Carson Farmer
项目:QGIS-CKAN-Browser    作者:BergWerkGIS    | 项目源码 | 文件源码
def get_proxies(self):
        s = QSettings()
        # if user has never clicked on proxy settings in GUI,
        # this settings does not even exist -> default to 'false'
        proxy_enabled = s.value('proxy/proxyEnabled', 'false')
        proxy_type = s.value('proxy/proxyType', '')
        proxy_host = s.value('proxy/proxyHost', '')
        proxy_port = s.value('proxy/proxyPort', '')
        proxy_user = s.value('proxy/proxyUser', None)
        proxy_password = s.value('proxy/proxyPassword', None)
        if proxy_enabled == 'false' or not proxy_enabled:
            return False, None
        if proxy_type == 'HttpProxy':
            proxy_string = ''
            if proxy_user is not None and proxy_password is not None\
                    and proxy_user != '' and proxy_password != '':
                proxy_string += proxy_user + ':' + proxy_password + '@'
            proxy_string += proxy_host + ':' + proxy_port
            #print proxy_string
            return True, {
                'http': 'http://' + proxy_string,
                'https': 'https://' + proxy_string
            }
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def initFrame(self):
        # window banner
        self.setWindowIcon(
            QtGui.QIcon(
                QtGui.QPixmap('resources/icons/olive.png')))



        # restoring windows and toolbars geometry
        settings = QtCore.QSettings()
        if len(settings.value("overviewColumnWidths").toString()) > 0:
            self.restoreGeometry(settings.value("geometry").toByteArray())
            self.restoreState(settings.value("windowState").toByteArray())
            self.overview.setColumnWidthsFromString(
                settings.value("overviewColumnWidths").toString())
        else:
            # first run
            self.setGeometry(32, 32, 32, 32)
项目:MK8-Editor    作者:TheKoopaKingdom    | 项目源码 | 文件源码
def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setWindowTitle("MK8-Editor")
        self.setGeometry(100,100,1080,720)

        self.setupMenu()

        self.qsettings = QtCore.QSettings("MrRean / RoadrunnerWMC","MK8 YAML Editor")
        self.restoreGeometry(self.qsettings.value("geometry").toByteArray())
        self.restoreState(self.qsettings.value("windowState").toByteArray())

        self.gamePath = self.qsettings.value('gamePath').toPyObject()
        if not self.isValidGameFolder(self.gamePath):
            self.changeGamePath(True)


        self.settings = SettingsWidget(self)
        self.setupGLScene()
        self.resizeWidgets()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.updateCamera)
        self.timer.start(30)

        self.show()
项目:isochrones    作者:Samweli    | 项目源码 | 文件源码
def save_state(self):
        """ Store current state of GUI to configuration file """
        settings = QSettings()

        settings.setValue('database', self.database.text())
        settings.setValue('host', self.host.text())
        settings.setValue('port', self.port.text())
        settings.setValue('user_name', self.user_name.text())
        settings.setValue('network_table', self.network_table.text())
        settings.setValue(
            'network_geom_column',
            self.network_geom_column.text())
        settings.setValue(
            'network_id_column',
            self.network_id_column.text())
        settings.setValue('catchment_table', self.catchment_table.text())
        settings.setValue(
            'catchment_geom_column',
            self.catchment_geom_column.text())
        settings.setValue(
            'catchment_id_column',
            self.catchment_id_column.text())
        settings.setValue(
            'contour_interval',
            self.contour_interval.text())
项目:qgis_resources_sharing    作者:akbargumbira    | 项目源码 | 文件源码
def fetch_online_directories(self):
        """Fetch online directory of repositories."""
        downloader = NetworkManager(self.DIRECTORY_URL)
        status, _ = downloader.fetch()
        if status:
            directory_file = QTemporaryFile()
            if directory_file.open():
                directory_file.write(downloader.content)
                directory_file.close()

            with open(directory_file.fileName()) as csv_file:
                reader = csv.DictReader(csv_file, fieldnames=('name', 'url'))
                for row in reader:
                    self._online_directories[row['name']] = row['url'].strip()
            # Save it to cache
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            settings.setValue('online_directories', self._online_directories)
            settings.endGroup()
        else:
            # Just use cache from previous use
            settings = QSettings()
            settings.beginGroup(repo_settings_group())
            self._online_directories = settings.value('online_directories', {})
            settings.endGroup()
项目:qgis_resources_sharing    作者:akbargumbira    | 项目源码 | 文件源码
def uninstall(self):
        """Uninstall the SVGs from QGIS."""
        # Remove from the searchPaths if the dir empty of collection
        settings = QSettings()
        search_paths_str = settings.value('svg/searchPathsForSVG')
        if not search_paths_str:
            search_paths = []
        else:
            search_paths = search_paths_str.split('|')

        collection_directories = os.listdir(local_collection_path())

        if len(collection_directories) == 0:
            if local_collection_path() in search_paths:
                search_paths.remove(local_collection_path())

        settings.setValue('svg/searchPathsForSVG', '|'.join(search_paths))
项目:GkukanMusiumdb    作者:matsu-reki    | 项目源码 | 文件源码
def createRubberBand(self, geomType):
        settings = QSettings()

        rb = QgsRubberBand(self.canvas, geomType)
        rb.setWidth(settings.value('/qgis/digitizing/line_width', 1, type=int))
        color = QColor(settings.value('/qgis/digitizing/line_color_red', 255, type=int),
                       settings.value('/qgis/digitizing/line_color_green', 0, type=int),
                       settings.value('/qgis/digitizing/line_color_blue', 0, type=int))
        alpha = settings.value('/qgis/digitizing/line_color_alpha', 200, type=int) / 255.0
        color.setAlphaF(alpha)
        rb.setColor(color)
        return rb
项目:GkukanMusiumdb    作者:matsu-reki    | 项目源码 | 文件源码
def _highlightLandmark(self):
        self._clearHighlight()

        self.highlight = QgsHighlight(self.canvas, self.info[1].geometry(), self.info[0])

        settings = QSettings()
        color = QColor(settings.value('/Map/highlight/color', QGis.DEFAULT_HIGHLIGHT_COLOR.name()))
        alpha = settings.value('/Map/highlight/colorAlpha', QGis.DEFAULT_HIGHLIGHT_COLOR.alpha(), type=int)
        buffer = settings.value('/Map/highlight/buffer', QGis.DEFAULT_HIGHLIGHT_BUFFER_MM, type=float)
        minWidth = settings.value('/Map/highlight/minWidth', QGis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM, type=float)

        self.highlight.setColor(color)
        color.setAlpha(alpha)
        self.highlight.setFillColor(color)
        self.highlight.setBuffer(buffer);
        self.highlight.setMinWidth(minWidth)
        self.highlight.show()
项目:j3dview    作者:blank63    | 项目源码 | 文件源码
def writeSettings(self):
        settings = QtCore.QSettings()

        settings.setValue('geometry',self.saveGeometry())
        settings.setValue('state',self.saveState())

        settings.beginGroup('view_settings')
        settings.setValue('z_near',self.viewer.z_near)
        settings.setValue('z_far',self.viewer.z_far)
        settings.setValue('fov',self.viewer.fov)
        settings.setValue('movement_speed',self.viewer.movement_speed)
        settings.setValue('rotation_speed',self.viewer.rotation_speed)
        settings.endGroup()
项目:qgis-shapetools-plugin    作者:NationalSecurityAgency    | 项目源码 | 文件源码
def __init__(self, iface, parent):
        super(GeodesicMeasureDialog, self).__init__(parent)
        self.setupUi(self)
        self.iface = iface
        self.canvas = iface.mapCanvas()
        settings = QSettings()

        self.restoreGeometry(settings.value("ShapeTools/MeasureDialogGeometry",
                                        QByteArray(), type=QByteArray))
        self.closeButton.clicked.connect(self.closeDialog)
        self.newButton.clicked.connect(self.newDialog)

        self.unitsComboBox.addItems(UNITS)

        self.tableWidget.setColumnCount(3)
        self.tableWidget.setSortingEnabled(False)
        self.tableWidget.setHorizontalHeaderLabels(['Heading To', 'Heading From', 'Distance'])

        self.unitsComboBox.activated.connect(self.unitsChanged)

        self.capturedPoints = []
        self.distances = []
        self.geod = Geodesic.WGS84
        self.activeMeasuring = True
        self.unitsChanged()
        self.currentDistance = 0.0

        color = QColor(222, 167, 67, 150)
        self.pointRb = QgsRubberBand(self.canvas, QGis.Point)
        self.pointRb.setColor(color)
        self.pointRb.setIconSize(10)
        self.lineRb = QgsRubberBand(self.canvas, QGis.Line)
        self.lineRb.setColor(color)
        self.lineRb.setWidth(3)
        self.tempRb = QgsRubberBand(self.canvas, QGis.Line)
        self.tempRb.setColor(color)
        self.tempRb.setWidth(3)
项目:qgis-shapetools-plugin    作者:NationalSecurityAgency    | 项目源码 | 文件源码
def closeDialog(self):
        self.clear()
        QSettings().setValue(
            "ShapeTools/MeasureDialogGeometry", self.saveGeometry())
        self.close()
项目:qgis-shapetools-plugin    作者:NationalSecurityAgency    | 项目源码 | 文件源码
def readSettings(self):
        '''Load the user selected settings. The settings are retained even when
        the user quits QGIS.'''
        qset = QSettings()
        self.guessNames = int(qset.value('/ShapeTools/GuessNames', 2))
        self.maxSegLength =  float(qset.value('/ShapeTools/MaxSegLength', 20.0)) # In km
        self.maxSegments =  int(qset.value('/ShapeTools/MaxSegments', 1000))
项目:qgis-shapetools-plugin    作者:NationalSecurityAgency    | 项目源码 | 文件源码
def accept(self):
        '''Accept the settings and save them for next time.'''
        qset = QSettings()
        qset.setValue('/ShapeTools/GuessNames', self.guessCheckBox.checkState())
        qset.setValue('/ShapeTools/MaxSegments', self.maxSegmentsSpinBox.value())
        qset.setValue('/ShapeTools/MaxSegLength', self.segLengthSpinBox.value())
        settings.readSettings()
        self.close()
项目:quartz-browser    作者:ksharindam    | 项目源码 | 文件源码
def importCookies(self):
        """ Window object must contain QSetting object 'self.settings' before calling this"""
        settings = QtCore.QSettings('quartz-browser', 'cookies', self)
        cookiesValue = settings.value("Cookies", QtCore.QByteArray()).toByteArray()
        cookiesList = QtNetwork.QNetworkCookie.parseCookies(cookiesValue)
        self.setAllCookies(cookiesList)
项目:quartz-browser    作者:ksharindam    | 项目源码 | 文件源码
def exportCookies(self):
        cookiesArray = QtCore.QByteArray()
        cookieList = self.allCookies()
        for cookie in cookieList:
            cookiesArray.append( cookie.toRawForm() + "\n" )
        settings = QtCore.QSettings('quartz-browser', 'cookies', self)
        settings.setValue("Cookies", cookiesArray)
项目:linkchecker-gui    作者:linkcheck    | 项目源码 | 文件源码
def __init__ (self, base, appname):
        """Initialize a QSettings object."""
        self.settings = QtCore.QSettings(base, appname)
项目:linkchecker-gui    作者:linkcheck    | 项目源码 | 文件源码
def sync (self):
        """Synchronize QSettings object to disk."""
        self.settings.sync()
项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
def savePro(self):
        from os.path import expanduser
        path = QtGui.QFileDialog.getSaveFileName(self, 'Save Profile',  expanduser("./"), 'INI(*.ini)')
        if path:
            sections = path.split('.')
            if(sections[-1]!='ini'):path+='.ini'
            saveProfile.guisave(self, QtCore.QSettings(path, QtCore.QSettings.IniFormat))
项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
def saveSelectedPro(self,parent):
        from os.path import expanduser
        path = QtGui.QFileDialog.getSaveFileName(self, 'Save Profile',  expanduser("./"), 'INI(*.ini)')
        sections = path.split('.')
        if(sections[-1]!='ini'):path+='.ini'
        print ('custom save',path)
        if path: saveProfile.guisave(parent, QtCore.QSettings(path, QtCore.QSettings.IniFormat))
项目:pslab-desktop-apps    作者:fossasia    | 项目源码 | 文件源码
def loadPro(self):
        from os.path import expanduser
        filename = QtGui.QFileDialog.getOpenFileName(self,  "Load a Profile", expanduser("."), 'INI(*.ini)')
        if filename :
            saveProfile.guirestore(self, QtCore.QSettings(filename, QtCore.QSettings.IniFormat))
项目:NOFAInsert    作者:NINAnor    | 项目源码 | 文件源码
def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        psycopg2.extras.register_uuid()

        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        self.org = u'NINA'
        self.app_name = u'NOFAInsert'

        self.settings = QSettings(self.org, u'NOFA')

        self.host_str = u'host'
        self.port_str = u'port'
        self.db_str = u'database'
        self.usr_str = u'user'
        self.pwd_str = u'password'

        self.con_str_tpl = (
            self.host_str,
            self.port_str,
            self.db_str,
            self.usr_str,
            self.pwd_str)

        self.sel_str = u'Select'
        self.none_str = str(None)
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def printFeatureAddedMessage( self, layer, featureId ):        
        """ SLOT to print a warning message letting the users know they must 
            save in order to see calculated values when a feature is added.        
        """
        if self.iface:
            settings = QSettings()
            showMessage = settings.value( self.settingsPrefix + "/showMessageFeatureAdded", True, type=bool )         
            if showMessage:
                self.msg.showWithButton( QApplication.translate( "EventManager", 
                        "When adding NEW features, you'll only see AutoField updates AFTER you SAVE your edits." ), 
                    QApplication.translate( "EventManager", "Don't show this anymore" ),
                    self.featureAddedMessageButtonAction,
                    'info' )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def featureAddedMessageButtonAction( self ):
        """ SLOT (logic) for the pressed SIGNAL button of a messagebar. """
        self.msg.show( "[Info] 'Don't show this anymore' button was clicked. This logging message should only be seen once.", 'info', True )        
        settings = QSettings()
        settings.setValue( self.settingsPrefix + "/showMessageFeatureAdded", False )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def layersAddedEnableAutoFields( self, mapLayers ): # QgsMapLayer
        """ Some layers were added, check if some AutoFields should be enabled """
        # As the enabled status must be updated in both QSettings and dict, 
        # let proper module know it's time to do so.
        self.layersAddedCheckIfAutoFields.emit( mapLayers )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def layersRemovedDisableAutoFields( self, layerIds ):
        """ Some layers were removed, disable all their AutoFields. 
            Since the layers objects are being destroyed, no need to disconnect 
            AutoFields events.
        """       
        # As the disabled status must be updated in both QSettings and dict, 
        # let the proper module know it's time to do so.
        self.autoFieldsReadyToBeDisabled.emit( layerIds )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def readStoredSettings( self, layer, fieldName ):
        """ Helper function to get a dictionary of stored QSettings for an AutoField """
        dictTmpProperties = {}
        autoFieldId = self.autoFieldManager.buildAutoFieldId( layer, fieldName )
        self.settings.beginGroup('/AutoFieldsTest/data/' + autoFieldId)
        dictTmpProperties['layer'] = self.settings.value( "layer", "", type=str )
        dictTmpProperties['field'] = self.settings.value( "field", u"", type=unicode )
        dictTmpProperties['expression'] = self.settings.value( "expression", u"", type=unicode )
        dictTmpProperties['layer2'] = self.settings.value( "layer2", "", type=str )
        dictTmpProperties['field2'] = self.settings.value( "field2", "", type=str )            
        dictTmpProperties['enabled'] = self.settings.value( "enabled", False, type=bool )
        self.settings.endGroup()

        return dictTmpProperties
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def test09RemoveAutoField( self ):
        """ QSettings should be deleted for the removed AutoField """
        self.msg.show( "Info! Test 9 started", 'info', True )

        # test07 deletes the layer object, so create it again
        self.layer = QgsVectorLayer( self.layerPath, 'puntos', 'ogr' )
        autoFieldId = self.autoFieldManager.buildAutoFieldId( self.layer, u'f1')
        self.autoFieldManager.removeAutoField( autoFieldId )
        dictTmpProperties = self.readStoredSettings( self.layer, u'f1' ) 

        self.assertEqual( dictTmpProperties, {'layer':"",'field':"",'expression':"",'layer2':"",'field2':"",'enabled':False} )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def __init__( self, messageManager, iface, settingsPrefix="/AutoFields", organizationName=None, applicationName=None ):
        QObject.__init__( self )
        self.msg = messageManager
        self.settings = QSettings( organizationName, applicationName ) if organizationName and applicationName else QSettings()
        self.dictAutoFields = OrderedDict()
        self.settingsPrefix = settingsPrefix
        self.eventManager = EventManager( self.msg, iface, settingsPrefix )
        self.eventManager.layersAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayers )
        self.eventManager.autoFieldsReadyToBeDisabled.connect( self.disableAutoFields )
        self.eventManager.attributesAddedCheckIfAutoFields.connect( self.checkAndEnableAutoFieldsForLayerFields )
        self.eventManager.attributesDeletedCheckIfAutoFields.connect( self.checkAndDisableAutoFieldsForLayer )

        self.eventManager.setAFM( self )

        self.fieldCalculator = FieldCalculator( self.msg, iface )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def overwriteAutoField( self, layer, fieldName, expression, layer2="", field2="", calculateOnExisting=True ):
        """ Logic to overwrite an existing AutoField in both QSettings and dictAutoFields """ 
        autoFieldId = self.buildAutoFieldId( layer, fieldName ) 
        if autoFieldId in self.dictAutoFields:
            self.removeAutoField( autoFieldId )        
            return self.createAutoField( layer, fieldName, expression, layer2, field2, calculateOnExisting )

        return False
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def readAutoFields( self ):
        """ Read AutoFields from QSettings, overwriting dictAutoFields """
        self.dictAutoFields = OrderedDict()
        dictTempAutoFields = {} # We will sort it when everything is read
        self.settings.beginGroup( self.settingsPrefix + "/data" )
        autoFieldsIds = self.settings.childGroups()
        self.settings.endGroup()
        for autoFieldId in autoFieldsIds:
            dictTmpProperties = {}
            self.settings.beginGroup( self.settingsPrefix + "/data/" + autoFieldId )
            dictTmpProperties['layer'] = self.settings.value( "layer", u"", type=unicode )
            dictTmpProperties['field'] = self.settings.value( "field", u"", type=unicode )
            dictTmpProperties['expression'] = self.settings.value( "expression", u"", type=unicode )
            dictTmpProperties['layer2'] = self.settings.value( "layer2", "", type=str )
            dictTmpProperties['field2'] = self.settings.value( "field2", "", type=str )            
            dictTmpProperties['order'] = self.settings.value( "order", 0, type=int )  
            self.settings.endGroup()

            # Check whether the AutoField must be enabled or not
            layer = self.getLayer( dictTmpProperties['layer'] )
            if layer:
                dictTmpProperties['layerId'] = layer.id()

            dictTmpProperties['enabled'] = self.validateAutoField( dictTmpProperties )

            dictTempAutoFields[autoFieldId] = dictTmpProperties


        # We need to set events in order of creation, so that the use case of
        #   AutoFields depending on other AutoFields becomes predictable    
        self.dictAutoFields = OrderedDict( sorted( dictTempAutoFields.items(), 
                                            key=lambda d: d[1]['order'] ) )

        for autoFieldId in self.dictAutoFields.keys():
            self.eventManager.setEventsForAutoField( autoFieldId, self.dictAutoFields[autoFieldId] )
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def writeAutoField( self, autoFieldId, dictProperties ):
        """ Write an AutoField from dictAutoFields to QSettings """
        self.settings.beginGroup( self.settingsPrefix + "/data/" + autoFieldId )
        self.settings.setValue( "layer", dictProperties['layer'] )
        self.settings.setValue( "field", dictProperties['field'] )
        self.settings.setValue( "expression", dictProperties['expression'] )
        self.settings.setValue( "layer2", dictProperties['layer2'] )
        self.settings.setValue( "field2", dictProperties['field2'] )
        self.settings.setValue( "enabled", dictProperties['enabled'] )
        self.settings.setValue( "order", dictProperties['order'] )
        self.settings.endGroup()
        self.settings.sync()
项目:AutoFields    作者:gacarrillor    | 项目源码 | 文件源码
def saveCalculateOnExistingPreference( self, status ):
        """ Saves the preference in QSettings """
        settings = QSettings()
        settings.setValue( self.autoFieldManager.settingsPrefix + "/calculateOnExistingFeatures" , status )
项目:dxf2gcode    作者:cnc-club    | 项目源码 | 文件源码
def writeSettings(self):
        settings = QtCore.QSettings("dxf2gcode", "dxf2gcode")
        settings.beginGroup("MainWindow")
        settings.setValue("size", self.size())
        settings.setValue("pos", self.pos())
        settings.endGroup()
项目:AGT    作者:narimanInrap    | 项目源码 | 文件源码
def getDefaultEncoding(default = 'System'):
        """Returns the default encoding. static"""

        settings = QSettings()
        return settings.value('/UI/encoding', default)
项目:AGT    作者:narimanInrap    | 项目源码 | 文件源码
def setDefaultEncoding(encoding):
        """Sets the default encoding. static"""

        # Make sure encoding is not blank.
        encoding = encoding or 'System'
        settings = QSettings()
        settings.setValue('/UI/encoding', encoding)
项目:QGIS-CKAN-Browser    作者:BergWerkGIS    | 项目源码 | 文件源码
def load(self):
        qgis_settings = QSettings()
        self.cache_dir = qgis_settings.value(self.KEY_CACHE_DIR, '')
        if self.cache_dir is None:
            self.cache_dir = ''
#         self.ckan_url = qgis_settings.value(self.KEY_CKAN_API, 'http://ckan.data.ktn.gv.at/api/3/action/')
        self.ckan_url = qgis_settings.value(self.KEY_CKAN_API, '')
        if self.ckan_url is None:
            self.ckan_url = ''
项目:QGIS-CKAN-Browser    作者:BergWerkGIS    | 项目源码 | 文件源码
def save(self):
        qgis_settings = QSettings()
        qgis_settings.setValue(self.KEY_CACHE_DIR, self.cache_dir)
        qgis_settings.setValue(self.KEY_CKAN_API, self.ckan_url)
项目:qgis-earthengine-plugin    作者:gena    | 项目源码 | 文件源码
def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'GoogleEarthEnginePlugin_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&Google Earth Engine')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'GoogleEarthEngine')
        self.toolbar.setObjectName(u'GoogleEarthEngine')

        self.pluginIsActive = False
        self.dock_widget = None

    # noinspection PyMethodMayBeStatic
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def closeEvent(self, event):
        if not self.doDirtyCheck():
            event.ignore()
            return
        settings = QtCore.QSettings()
        settings.setValue("geometry", self.saveGeometry())
        settings.setValue("windowState", self.saveState())
        settings.setValue(
            "overviewColumnWidths",
            self.overview.getColumnWidths())

        self.chessBox.sync()
        Conf.write()
        event.accept()
项目:ee-book    作者:ee-book    | 项目源码 | 文件源码
def closeEvent(self, event):
        settings = QSettings()
        settings.setValue("MainWindow/Size", QVariant(self.size()))
        settings.setValue("MainWindow/Position", QVariant(self.pos()))
        settings.setValue("MainWindow/State", QVariant(self.saveState()))