Skip to content

LineEdit

Qt Base Class: QLineEdit

Signature: QLineEdit(self, arg__1: str, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None QLineEdit(self, parent: Optional[PySide6.QtWidgets.QWidget] = None) -> None

Base classes

Name Children Inherits
WidgetMixin
prettyqt.widgets.widget
QLineEdit
PySide6.QtWidgets
QLineEdit(self, arg__1: str, parent: Optional[PySide6.QtWidgets.QWidget] \= None) -> None

Subclasses

Class Module Description
ListInput prettyqt.custom_widgets.editors.listinput
IntLineEdit prettyqt.custom_widgets.editors.lineedits
FloatLineEdit prettyqt.custom_widgets.editors.lineedits
UrlLineEdit prettyqt.custom_widgets.editors.lineedits
StringListEdit prettyqt.custom_widgets.editors.lineedits

⋔ Inheritance diagram

graph TD
  1473293691168["widgets.LineEdit"]
  1473293688240["widgets.WidgetMixin"]
  1473299815024["core.ObjectMixin"]
  140713234304496["builtins.object"]
  1473245548480["gui.PaintDeviceMixin"]
  1473290611536["QtWidgets.QLineEdit"]
  1473290849680["QtWidgets.QWidget"]
  1473288842240["QtCore.QObject"]
  1473291690208["Shiboken.Object"]
  1473300082368["QtGui.QPaintDevice"]
  1473293688240 --> 1473293691168
  1473299815024 --> 1473293688240
  140713234304496 --> 1473299815024
  1473245548480 --> 1473293688240
  140713234304496 --> 1473245548480
  1473290611536 --> 1473293691168
  1473290849680 --> 1473290611536
  1473288842240 --> 1473290849680
  1473291690208 --> 1473288842240
  140713234304496 --> 1473291690208
  1473300082368 --> 1473290849680
  1473291690208 --> 1473300082368

🛈 DocStrings

Bases: WidgetMixin, QLineEdit

One-line text editor.

Source code in prettyqt\widgets\lineedit.py
class LineEdit(widgets.WidgetMixin, widgets.QLineEdit):
    """One-line text editor."""

    value_changed = core.Signal(str)
    tab_pressed = core.Signal()

    def __init__(self, *args, **kwargs):
        self._validation_color = gui.Color("orange")
        super().__init__(*args, **kwargs)
        self.textChanged.connect(self._on_value_change)

    @classmethod
    def supports(cls, instance) -> bool:
        return isinstance(instance, str)

    def _on_value_change(self):
        val = self.get_value()
        self._update_background()
        self.value_changed.emit(val)

    def __repr__(self):
        return get_repr(self, self.text())

    def __add__(self, other: str):
        self.append_text(other)
        return self

    def _get_map(self):
        maps = super()._get_map()
        maps |= {
            "echoMode": ECHO_MODE,
            "cursorMoveStyle": constants.CURSOR_MOVE_STYLE,
            "alignment": constants.ALIGNMENTS,
        }
        return maps

    def font(self) -> gui.Font:
        return gui.Font(super().font())

    def keyPressEvent(self, event):
        super().keyPressEvent(event)
        if event.key() == constants.Key.Key_Tab:
            self.tab_pressed.emit()

    def append_text(self, text: str):
        self.set_text(self.text() + text)

    def set_text(self, text: str):
        self.setText(text)

    def set_completer(self, completer: widgets.QCompleter | Literal["files"]):
        match completer:
            case widgets.QCompleter():
                self.setCompleter(completer)
            case "files":
                model = widgets.FileSystemModel()
                model.set_root_path("")
                completer = widgets.Completer(self)
                completer.setModel(model)
                self.setCompleter(completer)

    def set_read_only(self, value: bool = True):
        """Set text to read-only.

        Args:
            value: True, for read-only, otherwise False
        """
        self.setReadOnly(value)

    def set_regex_validator(
        self, regex: str, flags: int = 0
    ) -> gui.RegularExpressionValidator:
        validator = gui.RegularExpressionValidator(self)
        validator.set_regex(regex, flags)
        self.set_validator(validator)
        return validator

    def set_range(self, lower: int | None, upper: int | None):
        val = gui.IntValidator()
        val.set_range(lower, upper)
        self.set_validator(val)

    def set_validator(
        self,
        validator: gui.QValidator
        | ValidatorStr
        | datatypes.PatternType
        | Callable
        | None,
        strict: bool = True,
        empty_allowed: bool | None = None,
        append: bool = False,
        **kwargs,
    ) -> gui.QValidator:
        from prettyqt import validators

        match validator:
            case str() if "|" in validator:
                vals = [get_validator(i, **kwargs) for i in validator.split("|")]
                validator: widgets.QValidator = validators.AndValidator(vals)
            case str() | re.Pattern() | core.QRegularExpression() | Callable():
                validator = get_validator(validator, **kwargs)
            case None | gui.QValidator():
                pass
            case _:
                raise ValueError(validator)
        if empty_allowed is False:
            validator = validators.AndValidator(
                [validator, validators.NotEmptyValidator()]
            )
        elif empty_allowed is True:
            validator = validators.OrValidator([validator, validators.EmptyValidator()])
        if not strict:
            validator = validators.NotStrictValidator(validator)
        if append and (prev := widget.validator()) is not None:
            validator = validators.AndValidator([prev, validator])
        self.setValidator(validator)
        self._update_background()
        return validator

    def set_input_mask(self, mask: str):
        match mask:
            case "ip_address":
                mask = "000.000.000.000;_"
            case "mac_address":
                mask = "HH:HH:HH:HH:HH:HH;_"
            case "iso_date":
                mask = "0000-00-00"
        self.setInputMask(mask)

    def _update_background(self):
        color = None if self.hasAcceptableInput() else self._validation_color
        self.set_background_color(color)

    def set_validation_color(self, color: datatypes.ColorType):
        self._validation_color = colors.get_color(color).as_qt()

    def get_validation_color(self) -> gui.QColor:
        return self._validation_color

    def set_echo_mode(self, mode: EchoModeStr | widgets.QLineEdit.EchoMode):
        """Set echo mode.

        Args:
            mode: echo mode to use
        """
        self.setEchoMode(ECHO_MODE.get_enum_value(mode))

    def get_echo_mode(self) -> EchoModeStr:
        """Return echo mode.

        Returns:
            echo mode
        """
        return ECHO_MODE.inverse[self.echoMode()]

    def set_cursor_move_style(
        self, style: constants.CursorMoveStyleStr | constants.CursorMoveStyle
    ):
        """Set cursor move style.

        Args:
            style: cursor move style to use
        """
        self.setCursorMoveStyle(constants.CURSOR_MOVE_STYLE.get_enum_value(style))

    def get_cursor_move_style(self) -> constants.CursorMoveStyleStr:
        """Return cursor move style.

        Returns:
            cursor move style
        """
        return constants.CURSOR_MOVE_STYLE.inverse[self.cursorMoveStyle()]

    def add_action(
        self,
        action: gui.QAction,
        position: ActionPositionStr | widgets.QLineEdit.ActionPosition = "trailing",
    ):
        self.addAction(action, ACTION_POSITION.get_enum_value(position))

    def set_value(self, value: str):
        self.setText(value)

    def get_value(self) -> str:
        return self.text()

    def is_valid(self) -> bool:
        return self.hasAcceptableInput()

get_cursor_move_style() -> constants.CursorMoveStyleStr

Return cursor move style.

Source code in prettyqt\widgets\lineedit.py
def get_cursor_move_style(self) -> constants.CursorMoveStyleStr:
    """Return cursor move style.

    Returns:
        cursor move style
    """
    return constants.CURSOR_MOVE_STYLE.inverse[self.cursorMoveStyle()]

get_echo_mode() -> EchoModeStr

Return echo mode.

Source code in prettyqt\widgets\lineedit.py
def get_echo_mode(self) -> EchoModeStr:
    """Return echo mode.

    Returns:
        echo mode
    """
    return ECHO_MODE.inverse[self.echoMode()]

set_cursor_move_style(style: constants.CursorMoveStyleStr | constants.CursorMoveStyle)

Set cursor move style.

Parameters:

Name Type Description Default
style CursorMoveStyleStr | CursorMoveStyle

cursor move style to use

required
Source code in prettyqt\widgets\lineedit.py
def set_cursor_move_style(
    self, style: constants.CursorMoveStyleStr | constants.CursorMoveStyle
):
    """Set cursor move style.

    Args:
        style: cursor move style to use
    """
    self.setCursorMoveStyle(constants.CURSOR_MOVE_STYLE.get_enum_value(style))

set_echo_mode(mode: EchoModeStr | widgets.QLineEdit.EchoMode)

Set echo mode.

Parameters:

Name Type Description Default
mode EchoModeStr | EchoMode

echo mode to use

required
Source code in prettyqt\widgets\lineedit.py
def set_echo_mode(self, mode: EchoModeStr | widgets.QLineEdit.EchoMode):
    """Set echo mode.

    Args:
        mode: echo mode to use
    """
    self.setEchoMode(ECHO_MODE.get_enum_value(mode))

set_read_only(value: bool = True)

Set text to read-only.

Parameters:

Name Type Description Default
value bool

True, for read-only, otherwise False

True
Source code in prettyqt\widgets\lineedit.py
def set_read_only(self, value: bool = True):
    """Set text to read-only.

    Args:
        value: True, for read-only, otherwise False
    """
    self.setReadOnly(value)

⌗ Property table

Qt Property Type Doc
objectName QString
modal bool
windowModality Qt::WindowModality
enabled bool
geometry QRect
frameGeometry QRect
normalGeometry QRect
x int
y int
pos QPoint
frameSize QSize
size QSize
width int
height int
rect QRect
childrenRect QRect
childrenRegion QRegion
sizePolicy QSizePolicy
minimumSize QSize
maximumSize QSize
minimumWidth int
minimumHeight int
maximumWidth int
maximumHeight int
sizeIncrement QSize
baseSize QSize
palette QPalette
font QFont
cursor QCursor
mouseTracking bool
tabletTracking bool
isActiveWindow bool
focusPolicy Qt::FocusPolicy
focus bool
contextMenuPolicy Qt::ContextMenuPolicy
updatesEnabled bool
visible bool
minimized bool
maximized bool
fullScreen bool
sizeHint QSize
minimumSizeHint QSize
acceptDrops bool
windowTitle QString
windowIcon QIcon
windowIconText QString
windowOpacity double
windowModified bool
toolTip QString
toolTipDuration int
statusTip QString
whatsThis QString
accessibleName QString
accessibleDescription QString
layoutDirection Qt::LayoutDirection
autoFillBackground bool
styleSheet QString
locale QLocale
windowFilePath QString
inputMethodHints QFlags
inputMask QString
text QString
maxLength int
frame bool
echoMode QLineEdit::EchoMode
displayText QString
cursorPosition int
alignment QFlags
modified bool
hasSelectedText bool
selectedText QString
dragEnabled bool
readOnly bool
undoAvailable bool
redoAvailable bool
acceptableInput bool
placeholderText QString
cursorMoveStyle Qt::CursorMoveStyle
clearButtonEnabled bool