/
QuantitySpinBox.cpp
1073 lines (921 loc) · 30.3 KB
/
QuantitySpinBox.cpp
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/***************************************************************************
* Copyright (c) 2014 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, *
* Fifth Floor, Boston, MA 02110-1301, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <QApplication>
# include <QDebug>
# include <QFocusEvent>
# include <QFontMetrics>
# include <QHBoxLayout>
# include <QLabel>
# include <QLineEdit>
# include <QMouseEvent>
# include <QPixmapCache>
# include <QStyle>
# include <QStyleOptionSpinBox>
# include <QStylePainter>
# include <QToolTip>
#endif
#include "QuantitySpinBox.h"
#include "QuantitySpinBox_p.h"
#include "DlgExpressionInput.h"
#include "propertyeditor/PropertyItem.h"
#include "BitmapFactory.h"
#include "Tools.h"
#include "Command.h"
#include <Base/Tools.h>
#include <Base/Exception.h>
#include <App/Application.h>
#include <App/Document.h>
#include <App/DocumentObject.h>
#include <App/ExpressionParser.h>
#include <App/PropertyGeo.h>
#include <sstream>
#include <boost/math/special_functions/round.hpp>
using namespace Gui;
using namespace App;
using namespace Base;
namespace Gui {
class QuantitySpinBoxPrivate
{
public:
QuantitySpinBoxPrivate() :
validInput(true),
pendingEmit(false),
unitValue(0),
maximum(DOUBLE_MAX),
minimum(-DOUBLE_MAX),
singleStep(1.0)
{
}
~QuantitySpinBoxPrivate()
{
}
QString stripped(const QString &t, int *pos) const
{
QString text = t;
const int s = text.size();
text = text.trimmed();
if (pos)
(*pos) -= (s - text.size());
return text;
}
bool validate(QString& input, Base::Quantity& result) const
{
// Do not accept empty strings because the parser will consider
// " unit" as "1 unit" which is not the desired behaviour (see #0004104)
if (input.isEmpty())
return false;
bool success = false;
QString tmp = input;
int pos = 0;
QValidator::State state;
Base::Quantity res = validateAndInterpret(tmp, pos, state);
res.setFormat(quantity.getFormat());
if (state == QValidator::Acceptable) {
success = true;
result = res;
input = tmp;
}
else if (state == QValidator::Intermediate) {
tmp = tmp.trimmed();
tmp += QLatin1Char(' ');
tmp += unitStr;
Base::Quantity res2 = validateAndInterpret(tmp, pos, state);
res2.setFormat(quantity.getFormat());
if (state == QValidator::Acceptable) {
success = true;
result = res2;
input = tmp;
}
}
return success;
}
Base::Quantity validateAndInterpret(QString& input, int& pos, QValidator::State& state) const
{
Base::Quantity res;
const double max = this->maximum;
const double min = this->minimum;
QString copy = input;
int len = copy.size();
const bool plus = max >= 0;
const bool minus = min <= 0;
switch (len) {
case 0:
state = max != min ? QValidator::Intermediate : QValidator::Invalid;
goto end;
case 1:
if (copy.at(0) == locale.decimalPoint()) {
state = QValidator::Intermediate;
copy.prepend(QLatin1Char('0'));
pos++;
len++;
goto end;
}
else if (copy.at(0) == QLatin1Char('+')) {
// the quantity parser doesn't allow numbers of the form '+1.0'
state = QValidator::Invalid;
goto end;
}
else if (copy.at(0) == QLatin1Char('-')) {
if (minus)
state = QValidator::Intermediate;
else
state = QValidator::Invalid;
goto end;
}
break;
case 2:
if (copy.at(1) == locale.decimalPoint()
&& (plus && copy.at(0) == QLatin1Char('+'))) {
state = QValidator::Intermediate;
goto end;
}
if (copy.at(1) == locale.decimalPoint()
&& (minus && copy.at(0) == QLatin1Char('-'))) {
state = QValidator::Intermediate;
copy.insert(1, QLatin1Char('0'));
pos++;
len++;
goto end;
}
break;
default: break;
}
{
if (copy.at(0) == locale.groupSeparator()) {
state = QValidator::Invalid;
goto end;
}
else if (len > 1) {
bool decOccurred = false;
for (int i = 0; i<copy.size(); i++) {
if (copy.at(i) == locale.decimalPoint()) {
// Disallow multiple decimal points within the same numeric substring
if (decOccurred) {
state = QValidator::Invalid;
goto end;
}
decOccurred = true;
}
// Reset decOcurred if non-numeric character found
else if (!(copy.at(i) == locale.groupSeparator() || copy.at(i).isDigit())) {
decOccurred = false;
}
}
}
bool ok = false;
double value = min;
if (locale.negativeSign() != QLatin1Char('-'))
copy.replace(locale.negativeSign(), QLatin1Char('-'));
if (locale.positiveSign() != QLatin1Char('+'))
copy.replace(locale.positiveSign(), QLatin1Char('+'));
try {
QString copy2 = copy;
copy2.remove(locale.groupSeparator());
res = Base::Quantity::parse(copy2);
value = res.getValue();
ok = true;
}
catch (Base::Exception&) {
}
if (!ok) {
// input may not be finished
state = QValidator::Intermediate;
}
else if (value >= min && value <= max) {
if (copy.endsWith(locale.decimalPoint())) {
// input shouldn't end with a decimal point
state = QValidator::Intermediate;
}
else if (res.getUnit().isEmpty() && !this->unit.isEmpty()) {
// if not dimensionless the input should have a dimension
state = QValidator::Intermediate;
}
else if (res.getUnit() != this->unit) {
// If the user input is of the form "number * unit", "number + unit"
// or "number - unit" it's rejected by the quantity parser and it's
// assumed that the user input is not complete yet (Intermediate).
// However, if the user input is of the form "number / unit" it's accepted
// by the parser but because the units mismatch it's considered as invalid
// and the last valid input will be restored.
// See #0004422: PartDesign value input does not accept trailing slash
// To work around this issue of the quantity parser it's checked if the
// inversed unit matches and if yes the input is also considered as not
// complete.
if (res.getUnit().pow(-1) == this->unit)
state = QValidator::Intermediate;
else
state = QValidator::Invalid;
}
else {
state = QValidator::Acceptable;
}
}
else if (max == min) { // when max and min is the same the only non-Invalid input is max (or min)
state = QValidator::Invalid;
}
else {
if ((value >= 0 && value > max) || (value < 0 && value < min)) {
state = QValidator::Invalid;
}
else {
state = QValidator::Intermediate;
}
}
}
end:
if (state != QValidator::Acceptable) {
res.setValue(max > 0 ? min : max);
}
input = copy;
return res;
}
QLocale locale;
bool validInput;
bool pendingEmit;
QString validStr;
Base::Quantity quantity;
Base::Quantity cached;
Base::Unit unit;
double unitValue;
QString unitStr;
double maximum;
double minimum;
double singleStep;
std::unique_ptr<Base::UnitsSchema> scheme;
};
}
QuantitySpinBox::QuantitySpinBox(QWidget *parent)
: QAbstractSpinBox(parent),
ExpressionBinding(),
d_ptr(new QuantitySpinBoxPrivate())
{
d_ptr->locale = locale();
this->setContextMenuPolicy(Qt::DefaultContextMenu);
QObject::connect(lineEdit(), SIGNAL(textChanged(QString)),
this, SLOT(userInput(QString)));
QObject::connect(this, SIGNAL(editingFinished()),
this, SLOT(handlePendingEmit()));
makeLabel(lineEdit());
// When a style sheet is set the text margins for top/bottom must be set to avoid to squash the widget
#ifndef Q_OS_MAC
lineEdit()->setTextMargins(0, 2, 0, 2);
#else
// https://forum.freecadweb.org/viewtopic.php?f=8&t=50615
lineEdit()->setTextMargins(0, 2, 0, 0);
#endif
QObject::connect(iconLabel, SIGNAL(clicked()), this, SLOT(openFormulaDialog()));
}
QuantitySpinBox::~QuantitySpinBox()
{
}
void QuantitySpinBox::bind(const App::ObjectIdentifier &_path)
{
ExpressionBinding::bind(_path);
iconLabel->show();
}
void Gui::QuantitySpinBox::setExpression(std::shared_ptr<Expression> expr)
{
Q_ASSERT(isBound());
try {
ExpressionBinding::setExpression(expr);
}
catch (const Base::Exception & e) {
setReadOnly(true);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Active, QPalette::Text, Qt::red);
lineEdit()->setPalette(p);
iconLabel->setToolTip(QString::fromLatin1(e.what()));
}
}
QString QuantitySpinBox::boundToName() const
{
if (isBound()) {
std::string path = getPath().toString();
return QString::fromStdString(path);
}
return QString();
}
/**
* @brief Create an object identifier by name.
*
* An identifier is written as document#documentobject.property.subproperty1...subpropertyN
* document# may be dropped, in this case the active document is used.
*/
void QuantitySpinBox::setBoundToByName(const QString &name)
{
try {
// get document
App::Document *doc = App::GetApplication().getActiveDocument();
QStringList list = name.split(QLatin1Char('#'));
if (list.size() > 1) {
doc = App::GetApplication().getDocument(list.front().toLatin1());
list.pop_front();
}
if (!doc) {
qDebug() << "No such document";
return;
}
// first element is assumed to be the document name
list = list.front().split(QLatin1Char('.'));
// get object
App::DocumentObject* obj = doc->getObject(list.front().toLatin1());
if (!obj) {
qDebug() << "No object " << list.front() << " in document";
return;
}
list.pop_front();
// the rest of the list defines the property and eventually subproperties
App::ObjectIdentifier path(obj);
path.setDocumentName(std::string(doc->getName()), true);
path.setDocumentObjectName(std::string(obj->getNameInDocument()), true);
for (QStringList::iterator it = list.begin(); it != list.end(); ++it) {
path << App::ObjectIdentifier::Component::SimpleComponent(it->toLatin1().constData());
}
if (path.getProperty())
bind(path);
}
catch (const Base::Exception& e) {
qDebug() << e.what();
}
}
QString Gui::QuantitySpinBox::expressionText() const
{
try {
if (hasExpression()) {
return QString::fromStdString(getExpressionString());
}
}
catch (const Base::Exception& e) {
qDebug() << e.what();
}
return QString();
}
void Gui::QuantitySpinBox::onChange()
{
Q_ASSERT(isBound());
if (getExpression()) {
std::unique_ptr<Expression> result(getExpression()->eval());
NumberExpression * value = freecad_dynamic_cast<NumberExpression>(result.get());
if (value) {
std::stringstream s;
s << value->getValue();
lineEdit()->setText(getUserString(value->getQuantity()));
handlePendingEmit();
setReadOnly(true);
QPixmap pixmap = getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight));
iconLabel->setPixmap(pixmap);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Text, Qt::lightGray);
lineEdit()->setPalette(p);
}
iconLabel->setExpressionText(Base::Tools::fromStdString(getExpression()->toString()));
}
else {
setReadOnly(false);
QPixmap pixmap = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight));
iconLabel->setPixmap(pixmap);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text));
lineEdit()->setPalette(p);
iconLabel->setExpressionText(QString());
}
}
bool QuantitySpinBox::apply(const std::string & propName)
{
if (!ExpressionBinding::apply(propName)) {
double dValue = value().getValue();
if (isBound()) {
const App::ObjectIdentifier & path = getPath();
const Property * prop = path.getProperty();
/* Skip update if property is bound and we know it is read-only */
if (prop && prop->isReadOnly())
return true;
if (prop && prop->getTypeId().isDerivedFrom(App::PropertyPlacement::getClassTypeId())) {
std::string p = path.getSubPathStr();
if (p == ".Rotation.Angle") {
dValue = Base::toRadians(dValue);
}
}
}
Gui::Command::doCommand(Gui::Command::Doc, "%s = %f", propName.c_str(), dValue);
return true;
}
else
return false;
}
void QuantitySpinBox::resizeEvent(QResizeEvent * event)
{
QAbstractSpinBox::resizeEvent(event);
int frameWidth = style()->pixelMetric(QStyle::PM_SpinBoxFrameWidth);
QSize sz = iconLabel->sizeHint();
iconLabel->move(lineEdit()->rect().right() - frameWidth - sz.width(), 0);
try {
if (isBound() && getExpression()) {
std::unique_ptr<Expression> result(getExpression()->eval());
NumberExpression * value = freecad_dynamic_cast<NumberExpression>(result.get());
if (value) {
setReadOnly(true);
QPixmap pixmap = getIcon(":/icons/bound-expression.svg", QSize(iconHeight, iconHeight));
iconLabel->setPixmap(pixmap);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Text, Qt::lightGray);
lineEdit()->setPalette(p);
}
iconLabel->setExpressionText(Base::Tools::fromStdString(getExpression()->toString()));
}
else {
setReadOnly(false);
QPixmap pixmap = getIcon(":/icons/bound-expression-unset.svg", QSize(iconHeight, iconHeight));
iconLabel->setPixmap(pixmap);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Active, QPalette::Text, defaultPalette.color(QPalette::Text));
lineEdit()->setPalette(p);
iconLabel->setExpressionText(QString());
}
}
catch (const Base::Exception & e) {
setReadOnly(true);
QPalette p(lineEdit()->palette());
p.setColor(QPalette::Active, QPalette::Text, Qt::red);
lineEdit()->setPalette(p);
iconLabel->setToolTip(QString::fromLatin1(e.what()));
}
}
void Gui::QuantitySpinBox::keyPressEvent(QKeyEvent *event)
{
if (event->text() == QString::fromUtf8("=") && isBound())
openFormulaDialog();
else
QAbstractSpinBox::keyPressEvent(event);
}
void Gui::QuantitySpinBox::paintEvent(QPaintEvent*)
{
QStyleOptionSpinBox opt;
initStyleOption(&opt);
if (hasExpression()) {
opt.activeSubControls &= ~QStyle::SC_SpinBoxUp;
opt.activeSubControls &= ~QStyle::SC_SpinBoxDown;
opt.state &= ~QStyle::State_Active;
opt.stepEnabled = StepNone;
}
QStylePainter p(this);
p.drawComplexControl(QStyle::CC_SpinBox, opt);
}
void QuantitySpinBox::updateText(const Quantity &quant)
{
Q_D(QuantitySpinBox);
double dFactor;
QString txt = getUserString(quant, dFactor, d->unitStr);
d->unitValue = quant.getValue()/dFactor;
lineEdit()->setText(txt);
handlePendingEmit();
}
Base::Quantity QuantitySpinBox::value() const
{
Q_D(const QuantitySpinBox);
return d->quantity;
}
double QuantitySpinBox::rawValue() const
{
Q_D(const QuantitySpinBox);
return d->quantity.getValue();
}
void QuantitySpinBox::setValue(const Base::Quantity& value)
{
Q_D(QuantitySpinBox);
d->quantity = value;
// check limits
if (d->quantity.getValue() > d->maximum)
d->quantity.setValue(d->maximum);
if (d->quantity.getValue() < d->minimum)
d->quantity.setValue(d->minimum);
d->unit = value.getUnit();
updateText(value);
}
void QuantitySpinBox::setValue(double value)
{
Q_D(QuantitySpinBox);
setValue(Base::Quantity(value, d->unit));
}
bool QuantitySpinBox::hasValidInput() const
{
Q_D(const QuantitySpinBox);
return d->validInput;
}
// Gets called after call of 'validateAndInterpret'
void QuantitySpinBox::userInput(const QString & text)
{
Q_D(QuantitySpinBox);
d->pendingEmit = true;
QString tmp = text;
Base::Quantity res;
if (d->validate(tmp, res)) {
d->validStr = tmp;
d->validInput = true;
}
else {
d->validInput = false;
return;
}
if (keyboardTracking()) {
d->cached = res;
handlePendingEmit();
}
else {
d->cached = res;
}
}
void QuantitySpinBox::openFormulaDialog()
{
Q_ASSERT(isBound());
Q_D(const QuantitySpinBox);
Gui::Dialog::DlgExpressionInput* box = new Gui::Dialog::DlgExpressionInput(getPath(), getExpression(), d->unit, this);
connect(box, SIGNAL(finished(int)), this, SLOT(finishFormulaDialog()));
box->show();
QPoint pos = mapToGlobal(QPoint(0,0));
box->move(pos-box->expressionPosition());
box->setExpressionInputSize(width(), height());
Q_EMIT showFormulaDialog(true);
}
void QuantitySpinBox::finishFormulaDialog()
{
Gui::Dialog::DlgExpressionInput* box = qobject_cast<Gui::Dialog::DlgExpressionInput*>(sender());
if (!box) {
qWarning() << "Sender is not a Gui::Dialog::DlgExpressionInput";
return;
}
if (box->result() == QDialog::Accepted)
setExpression(box->getExpression());
else if (box->discardedFormula())
setExpression(std::shared_ptr<Expression>());
box->deleteLater();
Q_EMIT showFormulaDialog(false);
}
void QuantitySpinBox::handlePendingEmit()
{
updateFromCache(true);
}
void QuantitySpinBox::updateFromCache(bool notify)
{
Q_D(QuantitySpinBox);
if (d->pendingEmit) {
double factor;
const Base::Quantity& res = d->cached;
QString text = getUserString(res, factor, d->unitStr);
d->unitValue = res.getValue() / factor;
d->quantity = res;
// signaling
if (notify) {
d->pendingEmit = false;
valueChanged(res);
valueChanged(res.getValue());
textChanged(text);
}
}
}
Base::Unit QuantitySpinBox::unit() const
{
Q_D(const QuantitySpinBox);
return d->unit;
}
void QuantitySpinBox::setUnit(const Base::Unit &unit)
{
Q_D(QuantitySpinBox);
d->unit = unit;
d->quantity.setUnit(unit);
updateText(d->quantity);
}
void QuantitySpinBox::setUnitText(const QString& str)
{
try {
Base::Quantity quant = Base::Quantity::parse(str);
setUnit(quant.getUnit());
}
catch (const Base::Exception&) {
}
}
QString QuantitySpinBox::unitText(void)
{
Q_D(QuantitySpinBox);
return d->unitStr;
}
double QuantitySpinBox::singleStep() const
{
Q_D(const QuantitySpinBox);
return d->singleStep;
}
void QuantitySpinBox::setSingleStep(double value)
{
Q_D(QuantitySpinBox);
if (value >= 0) {
d->singleStep = value;
}
}
double QuantitySpinBox::minimum() const
{
Q_D(const QuantitySpinBox);
return d->minimum;
}
void QuantitySpinBox::setMinimum(double minimum)
{
Q_D(QuantitySpinBox);
d->minimum = minimum;
}
double QuantitySpinBox::maximum() const
{
Q_D(const QuantitySpinBox);
return d->maximum;
}
void QuantitySpinBox::setMaximum(double maximum)
{
Q_D(QuantitySpinBox);
d->maximum = maximum;
}
void QuantitySpinBox::setRange(double minimum, double maximum)
{
Q_D(QuantitySpinBox);
d->minimum = minimum;
d->maximum = maximum;
}
int QuantitySpinBox::decimals() const
{
Q_D(const QuantitySpinBox);
return d->quantity.getFormat().precision;
}
void QuantitySpinBox::setDecimals(int v)
{
Q_D(QuantitySpinBox);
Base::QuantityFormat f = d->quantity.getFormat();
f.precision = v;
d->quantity.setFormat(f);
updateText(d->quantity);
}
void QuantitySpinBox::setSchema(const Base::UnitSystem& s)
{
Q_D(QuantitySpinBox);
d->scheme = Base::UnitsApi::createSchema(s);
updateText(d->quantity);
}
void QuantitySpinBox::clearSchema()
{
Q_D(QuantitySpinBox);
d->scheme = nullptr;
updateText(d->quantity);
}
QString QuantitySpinBox::getUserString(const Base::Quantity& val, double& factor, QString& unitString) const
{
Q_D(const QuantitySpinBox);
if (d->scheme) {
return val.getUserString(d->scheme.get(), factor, unitString);
}
else {
return val.getUserString(factor, unitString);
}
}
QString QuantitySpinBox::getUserString(const Base::Quantity& val) const
{
Q_D(const QuantitySpinBox);
if (d->scheme) {
double factor;
QString unitString;
return val.getUserString(d->scheme.get(), factor, unitString);
}
else {
return val.getUserString();
}
}
QAbstractSpinBox::StepEnabled QuantitySpinBox::stepEnabled() const
{
Q_D(const QuantitySpinBox);
if (isReadOnly()/* || !d->validInput*/)
return StepNone;
if (wrapping())
return StepEnabled(StepUpEnabled | StepDownEnabled);
StepEnabled ret = StepNone;
if (d->quantity.getValue() < d->maximum) {
ret |= StepUpEnabled;
}
if (d->quantity.getValue() > d->minimum) {
ret |= StepDownEnabled;
}
return ret;
}
void QuantitySpinBox::stepBy(int steps)
{
Q_D(QuantitySpinBox);
updateFromCache(false);
double step = d->singleStep * steps;
double val = d->unitValue + step;
if (val > d->maximum)
val = d->maximum;
else if (val < d->minimum)
val = d->minimum;
lineEdit()->setText(QString::fromUtf8("%L1 %2").arg(val).arg(d->unitStr));
updateFromCache(true);
update();
selectNumber();
}
QSize QuantitySpinBox::sizeHint() const
{
Q_D(const QuantitySpinBox);
ensurePolished();
const QFontMetrics fm(fontMetrics());
int h = lineEdit()->sizeHint().height();
int w = 0;
QString s;
QString fixedContent = QLatin1String(" ");
Base::Quantity q(d->quantity);
q.setValue(d->maximum);
s = textFromValue(q);
s.truncate(18);
s += fixedContent;
w = qMax(w, QtTools::horizontalAdvance(fm, s));
w += 2; // cursor blinking space
w += iconHeight;
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
QSize size = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
.expandedTo(QApplication::globalStrut());
return size;
}
QSize QuantitySpinBox::minimumSizeHint() const
{
Q_D(const QuantitySpinBox);
ensurePolished();
const QFontMetrics fm(fontMetrics());
int h = lineEdit()->minimumSizeHint().height();
int w = 0;
QString s;
QString fixedContent = QLatin1String(" ");
Base::Quantity q(d->quantity);
q.setValue(d->maximum);
s = textFromValue(q);
s.truncate(18);
s += fixedContent;
w = qMax(w, QtTools::horizontalAdvance(fm, s));
w += 2; // cursor blinking space
w += iconHeight;
QStyleOptionSpinBox opt;
initStyleOption(&opt);
QSize hint(w, h);
QSize size = style()->sizeFromContents(QStyle::CT_SpinBox, &opt, hint, this)
.expandedTo(QApplication::globalStrut());
return size;
}
void QuantitySpinBox::showEvent(QShowEvent * event)
{
Q_D(QuantitySpinBox);
QAbstractSpinBox::showEvent(event);
bool selected = lineEdit()->hasSelectedText();
updateText(d->quantity);
if (selected)
selectNumber();
}
void QuantitySpinBox::hideEvent(QHideEvent * event)
{
handlePendingEmit();
QAbstractSpinBox::hideEvent(event);
}
void QuantitySpinBox::closeEvent(QCloseEvent * event)
{
handlePendingEmit();
QAbstractSpinBox::closeEvent(event);
}
bool QuantitySpinBox::event(QEvent * event)
{
// issue #0004059: Tooltips for Gui::QuantitySpinBox not showing
// Here we must not try to show the tooltip of the icon label
// because it would override a custom tooltip set to this widget.
//
// We could also check if the text of this tooltip is empty but
// it will fail in cases where the widget is embedded into the
// property editor and the corresponding item has set a tooltip.
// Instead of showing the item's tooltip it will again show the
// tooltip of the icon label.
#if 0
if (event->type() == QEvent::ToolTip) {
if (isBound() && getExpression() && lineEdit()->isReadOnly()) {
QHelpEvent * helpEvent = static_cast<QHelpEvent*>(event);
QToolTip::showText( helpEvent->globalPos(), Base::Tools::fromStdString(getExpression()->toString()), this);
event->accept();
return true;
}
}
#endif
return QAbstractSpinBox::event(event);
}
void QuantitySpinBox::focusInEvent(QFocusEvent * event)
{
bool hasSel = lineEdit()->hasSelectedText();
QAbstractSpinBox::focusInEvent(event);
if (event->reason() == Qt::TabFocusReason ||
event->reason() == Qt::BacktabFocusReason ||
event->reason() == Qt::ShortcutFocusReason) {
if (isBound() && getExpression() && lineEdit()->isReadOnly()) {
QHelpEvent * helpEvent = new QHelpEvent(QEvent::ToolTip, QPoint( 0, rect().height() ), mapToGlobal( QPoint( 0, rect().height() ) ));
QApplication::postEvent(this, helpEvent);
lineEdit()->setSelection(0, 0);
}
else {
if (!hasSel)
selectNumber();
}
}
}
void QuantitySpinBox::focusOutEvent(QFocusEvent * event)
{
Q_D(QuantitySpinBox);
int pos = 0;
QString text = lineEdit()->text();
QValidator::State state;
d->validateAndInterpret(text, pos, state);
if (state != QValidator::Acceptable) {
lineEdit()->setText(d->validStr);
}
handlePendingEmit();
QToolTip::hideText();
QAbstractSpinBox::focusOutEvent(event);
}
void QuantitySpinBox::clear()