summaryrefslogtreecommitdiff
path: root/src/controls/ComboBox.qml
blob: 7891cd44e91d927982e736e49804b1393c4659c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Controls module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

import QtQuick 2.2
import QtQuick.Controls 1.2
import QtQuick.Controls.Private 1.0

/*!
    \qmltype ComboBox
    \inqmlmodule QtQuick.Controls
    \since 5.1
    \ingroup controls
    \brief Provides a drop-down list functionality.

    \image combobox.png

    Add items to the ComboBox by assigning it a ListModel, or a list of strings
    to the \l model property.

    \qml
       ComboBox {
           width: 200
           model: [ "Banana", "Apple", "Coconut" ]
       }
    \endqml

    In this example we are demonstrating how to use a ListModel with a combo box.

    \qml
       ComboBox {
           currentIndex: 2
           model: ListModel {
               id: cbItems
               ListElement { text: "Banana"; color: "Yellow" }
               ListElement { text: "Apple"; color: "Green" }
               ListElement { text: "Coconut"; color: "Brown" }
           }
           width: 200
           onCurrentIndexChanged: console.debug(cbItems.get(currentIndex).text + ", " + cbItems.get(currentIndex).color)
       }
    \endqml

    You can make a combo box editable by setting the \l editable property. An editable combo box will
    autocomplete its text based on what is available in the model.

    In the next example we demonstrate how you can append content to an editable combo box by
    reacting to the \l accepted signal. Note that you have to explicitly prevent duplicates.

    \qml
        ComboBox {
            editable: true
            model: ListModel {
                id: model
                ListElement { text: "Banana"; color: "Yellow" }
                ListElement { text: "Apple"; color: "Green" }
                ListElement { text: "Coconut"; color: "Brown" }
            }
            onAccepted: {
                if (find(currentText) === -1) {
                    model.append({text: editText})
                    currentIndex = find(editText)
                }
            }
        }
    \endqml


    You can create a custom appearance for a ComboBox by
    assigning a \l {QtQuick.Controls.Styles::ComboBoxStyle}{ComboBoxStyle}.
*/

Control {
    id: comboBox

    /*! \qmlproperty model ComboBox::model
        The model to populate the ComboBox from.

        Changing the model after initialization will reset \l currentIndex to \c 0.
    */
    property alias model: popupItems.model

    /*! The model role used for populating the ComboBox. */
    property string textRole: ""

    /*! \qmlproperty int ComboBox::currentIndex
        The index of the currently selected item in the ComboBox.

        Setting currentIndex to \c -1 will reset the selection and clear the text
        label. If \l editable is \c true, you may also need to manually clear \l editText.

        \sa model
    */
    property alias currentIndex: popup.__selectedIndex

    /*! \qmlproperty string ComboBox::currentText
        The text of the currently selected item in the ComboBox.

        \note Since \c currentText depends on \c currentIndex, there's no way to ensure \c currentText
        will be up to date whenever a \c onCurrentIndexChanged handler is called.
    */
    readonly property alias currentText: popup.currentText

    /*! This property holds whether the combo box can be edited by the user.
     The default value is \c false.
     \since QtQuick.Controls 1.1
    */
    property bool editable: false

    /*! \qmlproperty string ComboBox::editText
        \since QtQuick.Controls 1.1
        This property specifies text being manipulated by the user for an editable combo box.
    */
    property alias editText: input.text

    /*! This property specifies whether the combobox should gain active focus when pressed.
        The default value is \c false. */
    property bool activeFocusOnPress: false

    /*! \qmlproperty bool ComboBox::pressed

        This property holds whether the button is being pressed. */
    readonly property bool pressed: mouseArea.effectivePressed || popup.__popupVisible

    /*! \qmlproperty bool ComboBox::hovered

        This property indicates whether the control is being hovered.
    */
    readonly property bool hovered: mouseArea.containsMouse || input.containsMouse

    /*! \qmlproperty int ComboBox::count
        \since QtQuick.Controls 1.1
        This property holds the number of items in the combo box.
    */
    readonly property alias count: popupItems.count

    /*! Returns the text for a given \a index.
        If an invalid index is provided, \c null is returned
        \since QtQuick.Controls 1.1
    */
    function textAt (index) {
        if (index >= count || index < 0)
            return null;
        return popupItems.objectAt(index).text;
    }

    /*! Finds and returns the index of a given \a text
        If no match is found, \c -1 is returned. The search is case sensitive.
        \since QtQuick.Controls 1.1
    */
    function find (text) {
        return input.find(text, Qt.MatchExactly)
    }

    /*!
        \qmlproperty Validator ComboBox::validator
        \since QtQuick.Controls 1.1

        Allows you to set a text validator for an editable ComboBox.
        When a validator is set,
        the text field will only accept input which leaves the text property in
        an intermediate state. The accepted signal will only be sent
        if the text is in an acceptable state when enter is pressed.

        Currently supported validators are \l{QtQuick::}{IntValidator},
        \l{QtQuick::}{DoubleValidator}, and \l{QtQuick::}{RegExpValidator}. An
        example of using validators is shown below, which allows input of
        integers between 11 and 31 into the text field:

        \note This property is only applied when \l editable is \c true

        \qml
        import QtQuick 2.2
        import QtQuick.Controls 1.2

        ComboBox {
            editable: true
            model: 10
            validator: IntValidator {bottom: 0; top: 10;}
            focus: true
        }
        \endqml

        \sa acceptableInput, accepted, editable
    */
    property alias validator: input.validator

    /*!
        \since QtQuick.Controls 1.3

        This property contains the edit \l Menu for working
        with text selection. Set it to \c null if no menu
        is wanted.

        \note The menu is only in use when \l editable is \c true
    */
    property Component menu: input.editMenu.defaultMenu

    /*!
        \qmlproperty bool ComboBox::acceptableInput
        \since QtQuick.Controls 1.1

        Returns \c true if the combo box contains acceptable
        text in the editable text field.

        If a validator was set, this property will return \c
        true if the current text satisfies the validator or mask as
        a final string (not as an intermediate string).

        \sa validator, accepted

    */
    readonly property alias acceptableInput: input.acceptableInput

    /*!
        \qmlproperty bool ComboBox::selectByMouse
        \since QtQuick.Controls 1.3

        This property determines if the user can select the text in
        the editable text field with the mouse.

        The default value is \c true.
    */
    property bool selectByMouse: true

    /*!
        \qmlproperty bool ComboBox::inputMethodComposing
        \since QtQuick.Controls 1.3

        This property holds whether an editable ComboBox has partial text input from an input method.

        While it is composing an input method may rely on mouse or key events from the ComboBox
        to edit or commit the partial text. This property can be used to determine when to disable
        events handlers that may interfere with the correct operation of an input method.
    */
    readonly property bool inputMethodComposing: !!input.inputMethodComposing

    /*!
        \qmlsignal ComboBox::accepted()
        \since QtQuick.Controls 1.1

        This signal is emitted when the Return or Enter key is pressed on an
        \l editable combo box. If the confirmed string is not currently in the model,
        the currentIndex will be set to -1 and the \l currentText will be updated
        accordingly.

        \note If there is a \l validator set on the combobox,
        the signal will only be emitted if the input is in an acceptable state.

        The corresponding handler is \c onAccepted.
    */
    signal accepted

    /*!
        \qmlsignal ComboBox::activated(int index)
        \since QtQuick.Controls 1.1

        \a index is the triggered model index or -1 if a new string is accepted

        This signal is similar to currentIndex changed, but will only
        be emitted if the combo box index was changed by the user and not
        when set programatically.

        The corresponding handler is \c onActivated.
    */
    signal activated(int index)

    /*!
        \qmlmethod ComboBox::selectAll()
        \since QtQuick.Controls 1.1

        Causes all \l editText to be selected.
    */
    function selectAll() {
        input.selectAll()
    }

    /*! \internal */
    function __selectPrevItem() {
        input.blockUpdate = true
        if (currentIndex > 0) {
            currentIndex--;
            input.text = popup.currentText;
            activated(currentIndex);
        }
        input.blockUpdate = false;
    }

    /*! \internal */
    function __selectNextItem() {
        input.blockUpdate = true;
        if (currentIndex < popupItems.count - 1) {
            currentIndex++;
            input.text = popup.currentText;
            activated(currentIndex);
        }
        input.blockUpdate = false;
    }

    /*! \internal */
    property var __popup: popup

    style: Qt.createComponent(Settings.style + "/ComboBoxStyle.qml", comboBox)

    activeFocusOnTab: true

    Accessible.name: editable ? editText : currentText
    Accessible.role: Accessible.ComboBox
    Accessible.editable: editable

    MouseArea {
        id: mouseArea
        property bool overridePressed: false
        readonly property bool effectivePressed: (pressed || overridePressed) && containsMouse
        anchors.fill: parent
        hoverEnabled: Settings.hoverEnabled
        onPressed: {
            if (comboBox.activeFocusOnPress)
                forceActiveFocus()
            if (!Settings.hasTouchScreen)
                popup.toggleShow()
            else
                overridePressed = true
        }
        onCanceled: overridePressed = false
        onClicked: {
            if (Settings.hasTouchScreen)
                popup.toggleShow()
            overridePressed = false
        }
        onWheel: {
            if (wheel.angleDelta.y > 0) {
                __selectPrevItem();
            } else if (wheel.angleDelta.y < 0){
                __selectNextItem();
            }
        }
    }

    Component.onCompleted: {
        if (currentIndex === -1)
            currentIndex = 0

        popup.ready = true
        popup.resolveTextValue(textRole)
    }

    Keys.onPressed: {
        // Perform one-character based lookup for non-editable combo box
        if (!editable && event.text.length > 0) {
            var index = input.find(event.text, Qt.MatchStartsWith);
            if (index >= 0 && index !== currentIndex) {
                currentIndex = index;
                activated(currentIndex);
            }
        }
    }

    TextInputWithHandles {
        id: input

        visible: editable
        enabled: editable
        focus: true
        clip: contentWidth > width

        control: comboBox
        cursorHandle: __style ? __style.__cursorHandle : undefined
        selectionHandle: __style ? __style.__selectionHandle : undefined

        anchors.fill: parent
        anchors.leftMargin: __style ? __style.padding.left : 0
        anchors.topMargin: __style ? __style.padding.top : 0
        anchors.rightMargin: __style ? __panel.dropDownButtonWidth + __style.padding.right : 0
        anchors.bottomMargin: __style ? __style.padding.bottom: 0

        verticalAlignment: Text.AlignVCenter

        font: __panel && __panel.font !== undefined ? __panel.font : TextSingleton.font
        renderType: __style ? __style.renderType : Text.NativeRendering
        color: __panel ? __panel.textColor : "black"
        selectionColor: __panel ? __panel.selectionColor : "blue"
        selectedTextColor: __panel ? __panel.selectedTextColor : "white"
        onAccepted: {
            var idx = input.find(editText, Qt.MatchFixedString)
            if (idx > -1) {
                editTextMatches = true;
                currentIndex = idx;
                editText = textAt(idx);
            } else {
                editTextMatches = false;
                currentIndex = -1;
                popup.currentText = editText;
            }
            comboBox.accepted();
        }

        property bool blockUpdate: false
        property string prevText
        property bool editTextMatches: true

        function find (text, searchType) {
            for (var i = 0 ; i < popupItems.count ; ++i) {
                var currentString = popupItems.objectAt(i).text
                if (searchType === Qt.MatchExactly) {
                    if (text === currentString)
                        return i;
                } else if (searchType === Qt.CaseSensitive) {
                    if (currentString.indexOf(text) === 0)
                        return i;
                } else if (searchType === Qt.MatchFixedString) {
                    if (currentString.toLowerCase().indexOf(text.toLowerCase()) === 0
                            && currentString.length === text.length)
                        return i;
                } else if (currentString.toLowerCase().indexOf(text.toLowerCase()) === 0) {
                    return i
                }
            }
            return -1;
        }

        // Finds first entry and shortest entry. Used by editable combo
        function tryComplete (inputText) {
            var candidate = "";
            var shortestString = "";
            for (var i = 0 ; i < popupItems.count ; ++i) {
                var currentString = popupItems.objectAt(i).text;

                if (currentString.toLowerCase().indexOf(inputText.toLowerCase()) === 0) {
                    if (candidate.length) { // Find smallest possible match
                        var cmp = 0;

                        // We try to complete the shortest string that matches our search
                        if (currentString.length < candidate.length)
                            candidate = currentString

                        while (cmp < Math.min(currentString.length, shortestString.length)
                               && shortestString[cmp].toLowerCase() === currentString[cmp].toLowerCase())
                            cmp++;
                        shortestString = shortestString.substring(0, cmp);
                    } else { // First match, select as current index and find other matches
                        candidate = currentString;
                        shortestString = currentString;
                    }
                }
            }

            if (candidate.length)
                return inputText + candidate.substring(inputText.length, candidate.length);
            return inputText;
        }

        property bool allowComplete: false
        Keys.forwardTo: comboBox
        Keys.onPressed: allowComplete = (event.key !== Qt.Key_Backspace && event.key !== Qt.Key_Delete);

        onTextChanged: {
            if (editable && !blockUpdate && allowComplete && text.length > 0) {
                var completed = input.tryComplete(text)
                if (completed.length > text.length) {
                    var oldtext = input.text;
                    input.text = completed;
                    input.select(text.length, oldtext.length);
                }
            }
            prevText = text
        }
    }

    Binding {
        target: input
        property: "text"
        value: popup.currentText
        when: input.editTextMatches
    }

    onTextRoleChanged: popup.resolveTextValue(textRole)

    Menu {
        id: popup
        objectName: "popup"

        style: isPopup ? __style.__popupStyle : __style.__dropDownStyle

        property string currentText: selectedText
        onSelectedTextChanged: if (selectedText) popup.currentText = selectedText

        property string selectedText
        on__SelectedIndexChanged: {
            if (__selectedIndex === -1)
                popup.currentText = ""
            else
                updateSelectedText()
        }
        property string textRole: ""

        property bool ready: false
        property bool isPopup: !editable && !!__panel && __panel.popup

        property int y: isPopup ? (comboBox.__panel.height - comboBox.__panel.implicitHeight) / 2.0 : comboBox.__panel.height
        __minimumWidth: comboBox.width
        __visualItem: comboBox

        property ExclusiveGroup eg: ExclusiveGroup { id: eg }

        property bool modelIsArray: false

        Instantiator {
            id: popupItems
            active: false

            property bool updatingModel: false
            onModelChanged: {
                popup.modelIsArray = !!model ? model.constructor === Array : false
                if (active) {
                    if (updatingModel && popup.__selectedIndex === 0) {
                        // We still want to update the currentText
                        popup.updateSelectedText()
                    } else {
                        updatingModel = true
                        popup.__selectedIndex = 0
                    }
                }
                popup.resolveTextValue(comboBox.textRole)
            }

            MenuItem {
                text: popup.textRole === '' ?
                        modelData :
                          ((popup.modelIsArray ? modelData[popup.textRole] : model[popup.textRole]) || '')
                onTriggered: {
                    if (index !== currentIndex)
                        activated(index)
                    comboBox.editText = text
                }
                checkable: true
                exclusiveGroup: eg
            }
            onObjectAdded: {
                popup.insertItem(index, object)
                if (!updatingModel && index === popup.__selectedIndex)
                    popup.selectedText = object["text"]
            }
            onObjectRemoved: popup.removeItem(object)

        }

        function resolveTextValue(initialTextRole) {
            if (!ready || !model) {
                popupItems.active = false
                return;
            }

            var get = model['get'];
            if (!get && popup.modelIsArray && !!model[0]) {
                if (model[0].constructor !== String && model[0].constructor !== Number)
                    get = function(i) { return model[i]; }
            }

            var modelMayHaveRoles = get !== undefined
            textRole = initialTextRole
            if (textRole === "" && modelMayHaveRoles && get(0)) {
                // No text role set, check whether model has a suitable role
                // If 'text' is found, or there's only one role, pick that.
                var listElement = get(0)
                var roleName = ""
                var roleCount = 0
                for (var role in listElement) {
                    if (listElement[role].constructor === Function)
                        continue;
                    if (role === "text") {
                        roleName = role
                        break
                    } else if (!roleName) {
                        roleName = role
                    }
                    ++roleCount
                }
                if (roleCount > 1 && roleName !== "text") {
                    console.warn("No suitable 'textRole' found for ComboBox.")
                } else {
                    textRole = roleName
                }
            }

            if (!popupItems.active)
                popupItems.active = true
            else
                updateSelectedText()
        }

        function toggleShow() {
            if (popup.__popupVisible) {
                popup.__dismissMenu()
                popup.__destroyAllMenuPopups()
            } else {
                if (items[__selectedIndex])
                    items[__selectedIndex].checked = true
                __currentIndex = comboBox.currentIndex
                if (Qt.application.layoutDirection === Qt.RightToLeft)
                    __popup(Qt.rect(comboBox.width, y, 0, 0), isPopup ? __selectedIndex : 0)
                else
                    __popup(Qt.rect(0, y, 0, 0), isPopup ? __selectedIndex : 0)
            }
        }

        function updateSelectedText() {
            var selectedItem;
            if (__selectedIndex !== -1 && (selectedItem = items[__selectedIndex])) {
                input.editTextMatches = true
                selectedText = selectedItem.text
                if (currentText !== selectedText) // __selectedIndex went form -1 to 0
                    selectedTextChanged()
            }
        }
    }

    // The key bindings below will only be in use when popup is
    // not visible. Otherwise, native popup key handling will take place:
    Keys.onSpacePressed: {
        if (!editable)
            popup.toggleShow()
        else
            event.accepted = false
    }

    Keys.onUpPressed: __selectPrevItem()
    Keys.onDownPressed: __selectNextItem()
}