From 72b92ce160b3d2db5fe7708c047e06691ced3fae Mon Sep 17 00:00:00 2001 From: Kacper Donat Date: Wed, 4 Dec 2024 18:17:36 +0100 Subject: [PATCH] Gui: Add QuantitySpinBox normalization --- src/Gui/QuantitySpinBox.cpp | 31 +++++++++++++++++++++++++++++-- src/Gui/QuantitySpinBox.h | 3 +++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/Gui/QuantitySpinBox.cpp b/src/Gui/QuantitySpinBox.cpp index 1ca7d684e2..9e8acddaca 100644 --- a/src/Gui/QuantitySpinBox.cpp +++ b/src/Gui/QuantitySpinBox.cpp @@ -405,10 +405,18 @@ void QuantitySpinBox::resizeEvent(QResizeEvent * event) resizeWidget(); } -void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent *event) +void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent* event) { - if (!handleKeyEvent(event->text())) + const auto isEnter = event->key() == Qt::Key_Enter || event->key() == Qt::Key_Return; + + if (isEnter && !isNormalized()) { + normalize(); + return; + } + + if (!handleKeyEvent(event->text())) { QAbstractSpinBox::keyPressEvent(event); + } } void Gui::QuantitySpinBox::paintEvent(QPaintEvent*) @@ -477,6 +485,24 @@ double QuantitySpinBox::rawValue() const return d->quantity.getValue(); } +void QuantitySpinBox::normalize() +{ + // this does not really change the value, only the representation + QSignalBlocker blocker(this); + + Q_D(const QuantitySpinBox); + return setValue(d->quantity); +} + +bool QuantitySpinBox::isNormalized() +{ + static const QRegularExpression operators(QStringLiteral("[+\\-/*]"), + QRegularExpression::CaseInsensitiveOption); + + Q_D(const QuantitySpinBox); + return !d->validStr.contains(operators); +} + void QuantitySpinBox::setValue(const Base::Quantity& value) { Q_D(QuantitySpinBox); @@ -884,6 +910,7 @@ void QuantitySpinBox::focusInEvent(QFocusEvent * event) void QuantitySpinBox::focusOutEvent(QFocusEvent * event) { validateInput(); + normalize(); QToolTip::hideText(); QAbstractSpinBox::focusOutEvent(event); diff --git a/src/Gui/QuantitySpinBox.h b/src/Gui/QuantitySpinBox.h index dadc28d906..780553718c 100644 --- a/src/Gui/QuantitySpinBox.h +++ b/src/Gui/QuantitySpinBox.h @@ -57,6 +57,9 @@ public: /// Get the current quantity without unit double rawValue() const; + void normalize(); + bool isNormalized(); + /// Gives the current state of the user input, gives true if it is a valid input with correct quantity /// or returns false if the input is a unparsable string or has a wrong unit. bool hasValidInput() const;