Debian Codegraph @

src/imports/Components/Pickers/1.2/Picker.qml

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