[Qgis-developer] idea for settings

Denis Rouzaud denis.rouzaud at gmail.com
Fri Mar 9 05:55:15 EST 2012


Thanks a lot for the tip!

On 03/09/2012 11:49 AM, Alexandre Badez wrote:
> Hi,
>
> By the way instead of:
>      if self.defaultValue.has_key(setting) is False
>
> You should write this:
>      if setting not in self.defaultValue:
>
> It's more "pythonic" and work with list, tuple, set and every things
> that implement the __contains__ method (
> http://docs.python.org/reference/datamodel.html?highlight=__contains__#object.__contains__
> )
>
> On Fri, Mar 9, 2012 at 11:42, Denis Rouzaud<denis.rouzaud at gmail.com>  wrote:
>> Hi all,
>>
>> I just wanted to share an idea I had today. In my plugins, I always had the
>> problem of never knowing the default values I had set for the settings (the
>> info being spread all over the code files), and it was always a pain to
>> change a default value (I had to search in all my files for all the calls
>> for the setting in question).
>>
>> So, I created a class with a fake inheritance of QSettings:
>>
>> class MyPluginSettings():
>>     def __init__(self):
>>         self.settings = QSettings("MyPlugin","MyPlugin")
>>
>>         self.defaultValue = {    "mySettingValue1" : 0,
>>                                 "SomeTextSetting" : "hello",
>>                                 "Value4" : 13
>>                             }
>>
>>     def value(self,setting):
>>         if self.defaultValue.has_key(setting) is False:
>>             raise NameError('MyPlugin has no setting %s' % setting)
>>         return self.settings.value(setting,self.defaultValue.get(setting))
>>
>>     def setValue(self,setting,value):
>>         if self.defaultValue.has_key(setting) is False:
>>             raise NameError('MyPlugin has no setting %s' % setting)
>>         self.settings.setValue(setting,value)
>>
>>
>> You set self.settings = MyPluginSettings() in your plugin, and when you do
>> self.settings.value("mySettingValue1"), you don't need to specify the
>> default value.
>> The class will raise an exception if you call for an undefined setting. This
>> will avoid typos in settings calls and therefore multiple definitions of the
>> same setting.
>>
>>
>> Don't know if it's useful for you, but I was quite happy with this
>> solution....
>>
>> Greetings,
>>
>> Denis
>> _______________________________________________
>> Qgis-developer mailing list
>> Qgis-developer at lists.osgeo.org
>> http://lists.osgeo.org/mailman/listinfo/qgis-developer
>
>


More information about the Qgis-developer mailing list