From a2a285b7c90cbc958228a6445cc3c5dd1c953c50 Mon Sep 17 00:00:00 2001 From: wmayer Date: Sat, 12 Nov 2022 18:24:27 +0100 Subject: [PATCH] Gui: improve usability of QuantitySpinBox when used as menu item --- src/Gui/QuantitySpinBox.cpp | 27 ++++++++++++++++++++++++--- src/Gui/QuantitySpinBox.h | 1 + 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/Gui/QuantitySpinBox.cpp b/src/Gui/QuantitySpinBox.cpp index b71b943a0a..c88082b815 100644 --- a/src/Gui/QuantitySpinBox.cpp +++ b/src/Gui/QuantitySpinBox.cpp @@ -363,7 +363,7 @@ void QuantitySpinBox::evaluateExpression() void Gui::QuantitySpinBox::setNumberExpression(App::NumberExpression* expr) { - lineEdit()->setText(getUserString(expr->getQuantity())); + updateEdit(getUserString(expr->getQuantity())); handlePendingEmit(); } @@ -403,10 +403,31 @@ void QuantitySpinBox::updateText(const Quantity &quant) double dFactor; QString txt = getUserString(quant, dFactor, d->unitStr); d->unitValue = quant.getValue()/dFactor; - lineEdit()->setText(txt); + updateEdit(txt); handlePendingEmit(); } +void QuantitySpinBox::updateEdit(const QString& text) +{ + Q_D(QuantitySpinBox); + + QLineEdit* edit = lineEdit(); + + bool empty = edit->text().isEmpty(); + int cursor = edit->cursorPosition(); + int selsize = edit->selectedText().size(); + + edit->setText(text); + + cursor = qBound(0, cursor, edit->displayText().size() - d->unitStr.size()); + if (selsize > 0) { + edit->setSelection(0, cursor); + } + else { + edit->setCursorPosition(empty ? 0 : cursor); + } +} + void QuantitySpinBox::validateInput() { Q_D(QuantitySpinBox); @@ -416,7 +437,7 @@ void QuantitySpinBox::validateInput() const App::ObjectIdentifier & path = getPath(); d->validateAndInterpret(text, state, path); if (state != QValidator::Acceptable) { - lineEdit()->setText(d->validStr); + updateEdit(d->validStr); } handlePendingEmit(); diff --git a/src/Gui/QuantitySpinBox.h b/src/Gui/QuantitySpinBox.h index e06503a66a..aa177c2246 100644 --- a/src/Gui/QuantitySpinBox.h +++ b/src/Gui/QuantitySpinBox.h @@ -160,6 +160,7 @@ protected: private: void validateInput() override; void updateText(const Base::Quantity&); + void updateEdit(const QString& text); void updateFromCache(bool notify, bool updateUnit = true); QString getUserString(const Base::Quantity& val, double& factor, QString& unitString) const; QString getUserString(const Base::Quantity& val) const;