Skip to content

PathValidator

Base classes

Name Children Inherits
Validator
prettyqt.gui.validator

⋔ Inheritance diagram

graph TD
  2130042539["validators.PathValidator"]
  422589614["gui.Validator"]
  1804432572["gui.ValidatorMixin"]
  3227531497["core.ObjectMixin"]
  2751680898["builtins.object"]
  49520861["QtGui.QValidator"]
  3984060476["QtCore.QObject"]
  37984305["Shiboken.Object"]
  422589614 --> 2130042539
  1804432572 --> 422589614
  3227531497 --> 1804432572
  2751680898 --> 3227531497
  2751680898 --> 1804432572
  49520861 --> 422589614
  3984060476 --> 49520861
  37984305 --> 3984060476
  2751680898 --> 37984305

🛈 DocStrings

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",
    )

:fa-brands-github: Show source on GitHub