aboutsummaryrefslogtreecommitdiffstats
path: root/src/quicktemplates/qquickdoublespinbox.cpp
blob: 9a7d3e655c951f0d1c427ddfd6469919df31ae6a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
// Qt-Security score:significant reason:default

#include "qquickdoublespinbox_p.h"

#include <private/qquickcontrol_p_p.h>
#include <private/qquickindicatorbutton_p.h>
#include <private/qquicktextinput_p.h>

#include <private/qqmlengine_p.h>

#include <QtQml/qqmlinfo.h>

QT_BEGIN_NAMESPACE

/*!
    \qmltype DoubleSpinBox
    \inherits Control
//!     \nativetype QQuickDoubleSpinBox
    \inqmlmodule QtQuick.Controls
    \ingroup qtquickcontrols-input
    \ingroup qtquickcontrols-focusscopes
    \since 6.11
    \brief Allows the user to select from a set of preset floating-point
        values.

    \image qtquickcontrols-doublespinbox.png
           {Spin box displaying decimal values}

    DoubleSpinBox is similar to \l SpinBox, except that it supports double
    values rather than integer. The user can choose a value by clicking the up
    or down indicator buttons, or by pressing up or down on the keyboard.
    Optionally, DoubleSpinBox can be also made \l editable, so the user can
    enter a text value in the input field.

    By default, DoubleSpinBox provides discrete values in the range of
    \c [0.00-99.99] with a \l stepSize of \c 1.0.

    \snippet qtquickcontrols-doublespinbox.qml 1

    \sa SpinBox, Tumbler, {Customizing DoubleSpinBox},
        {Focus Management in Qt Quick Controls}
*/

/*!
    \include qquickspinbox.qdocinc {valueModified} {DoubleSpinBox}
*/

class QQuickDoubleSpinBoxPrivate
    : public QQuickAbstractSpinBox<QQuickDoubleSpinBox, double>::QQuickAbstractSpinBoxPrivate
{
    Q_DECLARE_PUBLIC(QQuickDoubleSpinBox)

public:
    QQuickDoubleSpinBoxPrivate();

    bool setValue(double newValue, bool wrap, ValueStatus modified) override;

    void updateValue() override;
    void updateDisplayText() override;

    void contentItemTextChanged();

    QString evaluateTextFromValue(double val, int decimals) const;
    double evaluateValueFromText(const QString &text) const;

    double round(double input) const;

    int decimals = 2;

private:
    friend class QQuickAbstractSpinBox<QQuickDoubleSpinBox, double>::QQuickAbstractSpinBoxPrivate;
};

QQuickDoubleSpinBoxPrivate::QQuickDoubleSpinBoxPrivate()
    : QQuickAbstractSpinBox<QQuickDoubleSpinBox, double>::QQuickAbstractSpinBoxPrivate()
{
    from = 0.0;
    to = 99.99;
}

/*!
    \internal

    modified indicates if the value was modified by the user and not programatically.
    This is then passed on to updateDisplayText to indicate that the user has modified
    the value, so it may need to trigger an update of the contentItem's text, too.
*/

bool QQuickDoubleSpinBoxPrivate::setValue(double newValue, bool wrap, ValueStatus modified)
{
    Q_Q(QQuickDoubleSpinBox);
    double correctedValue = newValue;
    if (q->isComponentComplete())
        correctedValue = boundValue(newValue, wrap);

    if (modified == ValueStatus::Unmodified && qFuzzyCompare(newValue, correctedValue)
        && qFuzzyCompare(newValue, value))
        return false;

    const bool emitSignals = (value != correctedValue);
    value = correctedValue;

    updateDisplayText();
    updateUpEnabled();
    updateDownEnabled();

    // Only emit the signals if the corrected value is not the same as the
    // original value to avoid unnecessary updates.
    if (emitSignals) {
        emit q->valueChanged();
        if (modified == ValueStatus::Modified)
            emit q->valueModified();
    }
    return true;
}

void QQuickDoubleSpinBoxPrivate::updateValue()
{
    if (!contentItem)
        return;

    const QVariant text = contentItem->property("text");
    if (text.isValid())
        setValue(evaluateValueFromText(text.toString()), false /* wrap */, ValueStatus::Modified);
}

void QQuickDoubleSpinBoxPrivate::updateDisplayText()
{
    setDisplayText(evaluateTextFromValue(value, decimals));
}

void QQuickDoubleSpinBoxPrivate::contentItemTextChanged()
{
    Q_Q(QQuickDoubleSpinBox);

    QQuickTextInput *inputTextItem = qobject_cast<QQuickTextInput *>(q->contentItem());
    if (!inputTextItem)
        return;
    setDisplayText(inputTextItem->text());
}

QString QQuickDoubleSpinBoxPrivate::evaluateTextFromValue(double val, int decimals) const
{
    Q_Q(const QQuickDoubleSpinBox);

    QString text;
    QQmlEngine *engine = qmlEngine(q);
    if (engine && textFromValue.isCallable()) {
        QJSValue loc;
#if QT_CONFIG(qml_locale)
        loc = QJSValuePrivate::fromReturnedValue(
                engine->handle()->fromData(QMetaType::fromType<QLocale>(), &locale));
#endif
        text = textFromValue.call(QJSValueList() << val << decimals << loc).toString();
    } else {
        text = locale.toString(val, 'f', decimals);
    }
    return text;
}

double QQuickDoubleSpinBoxPrivate::evaluateValueFromText(const QString &text) const
{
    Q_Q(const QQuickDoubleSpinBox);
    double value;
    QQmlEngine *engine = qmlEngine(q);
    if (engine && valueFromText.isCallable()) {
        QJSValue loc;
#if QT_CONFIG(qml_locale)
        loc = QJSValuePrivate::fromReturnedValue(
                engine->handle()->fromData(QMetaType::fromType<QLocale>(), &locale));
#endif
        value = valueFromText.call(QJSValueList() << text << loc).toNumber();
    } else {
        value = locale.toDouble(text);
    }
    return value;
}

double QQuickDoubleSpinBoxPrivate::round(double value) const
{
    return QString::number(value, 'f', decimals).toDouble();
}

QQuickDoubleSpinBox::QQuickDoubleSpinBox(QQuickItem *parent)
    : QQuickControl(*(new QQuickDoubleSpinBoxPrivate), parent),
      QQuickAbstractSpinBox<QQuickDoubleSpinBox, double>()
{
}

QQuickDoubleSpinBox::~QQuickDoubleSpinBox() { }

/*!
    \include qquickspinbox.qdocinc {from} {DoubleSpinBox} {0.0}
*/

void QQuickDoubleSpinBox::setFrom(double from)
{
    Q_D(QQuickDoubleSpinBox);
    const double newFrom = d->round(from);
    if (qFuzzyCompare(d->from, newFrom))
        return;

    d->from = newFrom;
    emit fromChanged();
    if (isComponentComplete()) {
        if (!d->setValue(d->round(d->value), false /* wrap */,
                         QQuickDoubleSpinBoxPrivate::ValueStatus::Unmodified)) {
            d->updateUpEnabled();
            d->updateDownEnabled();
        }
    }
}

/*!
    \include qquickspinbox.qdocinc {to} {DoubleSpinBox} {99.99}
*/

void QQuickDoubleSpinBox::setTo(double to)
{
    Q_D(QQuickDoubleSpinBox);
    const double newTo = d->round(to);
    if (qFuzzyCompare(d->to, newTo))
        return;

    d->to = newTo;
    emit toChanged();
    if (isComponentComplete()) {
        if (!d->setValue(d->round(d->value), false /* wrap */,
                         QQuickDoubleSpinBoxPrivate::ValueStatus::Unmodified)) {
            d->updateUpEnabled();
            d->updateDownEnabled();
        }
    }
}

/*!
    \include qquickspinbox.qdocinc {value-prop} {double} {DoubleSpinBox} {0.0}
*/

void QQuickDoubleSpinBox::setValue(double value)
{
    Q_D(QQuickDoubleSpinBox);
    d->setValue(d->round(value), false /* wrap */,
                QQuickDoubleSpinBoxPrivate::ValueStatus::Unmodified);
}

/*!
    \include qquickspinbox.qdocinc {stepSize} {DoubleSpinBox} {1.0}
*/

void QQuickDoubleSpinBox::setStepSize(double step)
{
    Q_D(QQuickDoubleSpinBox);
    if (qFuzzyCompare(d->stepSize, step))
        return;

    d->stepSize = step;
    emit stepSizeChanged();
}

/*!
    \qmlproperty int QtQuick.Controls::DoubleSpinBox::decimals

    This property holds how many decimals the spinbox will use for displaying
    and interpreting doubles.

    The default value is \c 2.

    Changing the value of this property may affect \l from, \l to and \l value.

    \warning The maximum value for \a decimals is \c {DBL_MAX_10_EXP +
    DBL_DIG} (\c 323) because of the limitations of the double type.
*/

int QQuickDoubleSpinBox::decimals() const
{
    Q_D(const QQuickDoubleSpinBox);

    return d->decimals;
}

void QQuickDoubleSpinBox::setDecimals(int decimals)
{
    Q_D(QQuickDoubleSpinBox);
    d->decimals = qBound(0, decimals, DBL_MAX_10_EXP + DBL_DIG);

    // Make sure values are rounded.
    setFrom(from());
    setTo(to());
    setValue(value());
    d->updateValue();
    emit decimalsChanged();
}

/*!
    \include qquickspinbox.qdocinc {editable} {DoubleSpinBox}
*/

#if QT_CONFIG(validator)
/*!
    \qmlproperty Validator QtQuick.Controls::DoubleSpinBox::validator

    This property holds the input text validator for editable spinboxes. By
    default, DoubleSpinBox uses \l DoubleValidator to accept input of double numbers.

    \code
    DoubleSpinBox {
        id: control
        validator: DoubleValidator {
            locale: control.locale.name
            bottom: Math.min(control.from, control.to)
            top: Math.max(control.from, control.to)
        }
    }
    \endcode

    \sa editable, textFromValue, valueFromText, {Control::locale}{locale},
        {Validating Input Text}
*/
#endif

/*!
    \qmlproperty function QtQuick.Controls::DoubleSpinBox::textFromValue

    This property holds a callback function that is called whenever
    a double value needs to be converted to display text.

    The default function can be overridden to display custom text for a given
    value. This applies to both editable and non-editable spinboxes;
    for example, when using the up and down buttons or a mouse wheel to
    increment and decrement the value, the new value is converted to display
    text using this function.

    The callback function signature is \c {string function(value, decimals, locale)}.
    The function can have two or three arguments, where the first argument
    is the value to be converted, the second argument is the number of decimals,
    and the optional third argument is the locale that should be used for
    the conversion, if applicable.

    The default implementation does the conversion using
    \l {QtQml::Number::toLocaleString()}{Number.toLocaleString}():

    \code
    textFromValue: function(value, decimals, locale) {
        return Number(value).toLocaleString(locale, 'f', decimals);
    }
    \endcode

    \note When applying a custom \c textFromValue implementation for editable
    spinboxes, a matching \l valueFromText implementation must be provided
    to be able to convert the custom text back to a double value.

    \sa valueFromText, validator, {Control::locale}{locale}
*/
QJSValue QQuickDoubleSpinBox::textFromValue() const
{
    Q_D(const QQuickDoubleSpinBox);
    if (!d->textFromValue.isCallable()) {
        QQmlEngine *engine = qmlEngine(this);
        if (engine) {
            d->textFromValue = engine->evaluate(
                    QStringLiteral("(function(value, decimals, locale) { return "
                                   "Number(value).toLocaleString(locale, 'f', decimals); })"));
        }
    }
    return d->textFromValue;
}

/*!
    \qmlproperty function QtQuick.Controls::DoubleSpinBox::valueFromText

    This property holds a callback function that is called whenever
    input text needs to be converted to a double value.

    This function only needs to be overridden when \l textFromValue
    is overridden for an editable spinbox.

    The callback function signature is \c {int function(text, locale)}.
    The function can have one or two arguments, where the first argument
    is the text to be converted, and the optional second argument is the
    locale that should be used for the conversion, if applicable.

    The default implementation does the conversion using
    \l {QtQml::Locale}{Number.fromLocaleString()}:

    \code
    valueFromText: function(text, locale) { return Number.fromLocaleString(locale, text); }
    \endcode

    \note When applying a custom \l textFromValue implementation for editable
    spinboxes, a matching \c valueFromText implementation must be provided
    to be able to convert the custom text back to a double value.

    \sa textFromValue, validator, {Control::locale}{locale}
*/
QJSValue QQuickDoubleSpinBox::valueFromText() const
{
    Q_D(const QQuickDoubleSpinBox);
    if (!d->valueFromText.isCallable()) {
        QQmlEngine *engine = qmlEngine(this);
        if (engine)
            d->valueFromText = engine->evaluate(QStringLiteral(
                    "(function(text, locale) { return Number.fromLocaleString(locale, text); })"));
    }
    return d->valueFromText;
}

/*!
    \include qquickspinbox.qdocinc {upAndDown} {DoubleSpinBox} {up} {increase()}
*/

/*!
    \include qquickspinbox.qdocinc {upAndDown} {DoubleSpinBox} {down} {decrease()}
*/

/*!
    \include qquickspinbox.qdocinc {inputMethodHints} {DoubleSpinBox}
*/

/*!
    \include qquickspinbox.qdocinc {inputMethodComposing} {DoubleSpinBox}
*/

/*!
    \since QtQuick.Controls 2.3 (Qt 5.10)
    \include qquickspinbox.qdocinc {wrap} {DoubleSpinBox}
*/

void QQuickDoubleSpinBox::setWrap(bool wrap)
{
    Q_D(QQuickDoubleSpinBox);
    if (d->wrap == wrap)
        return;

    d->wrap = wrap;
    if (qFuzzyCompare(d->value, d->from) || qFuzzyCompare(d->value, d->to)) {
        d->updateUpEnabled();
        d->updateDownEnabled();
    }
    emit wrapChanged();
}

/*!
    \qmlproperty string QtQuick.Controls::DoubleSpinBox::displayText
    \readonly

    This property holds the textual value of the spinbox.

    The value of the property is based on \l textFromValue and \l {Control::}
    {locale}, and equal to:
    \badcode
    let text = spinBox.textFromValue(spinBox.value, spinBox.decimals, spinBox.locale)
    \endcode

    \sa textFromValue
*/

/*!
    \include qquickspinbox.qdocinc {increase} {DoubleSpinBox}
*/

/*!
    \include qquickspinbox.qdocinc {decrease} {DoubleSpinBox}
*/

void QQuickDoubleSpinBox::contentItemChange(QQuickItem *newItem, QQuickItem *oldItem)
{
    Q_D(QQuickDoubleSpinBox);
    if (QQuickTextInput *oldInput = qobject_cast<QQuickTextInput *>(oldItem)) {
        disconnect(oldInput, &QQuickTextInput::inputMethodComposingChanged, this,
                   &QQuickDoubleSpinBox::inputMethodComposingChanged);
        QObjectPrivate::disconnect(oldInput, &QQuickTextInput::textChanged, d,
                                   &QQuickDoubleSpinBoxPrivate::contentItemTextChanged);
    }

    if (newItem) {
        newItem->setActiveFocusOnTab(true);
        if (d->activeFocus)
            newItem->forceActiveFocus(static_cast<Qt::FocusReason>(d->focusReason));
#if QT_CONFIG(cursor)
        if (d->editable)
            newItem->setCursor(Qt::IBeamCursor);
#endif

        if (QQuickTextInput *newInput = qobject_cast<QQuickTextInput *>(newItem)) {
            connect(newInput, &QQuickTextInput::inputMethodComposingChanged, this,
                    &QQuickDoubleSpinBox::inputMethodComposingChanged);
            QObjectPrivate::connect(newInput, &QQuickTextInput::textChanged, d,
                                    &QQuickDoubleSpinBoxPrivate::contentItemTextChanged);
        }
    }
}

QQuickControlPrivate *QQuickDoubleSpinBox::d_base_func()
{
    Q_D(QQuickDoubleSpinBox);
    return d;
}
const QQuickControlPrivate *QQuickDoubleSpinBox::d_base_func() const
{
    Q_D(const QQuickDoubleSpinBox);
    return d;
}

QT_END_NAMESPACE

#include "moc_qquickdoublespinbox_p.cpp"