loom
110 строк · 2.2 Кб
1#include "NumberSourceDataModel.hpp"
2
3#include "DecimalData.hpp"
4
5#include <QtCore/QJsonValue>
6#include <QtGui/QDoubleValidator>
7#include <QtWidgets/QLineEdit>
8
9NumberSourceDataModel::NumberSourceDataModel()
10: _number(std::make_shared<DecimalData>(0.0))
11, _lineEdit{nullptr}
12{}
13
14QJsonObject NumberSourceDataModel::save() const
15{
16QJsonObject modelJson = NodeDelegateModel::save();
17
18modelJson["number"] = QString::number(_number->number());
19
20return modelJson;
21}
22
23void NumberSourceDataModel::load(QJsonObject const &p)
24{
25QJsonValue v = p["number"];
26
27if (!v.isUndefined()) {
28QString strNum = v.toString();
29
30bool ok;
31double d = strNum.toDouble(&ok);
32if (ok) {
33_number = std::make_shared<DecimalData>(d);
34
35if (_lineEdit)
36_lineEdit->setText(strNum);
37}
38}
39}
40
41unsigned int NumberSourceDataModel::nPorts(PortType portType) const
42{
43unsigned int result = 1;
44
45switch (portType) {
46case PortType::In:
47result = 0;
48break;
49
50case PortType::Out:
51result = 1;
52
53default:
54break;
55}
56
57return result;
58}
59
60void NumberSourceDataModel::onTextEdited(QString const &str)
61{
62bool ok = false;
63
64double number = str.toDouble(&ok);
65
66if (ok) {
67_number = std::make_shared<DecimalData>(number);
68
69Q_EMIT dataUpdated(0);
70
71} else {
72Q_EMIT dataInvalidated(0);
73}
74}
75
76NodeDataType NumberSourceDataModel::dataType(PortType, PortIndex) const
77{
78return DecimalData().type();
79}
80
81std::shared_ptr<NodeData> NumberSourceDataModel::outData(PortIndex)
82{
83return _number;
84}
85
86QWidget *NumberSourceDataModel::embeddedWidget()
87{
88if (!_lineEdit) {
89_lineEdit = new QLineEdit();
90
91_lineEdit->setValidator(new QDoubleValidator());
92_lineEdit->setMaximumSize(_lineEdit->sizeHint());
93
94connect(_lineEdit, &QLineEdit::textChanged, this, &NumberSourceDataModel::onTextEdited);
95
96_lineEdit->setText(QString::number(_number->number()));
97}
98
99return _lineEdit;
100}
101
102void NumberSourceDataModel::setNumber(double n)
103{
104_number = std::make_shared<DecimalData>(n);
105
106Q_EMIT dataUpdated(0);
107
108if (_lineEdit)
109_lineEdit->setText(QString::number(_number->number()));
110}
111