Debian Codegraph @

src/qml/CIntInput.qml

raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2 // Copyright 2019 Juan Palacios <[email protected]>
3
4 import QtQuick 2.15
5 import QtQuick.Controls 2.15
6 import "Style.js" as Style
7
8 TextField {
9 property int value: 0
10 property alias minValue: range.bottom
11 property alias maxValue: range.top
12
13 text: value
14
15 hoverEnabled: Style.g_hover
16 selectByMouse: true
17
18 padding: Style.TextField.padding
19 horizontalAlignment: TextInput.AlignHCenter
20
21 validator: IntValidator {
22 id: range
23 bottom: 0
24 top: 0
25 }
26
27 onEditingFinished: {
28 var newValue = parseInt(text)
29 if (newValue !== value)
30 p.updateValue(newValue)
31 }
32
33 QtObject {
34 id: p
35
36 property bool restoreTextRequest: false
37 property string newText: ""
38
39 property bool updateValueRequest: false
40 property int newValue: 0
41
42 function restoreText(text) {
43 newText = text
44 restoreTextRequest = true
45 restoreTextRequest = false
46 }
47
48 function updateValue(value) {
49 newValue = value
50 updateValueRequest = true
51 updateValueRequest = false
52 }
53
54 function validateInput() {
55 if (!(text && text.length > 0)) {
56 restoreText(value)
57 }
58 else {
59 var newValue = parseInt(text)
60 if (newValue < range.bottom) {
61 if (value !== range.bottom)
62 updateValue(range.bottom)
63 else
64 restoreText(value)
65 }
66 else if (newValue > range.top) {
67 if (value !== range.top)
68 updateValue(range.top)
69 else
70 restoreText(value)
71 }
72 }
73 }
74 }
75
76 Binding on value {
77 when: p.updateValueRequest
78 value: p.newValue
79 restoreMode: Binding.RestoreBinding
80 }
81
82 Binding on text {
83 when: p.restoreTextRequest
84 value: p.newText
85 restoreMode: Binding.RestoreBinding
86 }
87
88 Keys.onPressed: event => {
89 if (event.key === Qt.Key_Tab ||
90 event.key === Qt.Key_Enter ||
91 event.key === Qt.Key_Return)
92 p.validateInput()
93 else if (event.key === Qt.Key_Escape)
94 p.restoreText(value)
95 }
96
97 onFocusChanged: {
98 if (!activeFocus)
99 p.validateInput()
100 }
101 }