Debian Codegraph @

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