11#include " DoubleSpinBox.hpp"
22#include " pre/utils/DoubleRange.hpp"
33#include " pre/utils/Expressions.hpp"
4+ #include " pre/utils/Rounding.hpp"
45#include " pre/models/units/UnitSystem.hpp"
56#include < QLineEdit>
67#include < cmath>
@@ -11,8 +12,7 @@ DoubleSpinBox::DoubleSpinBox(const Quantity& quantity, const DoubleRange& range,
1112 show_unit(true ),
1213 quantity(quantity)
1314{
14- setDecimals (8 ); // Magic number
15- setSingleStep (range.step );
15+ setDecimals (16 ); // High precision since this only applies to the internal value stored in base unit. Conversion and rounding is done in textFromValue.
1616 setMinimum (-std::numeric_limits<double >::infinity ()); // Not used
1717 setMaximum (std::numeric_limits<double >::infinity ()); // Not used
1818
@@ -33,9 +33,9 @@ QString DoubleSpinBox::textFromValue(double baseValue) const {
3333 // Convert value given in SI base to the selected unit
3434 double unitValue = quantity.getUnit ().fromBase (baseValue);
3535
36- // Convert value to string with fixed-point representation
36+ // Convert value to string with fixed-point representation and limited precision for display
3737 // If the result has a decimal point, remove any trailing zeros and possibly the point as well
38- QString result = QString::number (unitValue, ' f' , decimals () );
38+ QString result = QString::number (unitValue, ' f' , 6 );
3939 if (result.indexOf (' .' ) != -1 ) {
4040 while (result.endsWith (' 0' )) {
4141 result.chop (1 );
@@ -80,7 +80,7 @@ QValidator::State DoubleSpinBox::validate(QString& text, int& pos) const {
8080
8181// Overwriting this ensures that the range validation also applies to steps made by "spinning"
8282void DoubleSpinBox::stepBy (int steps) {
83- double newValue = value () + singleStep () * steps;
83+ double newValue = value () + singleStep ()* steps; // Compute new value by applying step
8484 if (range.contains (newValue)) {
8585 setValue (newValue);
8686 emit contentModified (); // Signal modification by user
@@ -91,4 +91,10 @@ void DoubleSpinBox::updateUnit() {
9191 // Show the selected unit as suffix
9292 // Setting the suffix also triggers a new evaluation of textFromValue
9393 setSuffix (quantity.getUnit ().getSuffix ());
94+
95+ // Select the step so that is has a smooth value when converted to the unit
96+ double unitStep = quantity.getUnit ().fromBase (range.step ); // Convert the preferred step size to the unít
97+ unitStep = floorToPow10 (unitStep); // Make the unit step a smooth value by rounding down to the nearest power of 10
98+
99+ setSingleStep (quantity.getUnit ().toBase (unitStep)); // Convert back to base value and apply
94100}
0 commit comments