scientific_spinbox.widget

Widget module.

Provides the widget and implements all logic related to the User Interface (UI), graphical elements, and related resources.

Since:

2024/02/06

Authors:
class ScientificSpinBox(*args, thousand_separators: bool = True, default_decimals: int = 2, default_value: Decimal = Decimal('0'), allowed_units: list[str] | str | None = None, preferred_units: list[str] | str | None = None, display_unit: str = '', enable_tooltip: bool = True, base_unit: str = '', backend_interface: PintInterface | None = None, **kwargs)[source]

Bases: QDoubleSpinBox

A Qt5 Widget to manipulate physical quantities with ease.

Note

  • When working with units, an unit being ‘’ means it’s dimensionless.

  • The baseQuantityChanged and baseValueChanged signals can be used to track changes in the base unit. They are emitted after editing is finished.

  • The valueChanged signal is only emitted after editing is finished.

  • The textChanged signal is only emitted after editing is finished.

Todo

  • implement the use of self._internalDecimalSeparator = ‘.’

Parameters:
thousand_separators : bool

if True, uses thousand separators when showing the text. Defaults to False.

default_decimals : int

number of decimals to show by default. Defaults to 2.

default_value : Decimal

default value of the widget. Defaults to 0.

allowed_units : List[str]

list of allowed units. If provided, enables the ‘allowed units’ feature. Can’t be used with ‘preferred units’ feature. Defaults to None.

preferred_units : List[str]

list of preferred units. If provided, enables the preferred units feature. Can’t be used with allowed units feature. Defaults to None.

display_unit : str

unit which will be used to display on the spinbox. If using the ‘preferred units’ or ‘allowed units’ features, the features units array must contain the display_unit. Defaults to '' (dimensionless).

enable_tooltip : bool

if False, disables showing tooltips when error occurs. Defaults to True.

base_unit : str

base unit in which the value will be stored on baseQuantity property. If base_unit=’’, allows only dimensionless values. Defaults to '' (dimensionless).

backend_interface : PintInterface

the backend interface object to use. Defaults to None.

addSeparators(text)[source]

Formats text as internal text with internal separators.

Uses ScientificInputValidator to get named captured groups from the provided text.

Parameters:
text : str

current text.

Returns:

text with internal separators.

Return type:

str

blockSignals(block: bool) None[source]

Blocks the signals.

Parameters:
block : bool

True to block the signals and False to unblock.

cleanText() str[source]

Returns only the numeric part of the displayed text.

clearErrorColor() None[source]

Sets the lineEdit text color to black.

Sets the isInputError property to false and updates the lineEdit style.

clearToolTip() None[source]

Hides the tooltip.

convertInternalToText(text: str) str[source]

Converts the internal representation to the user’s representation.

Parameters:
text : str

text formatted in internal representation.

Returns:

text formatted in user representation.

Return type:

str

correctCursorPosition(pre_position, is_step_by: bool = False, is_editing_finished: bool = False)[source]

Corrects the cursor position considering special cases.

If the is_step_by flag is True, does the following:
  1. if it was at the right-side of an unit, decimal or thousand

    separator, moves the cursor to the left-side of separator.

  2. if the cursor was after the numeric part, moves it to the

    right-side of the last character of the numeric part.

  3. if the cursor is at the left-side of the numeric part, on

    the signal place, moves it to the right-side of the first character of the numeric part.

If the is_step_by flag is False, does the following:
  1. if the cursor was at the right-side of the unit separator,

    moves it to the left-side of unit separator.

  2. if the cursor was at the right-side of the last character of

    the text, moves it to the right-side of the last character of the numeric part.

Parameters:
pre_position : int

position of the cursor before correction.

is_step_by : bool, optional

if True, considers it was called from a stepBy and handles differently. Defaults to False.

is_editing_finished : bool, optional

flag to know if the function was called inside onEditingFinished and handle it differently. Defaults to False.

Returns:

new cursor position.

Return type:

int

correctDecimals(text=None)[source]

Corrects the number of decimal places according to the text, adapting to the input’s decimal places.

Note

  • If text is not provided, uses the current internal text of the widget.

  • If text is provided, its expected to only contain the scientific representation text, e.g. +1234.54544E-9.

Examples

  1. text = 1.23E-5 => decimal_change = 5+2 = 7

  2. text = 25e+5 => decimal_change = self._decimals

  3. text = 25e-3 and default_decimals = 2 => decimal_change = self._decimals

  4. text = 3.251 and default_decimals = 2 => decimal_change = 3

  5. text = 3.1 and default_decimals = 2 => decimal_change = 2

Parameters:
text : str, optional

text to be processed. Defaults to None.

debugBaseQuantityChanged(quantity: PlainQuantity) None[source]

Debug method for the baseQuantityChanged signal.

debugBaseValueChanged(value: Decimal) None[source]

Debug method for the baseValueChanged signal.

debugDecimalsChanged(decimals: int) None[source]

Debug method for the decimalsChanged signal.

debugDisplayUnitChanged(unit: str) None[source]

Debug method for the displayUnitChanged signal.

debugEditingFinished() None[source]

Debug method for the editingFinished signal.

debugLineEditTextChanged(text: str) None[source]

Debug method for the lineEdit textChanged signal.

debugScientificSpinboxTextChanged(text: str) None[source]

Debug method for the textChanged signal of the ScientificSpinBox.

debugValueChanged(value: str) None[source]

Debug method for the valueChanged signal.

decimals() int[source]

Returns the current number of decimals.

Returns:

number of decimals.

Return type:

int

defaultConversor(numeric: str, unit: str) str[source]

Converts a quantity to its internal text representation.

Parameters:
numeric : str

text representation of the numeric part.

unit : str

text representation of the unit part.

Returns:

the internal text representation.

Return type:

str

displayUnitConversor(numeric: str, unit: str) str[source]

Converts a quantity to its internal text representation in the display unit.

Parameters:
numeric : str

text representation of the numeric part.

unit : str

text representation of the unit part.

Returns:

the internal text representation in the display unit.

Return type:

str

emptyUnitEvent() None[source]

Triggers tooltip and error color when unit is empty.

This function is called on validation.

getNumberToChange(cursor_pos: int, text: str, step: float)[source]

Gets the number to be added/subtracted to the value based on cursor position.

Attention

  • Only tested to work with abs(step) = 1 currently.

  • Can’t handle exponentials.

Parameters:
cursor_pos : int

current cursor position.

text : str

current text.

step : float

step to take.

getNumericText() str[source]

Returns only the scientific representation of the widget’s internal text.

handleArgs(thousand_separators, default_decimals, default_value, allowed_units, preferred_units, display_unit, enable_tooltip, base_unit, backend_interface)[source]

Processes the arguments passed to the constructor.

Do the necessary sanity checks and raises exceptions if needed.

Parameters:
thousand_separators : bool

if True, uses thousand separators when showing the text.

default_decimals : int

number of decimals to show by default.

default_value : Decimal

default value of the widget.

allowed_units : List[str]

list of allowed units. If provided, enables the ‘allowed units’ feature. Can’t be used with ‘preferred units’ feature.

preferred_units : List[str]

list of preferred units. If provided, enables the preferred units feature. Can’t be used with allowed units feature.

display_unit : str

unit which will be used to display on the spinbox. If using the ‘preferred units’ or ‘allowed units’ features, the features units array must contain the display_unit.

enable_tooltip : bool

if False, disables showing tooltips when error occurs. Defaults to True.

base_unit : str

base unit in which the value will be stored on baseQuantity property. If base_unit=’’, allows only dimensionless values.

backend_interface : PintInterface

the backend interface object to use.

incompatibleUnitEvent() None[source]

Triggers tooltip and error color when unit is incompatible.

This function is called on validation.

invalidUnitEvent() None[source]

Triggers tooltip and error color when unit is invalid.

This function is called on validation.

keepCursorPosition(last_position=None, correct=False, is_step_by=False, is_editing_finished=False)[source]

Sets the cursor position to the last position.

Note

  • If last_position is not provided, uses the internal last cursor position.

  • If correct is True, corrects the cursor position using correctCursorPosition.

  • The is_step_by and is_editing_finished args are passed to correctCursorPosition.

Parameters:
last_position : int, optional

the last cursor position. Defaults to self._lastCursorPosition.

correct : bool, optional

whether to correct the cursor position. Defaults to False.

is_step_by : bool, optional

whether the cursor position is being changed by a step. Passed to correctCursorPosition. Defaults to False.

is_editing_finished : bool, optional

whether the editing is finished. Passed to correctCursorPosition. Defaults to False.

keyPressEvent(event: QKeyEvent | None) None[source]

Intercepts the key press event.

If self._lastCursorPosition is exactly at the end of the text, resets self._lastCursorPosition to 0 avoiding corrections of cursor position when editing the text.

Parameters:
event : QKeyEvent

the key press event.

nearestPreferredUnitConversor(numeric: str, unit: str) str[source]

Converts a quantity to its internal text representation with the nearest preferred unit.

Parameters:
numeric : str

text representation of the numeric part.

unit : str

text representation of the unit part.

Returns:

the internal text representation in the nearest preferred unit.

Return type:

str

numericSignalChange(text_before: str, text_after: str)[source]

Detects if the number changed signal.

Parameters:
text_before : str

text before the change.

text_after : str

text after the change.

Returns:

None if can’t determine the signal, 1 if changed from

negative to positive, -1 if changed from positive to negative.

Return type:

float

onEditingFinished() None[source]

Executes necessary actions after editing finished.

Actions:
  • Corrects the cursor position.

  • Formats the text.

  • Updates the base quantity.

removeSeparators(text)[source]

Removes all internal and representation separators from text.

Parameters:
text : str

text to remove separators.

Returns:

text without separators.

Return type:

str

removeThousandSeparators(text: str)[source]

Remove thousand separators from text.

Parameters:
text : str

text to remove thousand separators.

Returns:

text without thousand separators

Return type:

str

scientificToDecimal(scientific_text)[source]

Converts text with scientific notation to a Decimal number and returns its text representation.

Parameters:
scientific_text : str

the input text.

Returns:

the text representation of the Decimal number.

Return type:

str

setBaseValue(value: Decimal | float, from_setvalue=False) None[source]

Sets the widget base value.

If the value is a float, converts the passed value to backend’s ValueType, using the current number of decimals.

If signals are not blocked, emits baseValueChanged with the value converted to ValueType.

Parameters:
value : PintInterface.ValueType

the value to set.

from_setvalue : bool

flag to know if the function was called by setValue to avoid infinite loops.

setDecimals(prec: int) None[source]

Sets the number of decimals.

Parameters:
prec : int

number of decimals.

setDisplayUnit(new_unit: str)[source]

Converts the display quantity to a new display unit and sets the value.

Parameters:
new_unit : str

The new display unit.

setErrorColor() None[source]

Sets the lineEdit text color to red.

Sets the isInputError property to true and updates the lineEdit style.

setValue(value: Decimal | float) None[source]

Sets the widget value.

If the value is a float, converts the passed value to backend’s ValueType, using the current number of decimals.

If signals are not blocked, emits valueChanged with the value converted to float.

Parameters:
value : PintInterface.ValueType

the value to set.

setupWidget()[source]

Sets up the widget defaults before running

showTooltip(text: str) None[source]

Shows immediately a tooltip with given text.

Parameters:
text : str

text to show on the tooltip. Can be HTML.

signalsBlocked()[source]

Verify if signals are blocked.

Returns:

True if signals are blocked and False otherwise.

Return type:

bool

stepBy(step: float)[source]

Handles the step by functionality.

Changes cursor position using correctCursorPosition to avoid separators and add/subtract the number using getNumberToChange.

Also corrects the cursor position if the number signal is changed.

Side effects:
  • sets the text and value, propagating the step.

Parameters:
step : float

step to take.

suffix() str[source]

Returns the suffix, that is, the unit text.

text() str[source]

Returns the widget text.

textFromValue(value: Decimal) str[source]

Retrieves the text from current value and sets the internal text.

Side effects:
  • sets the number of decimals

  • corrects the cursor position

Parameters:
value : Decimal

the current numeric value of the widget.

Returns:

the text representation of the value.

Return type:

str

unitNotAllowedEvent() None[source]

Triggers tooltip and error color when unit is not allowed.

This function is called on validation.

unitNotEmptyEvent() None[source]

Triggers tooltip and error color when unit is not empty.

This function is called on validation.

validate(text: str, position: int) tuple[State, str, int][source]

Validates the text input using two layers of validation.

First, the text is validated by ScientificInputValidator to verify if the text is in the expected format for physical quantities.

If the result of the first validator is Acceptable, does a second validation to verify if the unit provided is valid, compatible and not empty.

Triggers the tooltip and error color hints.

Parameters:
text : str

text to validate.

position : int

position of the cursor before validation.

Returns:

state of the validator. text (str): text after the validation. position (int): position of the cursor after validation.

Return type:

state (ScientificInputValidator.State)

valueFromText(text: str) float[source]

Retrieves the value from text and sets the current value.

This method uses the ScientificInputValidator’s regex parser to get the named capture groups of the current text and parse them into a value.

Side effects:
  • sets the representation quantity.

Parameters:
text : str

the current widget’s text.

Returns:

the value retrieved from the text.

Return type:

float

property backend : PintInterface

backend interface used by the widget.

Type:

PintInterface

property baseQuantity : PlainQuantity

base quantity with the base unit and value converted to base unit.

Type:

PintInterface.QuantityType

baseQuantityChanged

Signal emitted when the base quantity is changed. Returns the new base quantity.

Type:

pint.Quantity

property baseUnit : str

unit of the base quantity.

Type:

str

property baseValue : Decimal

value of the quantity converted to the base unit.

Type:

PintInterface.ValueType

baseValueChanged

Signal emitted when the base value is changed. Returns the new base value.

Type:

Decimal

decimalsChanged

Signal emitted when the decimals is changed. Returns the decimals.

Type:

int

property defaultDecimals : int

default number of decimals

Type:

int

displayUnitChanged

Signal emitted when the display unit is changed. Returns the new display unit.

Type:

str

property quantity : PlainQuantity

quantity being displayed.

Type:

PintInterface.QuantityType

property unit : str

unit of the quantity being displayed.

Type:

str

property value : Decimal

value of the quantity being displayed.

Type:

PintInterface.ValueType