How to get a boolean value from QSettings correctly?
-
How to get a boolean value from QSettings correctly without helper function?
Value is 'str' if setting key is defined
Value is 'bool' if default value is True
Value is 'NoneType' if default value is Falsedef readSettings(self): settings = QSettings() showTitle = self.valueToBool(settings.value('Settings/showTitle', True)) def valueToBool(self, value): if type(value) is str: return True if value == 'true' else False elif value is None: return False else: return value
Pyside2 5.13.1 on Manjaro
-
@NonNT
I thought about this for a while! I claim there is not a perfect solution to your case which obeys your rules, is an in-liner (short, and using only Python in-builts), does not raise an exception, does not use regular expressions and does not evaluate the expression more than once. :)The best I can come up with which obeys these is:
str(expr) in ['true', '1']
Obviously this means that only entries of
true
or1
are true, everything else (includingNone
, the empty string (''
) and e.g.0
or2
or1.0
). You could also acceptTrue
orTRUE
withstr(expr).lower() ...
.Having said that, most people would write a function, and that allows us to reference the
value
parameter more than once. The shortest I would offer is:@staticmethod def valueToBool(value): return value.lower() == 'true' if isinstance(value, str) else bool(value)
This treats, say,
2
or1.0
as true rather than false, unlike the in-liner. Which behaviour you prefer for such a case is probably a matter of taste!A lot of Pythonistas would write the function multi-line to use
int(value)
inside atry ... except ...
. Personally I don't like multi-lines where one would suffice and I just don't like raising exceptions in the way they are fond of, but that's up to you. In any case this would be the opposite of what you are asking for. -
@JonB
It looks great. Thanksdef writeSettings(self): showTitle = self.showTitleCheckBox.isChecked() settings = QSettings() settings.setValue('Settings/showTitle', showTitle) def readSettings(self): settings = QSettings() showTitle = self.valueToBool(settings.value('Settings/showTitle', True)) self.showTitleCheckBox.setChecked(showTitle) @staticmethod def valueToBool(value): return value.lower() == 'true' if isinstance(value, str) else bool(value)
-
@NonNT said in How to get a boolean value from QSettings correctly?:
It looks great.
time to mark your post as solved then? Thanks.
-
To make sure results are consistent and repeatable clear the settings before setting them.
settings.clear() settings.setValue("Settings/showTitle", False) print(settings.value("Settings/showTitle", type=bool)
This solution works on macOS and Windows.
The other thing to be careful about when working cross platform is always use the same case for keys and never use case to differentiate two keys. Windows init file is case insensitive while macOS is case sensitive.
-
PySide also let's you specify a type: