Debian Codegraph @

src/qml/CustomPickers/1.0/Picker.qml

raw
1 /*
2 * Copyright 2015 Canonical Ltd.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License as published by
6 * the Free Software Foundation; version 3.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 import QtQuick 2.4
18 import Lomiri.Components 1.3
19
20 /*!
21 \qmltype Picker
22 \inqmlmodule Lomiri.Components.Pickers 1.0
23 \ingroup ubuntu-pickers
24 \inherits StyledItem
25 \brief Picker is a slot-machine style value selection component.
26
27 The Picker lists the elements specified by the \l model using the \l delegate
28 vertically using a slot-machine tumbler-like list. The selected item is
29 always the one in the center of the component, and it is represented by the
30 \l selectedIndex property.
31
32 The elements can be either in a circular list or in a normal list.
33
34 Delegates must be composed using PickerDelegate.
35
36 Example:
37 \qml
38 import QtQuick 2.4
39 import Lomiri.Components 1.3
40 import Lomiri.Components.Pickers 1.0
41
42 Picker {
43 model: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"]
44 delegate: PickerDelegate {
45 Label {
46 text: modelData
47 }
48 }
49 selectedIndex: 5
50 onSelectedIndexChanged: {
51 print("selected month: " + selectedIndex);
52 }
53 }
54 \endqml
55
56 \b Note: the \l selectedIndex must be set explicitly to the desired index if
57 the model is set, filled or changed after the component is complete. In the
58 following example the selected item must be set after the model is set.
59
60 \qml
61 Picker {
62 selectedIndex: 5 // this will be set to 0 at the model completion
63 delegate: PickerDelegate {
64 Label {
65 text: modelData
66 }
67 }
68 Component.onCompleted: {
69 var stack = [];
70 for (var i = 0; i < 10; i++) {
71 stack.push("Line " + i);
72 }
73 model = stack;
74 // selectedIndex must be set explicitly
75 selectedIndex = 3;
76 }
77 }
78 \endqml
79
80 \section3 Known issues
81 \list
82 \li [1] Circular picker does not react on touch generated flicks (on touch
83 enabled devices) when nested into a Flickable -
84 \l {https://bugreports.qt-project.org/browse/QTBUG-30840}
85 \li [2] Circular picker sets \l selectedIndex to 0 when the model is cleared,
86 contrary to linear one, which sets it to -1 -
87 \l {https://bugreports.qt-project.org/browse/QTBUG-35400}
88 \endlist
89 */
90
91 StyledItem {
92 id: picker
93
94 /*!
95 Property specifying whether the tumbler list is wrap-around (\a true), or
96 normal (\a false). Default value is true.
97 */
98 property bool circular: true
99
100 /*!
101 Specifies the model listing the content of the picker.
102 */
103 property var model
104
105 /*!
106 The delegate visualizing the model elements. Any kind of component can be
107 used as delegate, however it is recommended to use \l PickerDelegate, which
108 integrates selection functionality into the Picker.
109 */
110 property Component delegate
111
112 /*!
113 The property holds the index of the selected item
114 */
115 property int selectedIndex
116
117 /*!
118 Defines whether the \l selectedIndex should be updated while the tumbler
119 changes the selected item during draggingm or only when the tumbler's motion
120 ends. The default behavior is non-live update.
121 */
122 property bool live: false
123
124 /*!
125 The property holds whether the picker's view is moving due to the user
126 interaction either by dragging, flicking or due to the manual change of
127 the selectedIndex property.
128 */
129 readonly property bool moving: (loader.item ? loader.item.moving : false) || movingPoll.indexChanging
130
131 /*!
132 \since Lomiri.Components.Pickers 1.3
133 The property specifies the defautl height of the PickerDelegates. It is
134 recommended to change the delegate height through this property rather than
135 changing it from the delegate itself.
136 */
137 property real itemHeight: units.gu(4)
138
139 /*!
140 The function positions the picker's view to the given index without animating
141 the view. The component must be ready when calling the function, e.g. to make
142 sure the Picker shows up at the given index, do the following:
143 \qml
144 Picker {
145 model: 120
146 delegate: PickerDelegate {
147 Label {
148 anchors.fill: parent
149 verticalCenter: Text.AlignVCenter
150 text: modelData
151 }
152 }
153 Component.onCompleted: positionViewAtIndex(10)
154 }
155 \endqml
156 */
157 function positionViewAtIndex(index) {
158 if (!loader.item || !internals.completed) {
159 return;
160 }
161 loader.item.positionViewAtIndex(index, loader.isListView ? ListView.SnapPosition : PathView.SnapPosition);
162 // update selectedIndex
163 selectedIndex = loader.item.currentIndex;
164 }
165
166 activeFocusOnPress: true
167
168 styleName: "PickerStyle"
169
170 /*! \internal */
171 property int __clickedIndex: -1
172
173 // bind style instance's view property to the Loader's item
174 Binding {
175 target: __styleInstance
176 property: "view"
177 value: loader.item
178 when: __styleInstance && __styleInstance.hasOwnProperty("view") && loader.item
179 }
180
181 /*
182 ListView/PathView do not change moding property when the current index is
183 changed manually. Therefore we use an idle timer to poll the contentY to
184 detect whether the views are still moving.
185 PathView's currentIndex changes while the component is moving, however this
186 is not true for ListView.
187 */
188 Timer {
189 id: movingPoll
190 interval: 50
191 running: false
192 property bool indexChanging: false
193 property real prevContentY
194 onTriggered: {
195 if (prevContentY === loader.item.contentY) {
196 indexChanging = false;
197 } else {
198 kick();
199 }
200 }
201 function kick() {
202 if (!loader.item) return;
203 indexChanging = true;
204 prevContentY = loader.item.contentY;
205 running = true;
206 }
207 }
208
209 // tumbler
210 Loader {
211 id: loader
212 objectName: "Picker_ViewLoader"
213 asynchronous: false
214 parent: __styleInstance.hasOwnProperty("tumblerHolder") ? __styleInstance.tumblerHolder : picker
215 anchors.fill: parent
216 sourceComponent: circular ? wrapAround : linear
217
218 // property for loading completion
219 property bool completed: item && (status === Loader.Ready) && item.viewCompleted
220
221 // do we have a ListView or PathView?
222 property bool isListView: (item && QuickUtils.className(item) === "QQuickListView")
223
224 // update curentItem automatically when selectedIndex changes
225 Binding {
226 target: loader.item
227 property: "currentIndex"
228 value: picker.selectedIndex
229 when: loader.completed && (picker.selectedIndex > 0)
230 }
231
232 // selectedIndex updater, live or non-live ones
233 Connections {
234 target: loader.item
235 ignoreUnknownSignals: true
236 onMovementEnded: {
237 if (!loader.completed || !model) return;
238 if (!picker.live) {
239 picker.selectedIndex = loader.item.currentIndex;
240 }
241 }
242 onCurrentIndexChanged: {
243 movingPoll.kick();
244 if (!loader.completed) return;
245 if (picker.live || (modelWatcher.modelSize() <= 0)
246 || (picker.__clickedIndex >= 0 && (picker.__clickedIndex === loader.item.currentIndex))
247 || modelWatcher.cropping) {
248 picker.selectedIndex = loader.item.currentIndex;
249 modelWatcher.cropping = false;
250 picker.__clickedIndex = -1;
251 }
252 }
253 onModelChanged: {
254 modelWatcher.connectModel(picker.model);
255 if (!loader.completed) return;
256 loader.moveToIndex((loader.completed) ? 0 : picker.selectedIndex);
257 if (loader.completed && !picker.live) {
258 picker.selectedIndex = 0;
259 }
260 }
261 // focus handling
262 onMoveStarted: picker.requestFocus(Qt.MouseFocusReason)
263 onFlickStarted: picker.requestFocus(Qt.MouseFocusReason)
264 }
265
266 function moveToIndex(toIndex) {
267 var count = (loader.item && loader.item.model) ? modelWatcher.modelSize() : -1;
268 if (completed && count > 0) {
269 if (loader.isListView) {
270 loader.item.currentIndex = toIndex;
271 return;
272 } else {
273 loader.item.positionViewAtIndex(count - 1, PathView.Center);
274 loader.item.positionViewAtIndex(toIndex, PathView.Center);
275 }
276 }
277 }
278
279 Component.onCompleted: modelWatcher.connectModel(picker.model);
280 Component.onDestruction: modelWatcher.disconnectModel()
281 }
282
283 // circular list
284 Component {
285 id: wrapAround
286 PathView {
287 id: pView
288 objectName: "Picker_WrapAround"
289 // property declared for PickerDelegate to be able to access the main component
290 property Item pickerItem: picker
291 // property holding view completion
292 property bool viewCompleted: false
293 // declared to ease moving detection
294 property real contentY: offset
295 anchors {
296 top: parent ? parent.top : undefined
297 bottom: parent ? parent.bottom : undefined
298 horizontalCenter: parent ? parent.horizontalCenter : undefined
299 }
300 width: parent ? parent.width : 0
301 clip: true
302 focus: true
303
304 model: picker.model
305 delegate: picker.delegate
306 currentIndex: picker.selectedIndex
307 // put the currentItem to the center of the view
308 preferredHighlightBegin: 0.5
309 preferredHighlightEnd: 0.5
310
311 pathItemCount: pView.height / picker.itemHeight
312 snapMode: PathView.SnapToItem
313 flickDeceleration: 100
314
315 property int contentHeight: pathItemCount * picker.itemHeight
316 path: Path {
317 startX: pView.width / 2
318 startY: -(pView.contentHeight - pView.height) / 2
319 PathLine {
320 x: pView.width / 2
321 y: pView.height + (pView.contentHeight - pView.height) / 2
322 }
323 }
324
325 Component.onCompleted: {
326 var complete = true
327 if (modelWatcher.isObjectModel()) {
328 complete = (model.count > 0);
329 if (model.count >= 2) {
330 positionViewAtIndex(1, PathView.SnapPosition);
331 positionViewAtIndex(0, PathView.SnapPosition);
332 }
333 } else if (Object.prototype.toString.call(model) === "[object Number]") {
334 if (model >= 2) {
335 positionViewAtIndex(1, PathView.SnapPosition);
336 positionViewAtIndex(0, PathView.SnapPosition);
337 }
338 }
339
340 viewCompleted = complete;
341 }
342 }
343 }
344
345 // linear list
346 Component {
347 id: linear
348 ListView {
349 id: lView
350 objectName: "Picker_Linear"
351 // property declared for PickerDelegate to be able to access the main component
352 property Item pickerItem: picker
353 // property holding view completion
354 property bool viewCompleted: false
355 anchors {
356 top: parent ? parent.top : undefined
357 bottom: parent ? parent.bottom : undefined
358 horizontalCenter: parent ? parent.horizontalCenter : undefined
359 }
360 width: parent ? parent.width : 0
361 clip: true
362 focus: true
363 Mouse.onClicked: picker.requestFocus(Qt.MouseFocusReason)
364
365 model: picker.model
366 delegate: picker.delegate
367 currentIndex: picker.selectedIndex
368
369 preferredHighlightBegin: (height - (currentItem ? currentItem.height : 0)) / 2
370 preferredHighlightEnd: preferredHighlightBegin + (currentItem ? currentItem.height : 0)
371 highlightRangeMode: ListView.StrictlyEnforceRange
372 highlightMoveDuration: 300
373 flickDeceleration: 100
374
375 Component.onCompleted: viewCompleted = true
376 }
377 }
378
379 /*
380 Watch Picker's model to catch when elements are removed ro model is cleared.
381 We need this to detect currentIndex changes in List/PathViews when non-live
382 update mode is chosen, to know when do we need to update selectedIndex.
383 */
384 QtObject {
385 id: modelWatcher
386
387 property var prevModel
388 property bool cropping: false
389
390 function isObjectModel() {
391 return (prevModel && Object.prototype.toString.call(prevModel) === "[object Object]");
392 }
393
394 function modelSize() {
395 if (prevModel) {
396 if (Object.prototype.toString.call(model) === "[object Object]") {
397 return prevModel.count;
398 } else if (Object.prototype.toString.call(model) === "[object Array]") {
399 return prevModel.length;
400 } else if (Object.prototype.toString.call(model) === "[object Number]") {
401 return prevModel;
402 }
403 }
404 return -1;
405 }
406
407 function connectModel(model) {
408 disconnectModel();
409 prevModel = model;
410 // check if the model is derived from QAbstractListModel
411 if (model && Object.prototype.toString.call(model) === "[object Object]") {
412 model.rowsAboutToBeRemoved.connect(itemsAboutToRemove);
413 model.rowsInserted.connect(updateView);
414 }
415 }
416
417 function disconnectModel() {
418 if (isObjectModel()) {
419 prevModel.rowsAboutToBeRemoved.disconnect(itemsAboutToRemove);
420 prevModel.rowsInserted.disconnect(updateView);
421 }
422 }
423
424 function updateView() {
425 if (!loader.isListView && loader.item.count === 2) {
426 // currentItem gets set upon first flick or move when the model is empty
427 // at the time the component gets completed. Disable viewCompleted till
428 // we move the view so selectedIndex doesn't get altered
429 loader.item.viewCompleted = false;
430 loader.item.positionViewAtIndex(1, PathView.SnapPosition);
431 loader.item.positionViewAtIndex(0, PathView.SnapPosition);
432 loader.item.viewCompleted = true;
433 }
434 }
435
436 function itemsAboutToRemove(parent, start, end) {
437 if ((end - start + 1) === loader.item.count) {
438 cropping = true;
439 } else if (selectedIndex >= start) {
440 // Notify views that the model got cleared or got cropped
441 // the loader.item.currentIndex is not yet updated, so we simply remember
442 // that we need to update when currentIndex change is notified
443 cropping = true;
444 if (selectedIndex <= (start + end)) {
445 // the selection is in between the removed indexes, so move the selection
446 // to the closest available one
447 loader.item.positionViewAtIndex(Math.max(start - 1, 0),
448 (loader.isListView) ? ListView.SnapPosition : PathView.SnapPosition);
449 }
450 }
451 }
452 }
453 }