Debian Codegraph @

src/imports/Components/Pickers/1.3/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 lomiri-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 /*!
141 The function positions the picker's view to the given index without animating
142 the view. The component must be ready when calling the function, e.g. to make
143 sure the Picker shows up at the given index, do the following:
144 \qml
145 Picker {
146 model: 120
147 delegate: PickerDelegate {
148 Label {
149 anchors.fill: parent
150 verticalCenter: Text.AlignVCenter
151 text: modelData
152 }
153 }
154 Component.onCompleted: positionViewAtIndex(10)
155 }
156 \endqml
157 */
158 function positionViewAtIndex(index) {
159 if (!loader.item || !internals.completed) {
160 return;
161 }
162 loader.item.positionViewAtIndex(index, loader.isListView ? ListView.SnapPosition : PathView.SnapPosition);
163 // update selectedIndex
164 selectedIndex = loader.item.currentIndex;
165 }
166
167 activeFocusOnPress: true
168
169 styleName: "PickerStyle"
170
171 /*! \internal */
172 property int __clickedIndex: -1
173
174 /*! \internal */
175 property alias ready: loader.completed
176
177 // bind style instance's view property to the Loader's item
178 Binding {
179 target: __styleInstance
180 property: "view"
181 value: loader.item
182 when: __styleInstance && __styleInstance.hasOwnProperty("view") && loader.item
183 }
184
185 /*
186 ListView/PathView do not change moding property when the current index is
187 changed manually. Therefore we use an idle timer to poll the contentY to
188 detect whether the views are still moving.
189 PathView's currentIndex changes while the component is moving, however this
190 is not true for ListView.
191 */
192 Timer {
193 id: movingPoll
194 interval: 50
195 running: false
196 property bool indexChanging: false
197 property real prevContentY
198 onTriggered: {
199 if (prevContentY === loader.item.contentY) {
200 indexChanging = false;
201 } else {
202 kick();
203 }
204 }
205 function kick() {
206 if (!loader.item) return;
207 indexChanging = true;
208 prevContentY = loader.item.contentY;
209 running = true;
210 }
211 }
212
213 // update curentItem automatically when selectedIndex changes
214 Binding {
215 target: loader.item
216 property: "currentIndex"
217 value: picker.selectedIndex
218 when: loader.completed && (picker.selectedIndex > 0)
219 }
220
221 // tumbler
222 Loader {
223 id: loader
224 objectName: "Picker_ViewLoader"
225 asynchronous: false
226 parent: __styleInstance.hasOwnProperty("tumblerHolder") ? __styleInstance.tumblerHolder : picker
227 anchors.fill: parent
228 sourceComponent: circular ? wrapAround : linear
229
230 // property for loading completion
231 property bool completed: item && (status === Loader.Ready) && item.viewCompleted
232
233 // do we have a ListView or PathView?
234 property bool isListView: (item && QuickUtils.className(item) === "QQuickListView")
235
236 // selectedIndex updater, live or non-live ones
237 Connections {
238 target: loader.item
239 ignoreUnknownSignals: true
240 function onMovementEnded() {
241 if (!loader.completed || !model) return;
242 if (!picker.live) {
243 picker.selectedIndex = loader.item.currentIndex;
244 }
245 }
246 function onCurrentIndexChanged() {
247 movingPoll.kick();
248 if (!loader.completed) return;
249 if (picker.live || (modelWatcher.modelSize() <= 0)
250 || (picker.__clickedIndex >= 0 && (picker.__clickedIndex === loader.item.currentIndex))
251 || modelWatcher.cropping) {
252 picker.selectedIndex = loader.item.currentIndex;
253 modelWatcher.cropping = false;
254 picker.__clickedIndex = -1;
255 }
256 }
257 function onModelChanged() {
258 modelWatcher.connectModel(picker.model);
259 if (!loader.completed) return;
260 loader.moveToIndex((loader.completed) ? 0 : picker.selectedIndex);
261 if (loader.completed && !picker.live) {
262 picker.selectedIndex = 0;
263 }
264 }
265 // focus handling
266 function onMoveStarted() { picker.requestFocus(Qt.MouseFocusReason) }
267 function onFlickStarted() { picker.requestFocus(Qt.MouseFocusReason) }
268 }
269
270 function moveToIndex(toIndex) {
271 var count = (loader.item && loader.item.model) ? modelWatcher.modelSize() : -1;
272 if (completed && count > 0) {
273 if (loader.isListView) {
274 loader.item.currentIndex = toIndex;
275 return;
276 } else {
277 loader.item.positionViewAtIndex(count - 1, PathView.Center);
278 loader.item.positionViewAtIndex(toIndex, PathView.Center);
279 }
280 }
281 }
282
283 Component.onCompleted: modelWatcher.connectModel(picker.model);
284 Component.onDestruction: modelWatcher.disconnectModel()
285 }
286
287 // circular list
288 Component {
289 id: wrapAround
290 PathView {
291 id: pView
292 objectName: "Picker_WrapAround"
293 // property declared for PickerDelegate to be able to access the main component
294 property Item pickerItem: picker
295 // property holding view completion
296 property bool viewCompleted: false
297 // declared to ease moving detection
298 property real contentY: offset
299 anchors {
300 top: parent ? parent.top : undefined
301 bottom: parent ? parent.bottom : undefined
302 horizontalCenter: parent ? parent.horizontalCenter : undefined
303 }
304 width: parent ? parent.width : 0
305 clip: true
306 focus: true
307
308 model: picker.model
309 delegate: picker.delegate
310 currentIndex: picker.selectedIndex
311 // put the currentItem to the center of the view
312 preferredHighlightBegin: 0.5
313 preferredHighlightEnd: 0.5
314
315 pathItemCount: pView.height / picker.itemHeight
316 snapMode: PathView.SnapToItem
317 flickDeceleration: 100
318
319 property int contentHeight: pathItemCount * picker.itemHeight
320 path: Path {
321 startX: pView.width / 2
322 startY: -(pView.contentHeight - pView.height) / 2
323 PathLine {
324 x: pView.width / 2
325 y: pView.height + (pView.contentHeight - pView.height) / 2
326 }
327 }
328
329 Component.onCompleted: {
330 var complete = true
331 if (modelWatcher.isObjectModel()) {
332 complete = (model.count > 0);
333 if (model.count >= 2) {
334 positionViewAtIndex(1, PathView.SnapPosition);
335 positionViewAtIndex(0, PathView.SnapPosition);
336 }
337 } else if (model && Object.prototype.toString.call(model) === "[object Number]") {
338 if (model >= 2) {
339 positionViewAtIndex(1, PathView.SnapPosition);
340 positionViewAtIndex(0, PathView.SnapPosition);
341 }
342 }
343
344 viewCompleted = complete;
345 }
346 }
347 }
348
349 // linear list
350 Component {
351 id: linear
352 ListView {
353 id: lView
354 objectName: "Picker_Linear"
355 // property declared for PickerDelegate to be able to access the main component
356 property Item pickerItem: picker
357 // property holding view completion
358 property bool viewCompleted: false
359 anchors {
360 top: parent ? parent.top : undefined
361 bottom: parent ? parent.bottom : undefined
362 horizontalCenter: parent ? parent.horizontalCenter : undefined
363 }
364 width: parent ? parent.width : 0
365 clip: true
366 focus: true
367 Mouse.onClicked: picker.requestFocus(Qt.MouseFocusReason)
368
369 model: picker.model
370 delegate: picker.delegate
371 currentIndex: picker.selectedIndex
372
373 preferredHighlightBegin: (height - (currentItem ? currentItem.height : 0)) / 2
374 preferredHighlightEnd: preferredHighlightBegin + (currentItem ? currentItem.height : 0)
375 highlightRangeMode: ListView.StrictlyEnforceRange
376 highlightMoveDuration: 300
377 flickDeceleration: 100
378
379 Component.onCompleted: viewCompleted = true
380 }
381 }
382
383 /*
384 Watch Picker's model to catch when elements are removed ro model is cleared.
385 We need this to detect currentIndex changes in List/PathViews when non-live
386 update mode is chosen, to know when do we need to update selectedIndex.
387 */
388 QtObject {
389 id: modelWatcher
390
391 property var prevModel
392 property bool cropping: false
393
394 function isObjectModel() {
395 return (prevModel && Object.prototype.toString.call(prevModel) === "[object Object]");
396 }
397
398 function modelSize() {
399 if (prevModel) {
400 if (Object.prototype.toString.call(model) === "[object Object]") {
401 return prevModel.count;
402 } else if (Object.prototype.toString.call(model) === "[object Array]") {
403 return prevModel.length;
404 } else if (Object.prototype.toString.call(model) === "[object Number]") {
405 return prevModel;
406 }
407 }
408 return -1;
409 }
410
411 function connectModel(model) {
412 disconnectModel();
413 prevModel = model;
414 // check if the model is derived from QAbstractListModel
415 if (model && Object.prototype.toString.call(model) === "[object Object]") {
416 model.rowsAboutToBeRemoved.connect(itemsAboutToRemove);
417 model.rowsInserted.connect(updateView);
418 }
419 }
420
421 function disconnectModel() {
422 if (isObjectModel()) {
423 prevModel.rowsAboutToBeRemoved.disconnect(itemsAboutToRemove);
424 prevModel.rowsInserted.disconnect(updateView);
425 }
426 }
427
428 function updateView() {
429 if (!loader.isListView && loader.item.count === 2) {
430 // currentItem gets set upon first flick or move when the model is empty
431 // at the time the component gets completed. Disable viewCompleted till
432 // we move the view so selectedIndex doesn't get altered
433 loader.item.viewCompleted = false;
434 loader.item.positionViewAtIndex(1, PathView.SnapPosition);
435 loader.item.positionViewAtIndex(0, PathView.SnapPosition);
436 loader.item.viewCompleted = true;
437 }
438 }
439
440 function itemsAboutToRemove(parent, start, end) {
441 if ((end - start + 1) === loader.item.count) {
442 cropping = true;
443 } else if (selectedIndex >= start) {
444 // Notify views that the model got cleared or got cropped
445 // the loader.item.currentIndex is not yet updated, so we simply remember
446 // that we need to update when currentIndex change is notified
447 cropping = true;
448 if (selectedIndex <= (start + end)) {
449 // the selection is in between the removed indexes, so move the selection
450 // to the closest available one
451 loader.item.positionViewAtIndex(Math.max(start - 1, 0),
452 (loader.isListView) ? ListView.SnapPosition : PathView.SnapPosition);
453 }
454 }
455 }
456 }
457 }