PrettyQt Validators.
PrettyQt ships a large number of predefined validators.
Apart from LineEdits, ComboBoxes and SpinBoxes, PlainTextEdits also gained the ability
to take a validator.
The set_validator method also gained a "strict" keyword argument, which wraps the passed
validator into a NotStrictValidator, effectively removing the "Invalid" state. That way
there never is a situation where the user input is ignored, which might be preferred in a
lot of situations.
The acceptance of "" may also be overriden explicitely by setting the "allow_empty"
keyword argument.
Validators can also be combined. The resulting CompositeValidator checks if all
containing validators accept the input.
Example:
val_1 = BlackListValidator(["Blacklisted word"])
val_2 = AlphanumericValidator()
and_validator = val_1 & val_2 # returns an AndValidator
val_1 = AlphanumericValidator()
val_2 = RegularExpressionValidator("some_regex")
or_val = val_1 | val_2 # returns an OrValidator
Validators can also be set by an id. Since everything is typed with Literals,
the possible ids should be shown by your IDE.
lineedit.set_validator("float")
AlphaNumericValidator
Bases: Validator
Validator which checks whether only alphanumeric characters are included.
Source code in prettyqt/validators/alphanumericvalidator.py
| class AlphaNumericValidator(gui.Validator):
"""Validator which checks whether only alphanumeric characters are included."""
ID = "alphanumeric"
def __eq__(self, other: object):
return isinstance(other, AlphaNumericValidator)
def validate(self, text: str, pos: int = 0):
if text.replace("_", "").isalnum():
return self.State.Acceptable, text, pos
return self.State.Invalid, text, pos
|
AndValidator
Bases: CompositeValidator
Validator to AND-combine other validators.
Source code in prettyqt/validators/compositevalidator.py
| class AndValidator(CompositeValidator):
"""Validator to AND-combine other validators."""
ID = "and"
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
vals = [v.validate(text, pos)[0] for v in self.validators] # type: ignore
if self.State.Invalid in vals:
return self.State.Invalid, text, pos
if self.State.Intermediate in vals:
return self.State.Intermediate, text, pos
return self.State.Acceptable, text, pos
|
BlacklistValidator
Bases: Validator
Validator which excludes a fixed list of strings.
Source code in prettyqt/validators/blacklistvalidator.py
| class BlacklistValidator(gui.Validator):
"""Validator which excludes a fixed list of strings."""
ID = "blacklist"
def __init__(
self,
options: list[str] | None = None,
parent: QtCore.QObject | None = None,
):
super().__init__(parent)
self._options = options or []
def __eq__(self, other: object):
return isinstance(other, BlacklistValidator) and self._options == other._options
def validate(self, text: str, pos: int = 0):
if any(option == text for option in self._options):
return self.State.Invalid, text, pos
return self.State.Acceptable, text, pos
|
ColorValidator
Bases: Validator
Validator which checks for strings representing a color.
Source code in prettyqt/validators/colorvalidator.py
| class ColorValidator(gui.Validator):
"""Validator which checks for strings representing a color."""
ID = "color"
def __eq__(self, other: object):
return isinstance(other, ColorValidator)
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
color = gui.QColor(text)
if color.isValid():
return self.State.Acceptable, text, pos
return self.State.Intermediate, text, pos
|
FloatListValidator
Bases: BaseRegexValidator
Validator which checks whether given string is a comma-separated list of floats.
Source code in prettyqt/validators/regexvalidators.py
| class FloatListValidator(BaseRegexValidator):
"""Validator which checks whether given string is a comma-separated list of floats."""
ID = "float_list"
def __init__(self, allow_single: bool = True, parent: QtCore.QObject | None = None):
super().__init__(parent=parent)
self.allow_single = allow_single
if allow_single:
self.set_regex(r"^(\s*-?\d+(\.\d+)?)(\s*,\s*-?\d+(\.\d+)?)*$")
else:
self.set_regex(
r"^(\s*-?\d+(\.\d+)?)(\s*,\s*-?\d+(\.\d+)?)(\s*,\s*-?\d+(\.\d+)?)*$"
)
def __reduce__(self):
return type(self), (self.allow_single,)
def __repr__(self):
return get_repr(self, allow_single=self.allow_single)
|
FunctionValidator
Bases: Validator
Validator which checks based on a given Callable.
Allows for quickly creating a validator without subclassing.
Source code in prettyqt/validators/functionvalidator.py
| class FunctionValidator(gui.Validator):
"""Validator which checks based on a given Callable.
Allows for quickly creating a validator without subclassing.
"""
ID = "function"
def __init__(self, fn: Callable[[str], bool], parent=None):
super().__init__(parent)
self._fn = fn
def __eq__(self, other: object):
return isinstance(other, FunctionValidator) and other._fn == self._fn
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
if self._fn(text):
return self.State.Acceptable, text, pos
return self.State.Invalid, text, pos
|
HexValidator
Bases: Validator
Validator which checks for hexadecimal values.
Source code in prettyqt/validators/hexvalidator.py
| class HexValidator(gui.Validator):
"""Validator which checks for hexadecimal values."""
ID = "hex"
def __init__(self, maximum: int | None = None, parent=None):
super().__init__(parent)
self._maximum = maximum
def __eq__(self, other: object):
return isinstance(other, HexValidator) and other._maximum == self._maximum
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
try:
val = int(text, 16)
except ValueError:
return self.State.Intermediate, text, pos
if self._maximum is not None and val > self._maximum:
return self.State.Invalid, text, pos
return self.State.Acceptable, text, pos
|
IntListValidator
Bases: BaseRegexValidator
Validator which checks whether given string is a comma-separated list of ints.
Source code in prettyqt/validators/regexvalidators.py
| class IntListValidator(BaseRegexValidator):
"""Validator which checks whether given string is a comma-separated list of ints."""
ID = "int_list"
def __init__(self, allow_single: bool = True, parent: QtCore.QObject | None = None):
super().__init__(parent=parent)
self.allow_single = allow_single
if allow_single:
self.set_regex(r"^(\d+)(,\s*\d+)*$")
else:
self.set_regex(r"^[0-9]+(,[0-9]+)+$")
def __reduce__(self):
return type(self), (self.allow_single,)
def __repr__(self):
return get_repr(self, allow_single=self.allow_single)
|
IntegerValidator
Bases: Validator
Validator to check for integer values.
In contrast to IntValidator provided by Qt, this validator is not bound to
a restricted value range.
Source code in prettyqt/validators/integervalidator.py
| class IntegerValidator(gui.Validator):
"""Validator to check for integer values.
In contrast to IntValidator provided by Qt, this validator is not bound to
a restricted value range.
"""
ID = "integer"
def __init__(
self,
bottom: int | None = None,
top: int | None = None,
parent: core.QObject | None = None,
):
super().__init__(parent)
self._bottom = -sys.maxsize if bottom is None else bottom
self._top = sys.maxsize if top is None else top
def set_range(self, lower: int | None, upper: int | None):
self.set_top(upper)
self.set_bottom(lower)
def get_range(self) -> tuple[int, int]:
return (self._bottom, self._top)
def set_bottom(self, bottom: int | None):
self._bottom = -sys.maxsize if bottom is None else bottom
def get_bottom(self) -> int:
return self._bottom
def set_top(self, top: int | None):
self._top = sys.maxsize if top is None else top
def get_top(self) -> int:
return self._top
def validate(self, text: str, pos: int):
if text in {"", "-"}:
return self.State.Intermediate, text, pos
try:
val = int(text)
except ValueError:
return self.State.Invalid, text, pos
if not text.isascii():
return self.State.Invalid, text, pos
if self._bottom <= val <= self._top:
return self.State.Acceptable, text, pos
return self.State.Invalid, text, pos
bottom = core.Property(
int,
get_bottom,
set_bottom,
doc="Minimum value",
)
top = core.Property(
int,
get_top,
set_top,
doc="Maximum value",
)
|
JsonValidator
Bases: Validator
Validator which checks for strings which can be parsed as JSON.
Source code in prettyqt/validators/jsonvalidator.py
| class JsonValidator(gui.Validator):
"""Validator which checks for strings which can be parsed as JSON."""
ID = "json"
def __eq__(self, other: object):
return isinstance(other, JsonValidator)
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
import anyenv
try:
anyenv.load_json(text)
except anyenv.JsonLoadError:
return self.State.Intermediate, text, pos
else:
return self.State.Acceptable, text, pos
|
MonotonicListValidator
Bases: Validator
Validator which checks whether given string contains a monotonic list.
Source code in prettyqt/validators/monotoniclistvalidator.py
| class MonotonicListValidator(gui.Validator):
"""Validator which checks whether given string contains a monotonic list."""
ID = "monotonic"
def __init__(self, kind: str = "increasing", parent=None):
super().__init__(parent)
self._kind = kind
def __eq__(self, other: object):
return isinstance(other, MonotonicListValidator) and other._kind == self._kind
def validate(self, string: str, pos: int) -> tuple[gui.Validator.State, str, int]:
for i, c in enumerate(string, start=1):
if c not in "+-., 0123456789":
return self.State.Invalid, string, i
if pos == len(string) >= 2 and string[-1] == " " and string[-2].isdigit(): # noqa: PLR2004
string = f"{string[:-1]}, "
pos += 1
prev = None
for valuestr in re_custom_sep.split(string.strip()):
try:
value = float(valuestr)
except ValueError:
return self.State.Intermediate, string, pos
if prev is not None and (
value <= prev if self._kind == "increasing" else value >= prev
):
return self.State.Intermediate, string, pos
prev = value
return self.State.Acceptable, string, pos
|
NotStrictValidator
Bases: Validator
Validator which turns Invalid state into Intermediate state.
Source code in prettyqt/validators/notstrictvalidator.py
| class NotStrictValidator(gui.Validator):
"""Validator which turns Invalid state into Intermediate state."""
ID = "not_strict"
def __init__(self, validator: gui.QValidator | None = None, **kwargs):
self._validator = validator
super().__init__(**kwargs)
def __eq__(self, other: object):
return (
isinstance(other, NotStrictValidator) and other._validator == self._validator
)
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
if self._validator is None:
return self.State.Acceptable, text, pos
# The PySide6 stubs type validate()'s result as `object`.
result = cast(
"tuple[gui.QValidator.State, str, int]", self._validator.validate(text, pos)
)
state, text, pos = result
is_invalid = state == self.State.Invalid
return self.State.Intermediate if is_invalid else state, text, pos
|
OrValidator
Bases: CompositeValidator
Validator to OR-combine other validators.
Source code in prettyqt/validators/compositevalidator.py
| class OrValidator(CompositeValidator):
"""Validator to OR-combine other validators."""
ID = "or"
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
vals = [v.validate(text, pos)[0] for v in self.validators] # type: ignore
if self.State.Acceptable in vals:
return self.State.Acceptable, text, pos
if self.State.Intermediate in vals:
return self.State.Intermediate, text, pos
return self.State.Invalid, text, pos
|
PathValidator
Bases: Validator
Validator which checks whether given string is a valid path.
Source code in prettyqt/validators/pathvalidator.py
| class PathValidator(gui.Validator):
"""Validator which checks whether given string is a valid path."""
ID = "path"
def __init__(self, *args, **kwargs):
self._mode: ModeStr = "any"
super().__init__(*args, **kwargs)
def __eq__(self, other: object):
return isinstance(other, PathValidator) and self._mode == other._mode
def validate(self, text: str, pos: int = 0):
if not text:
return self.State.Intermediate, text, pos
try:
path = pathlib.Path(text)
exists = path.exists()
except ValueError, OSError:
return self.State.Invalid, text, pos
if not exists:
return self.State.Intermediate, text, pos
match self._mode:
case "any":
is_valid = True
case "file":
is_valid = path.is_file()
case "folder":
is_valid = path.is_dir()
case _:
is_valid = False
state = self.State.Acceptable if is_valid else self.State.Intermediate
return state, text, pos
def set_mode(self, mode: ModeStr):
self._mode = mode
def get_mode(self) -> ModeStr:
return self._mode
mode = core.Property(
str,
get_mode,
set_mode,
doc="Whether text can be any, an existing file or an existing folder",
)
|
PythonCodeValidator
Bases: Validator
Validator which checks whether given string is valid Python code.
Source code in prettyqt/validators/pythoncodevalidator.py
| class PythonCodeValidator(gui.Validator):
"""Validator which checks whether given string is valid Python code."""
ID = "python_code"
def __eq__(self, other: object):
return isinstance(other, PythonCodeValidator)
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
try:
ast.parse(text)
except SyntaxError:
return self.State.Intermediate, text, pos
else:
return self.State.Acceptable, text, pos
|
QssValidator
Bases: Validator
Validator which checks whether given string is a parseable css string.
Source code in prettyqt/validators/qssvalidator.py
| class QssValidator(gui.Validator):
"""Validator which checks whether given string is a parseable css string."""
ID = "qss"
def __eq__(self, other: object):
return isinstance(other, QssValidator)
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
with contextlib.suppress(ValueError):
if not text or parser.parse(text):
return self.State.Acceptable, text, pos
return self.State.Intermediate, text, pos
|
RegexPatternValidator
Bases: Validator
Validator which checks whether given string is a parseable regex pattern.
Source code in prettyqt/validators/regexpatternvalidator.py
| class RegexPatternValidator(gui.Validator):
"""Validator which checks whether given string is a parseable regex pattern."""
ID = "regex_pattern"
error_occured = core.Signal(str)
pattern_updated = core.Signal(object)
def __repr__(self):
return get_repr(self)
def __eq__(self, other: object):
return isinstance(other, type(self))
def validate(self, text: str, pos: int = 0) -> tuple[gui.QValidator.State, str, int]:
# if text == "":
# self.compiled = None
# return (self.Intermediate, text, pos)
try:
compiled = re.compile(text)
except re.PatternError as e:
self.error_occured.emit(str(e))
self.pattern_updated.emit(None)
return self.State.Intermediate, text, pos
else:
self.error_occured.emit("")
self.pattern_updated.emit(compiled)
return self.State.Acceptable, text, pos
|
ScientificFloatValidator
Bases: BaseScientificValidator
This is a validator for float values represented as strings in scientific notation.
(i.e. "1.35e-9", ".24E+8", "14e3" etc.)
Also supports SI unit prefix like 'M', 'n' etc.
Source code in prettyqt/validators/scientificvalidators.py
| class ScientificFloatValidator(BaseScientificValidator):
"""This is a validator for float values represented as strings in scientific notation.
(i.e. "1.35e-9", ".24E+8", "14e3" etc.)
Also supports SI unit prefix like 'M', 'n' etc.
"""
ID = "scientific_float"
re_pattern = re.compile(
r"(\s*([+-]?)(\d+\.\d+|\.\d+|\d+\.?)([eE][+-]?\d+)?\s?([YZEPTGMkmµunpfazy]?)\s*)",
flags=re.UNICODE,
)
group_map: ClassVar = {"match": 0, "sign": 1, "mantissa": 2, "exponent": 3, "si": 4}
def validate(self, string, position): # noqa: PLR0911
stripped = string.strip()
if (
stripped in {"", "+", "-", "."}
or stripped in list("YZEPTGMkmµunpfazy")
or re.match(r"[+-]?(in$|i$)", string, re.IGNORECASE)
):
return self.State.Intermediate, string, position
# Accept input of [+-]inf. Not case sensitive.
if re.match(r"[+-]?\binf$", string, re.IGNORECASE):
return self.State.Acceptable, string.lower(), position
position = min(position, len(string))
if not (group_dict := self.get_group_dict(string)):
return (
(self.State.Intermediate, string, position)
if string[position - 1] in "eE-+." and "i" not in string.lower()
else (self.State.Invalid, "", position)
)
if group_dict["match"] == string:
return self.State.Acceptable, string, position
if string.count(".") > 1:
return self.State.Invalid, group_dict["match"], position
if string[position - 1] in "eE-+" and "i" not in string.lower():
return self.State.Intermediate, string, position
return self.State.Invalid, group_dict["match"], position
|
ScientificIntegerValidator
Bases: BaseScientificValidator
This is a validator for int values represented as strings in scientific notation.
Using engineering notation only positive exponents are allowed
(i.e. "1e9", "2E+8", "14e+3" etc.)
Also supports non-fractional SI unit prefix like 'M', 'k' etc.
Source code in prettyqt/validators/scientificvalidators.py
| class ScientificIntegerValidator(BaseScientificValidator):
"""This is a validator for int values represented as strings in scientific notation.
Using engineering notation only positive exponents are allowed
(i.e. "1e9", "2E+8", "14e+3" etc.)
Also supports non-fractional SI unit prefix like 'M', 'k' etc.
"""
ID = "scientific_integer"
re_pattern = re.compile(
r"(([+-]?\d+)([eE]\+?\d+)?\s?([YZEPTGMk])?\s*)", flags=re.UNICODE
)
group_map: ClassVar = {"match": 0, "mantissa": 1, "exponent": 2, "si": 3}
def validate(self, string, position):
if not string.strip() or string.strip() in list("YZEPTGMk"):
return self.State.Intermediate, string, position
if not (group_dict := self.get_group_dict(string)):
return self.State.Invalid, "", position
if group_dict["match"] == string:
return self.State.Acceptable, string, position
position = min(position, len(string))
if string[position - 1] in "eE-+":
return self.State.Intermediate, string, position
return self.State.Invalid, group_dict["match"], position
|
TextLengthValidator
Bases: Validator
Validator which checks whether given text has a specific length.
Source code in prettyqt/validators/textlengthvalidator.py
| class TextLengthValidator(gui.Validator):
"""Validator which checks whether given text has a specific length."""
ID = "text_length"
def __init__(
self,
minimum: int | None = None,
maximum: int | None = None,
parent: core.QObject | None = None,
):
super().__init__(parent)
self._minimum = 0 if minimum is None else minimum
self._maximum = sys.maxsize if maximum is None else maximum
def set_range(self, minimum: int | None, maximum: int | None):
self._minimum = 0 if minimum is None else minimum
self._maximum = sys.maxsize if maximum is None else maximum
def get_range(self) -> tuple[int | None, int | None]:
return (self._minimum, self._maximum)
def set_minimum(self, minimum: int | None):
self._minimum = 0 if minimum is None else minimum
def get_minimum(self) -> int:
return self._minimum
def set_maximum(self, maximum: int | None):
self._maximum = sys.maxsize if maximum is None else maximum
def get_maximum(self) -> int:
return self._maximum
def validate(self, text: str, pos: int):
if self._minimum <= len(text) <= self._maximum:
return self.State.Acceptable, text, pos
if len(text) <= self._maximum:
return self.State.Intermediate, text, pos
return self.State.Invalid, text, pos
minimum = core.Property(
int,
get_minimum,
set_minimum,
doc="Minimum text length",
)
maximum = core.Property(
int,
get_maximum,
set_maximum,
doc="Maximum text length",
)
|
WhitelistValidator
Bases: Validator
Validator which allows a fixed list of strings.
Source code in prettyqt/validators/whitelistvalidator.py
| class WhitelistValidator(gui.Validator):
"""Validator which allows a fixed list of strings."""
ID = "whitelist"
def __init__(
self,
options: list[str] | None = None,
parent: QtCore.QObject | None = None,
):
super().__init__(parent)
self._options = options or []
def __eq__(self, other: object):
return isinstance(other, WhitelistValidator) and self._options == other._options
def validate(self, text: str, pos: int = 0):
if any(option == text for option in self._options):
return self.State.Acceptable, text, pos
if any(option.startswith(text) for option in self._options):
return self.State.Intermediate, text, pos
return self.State.Invalid, text, pos
|