Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qquickcombobox.cpp
Go to the documentation of this file.
1// Copyright (C) 2017 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
13
14#include <QtCore/qregularexpression.h>
15#include <QtCore/qabstractitemmodel.h>
16#include <QtCore/qglobal.h>
17#include <QtGui/qinputmethod.h>
18#include <QtGui/qtextdocument.h>
19#include <QtGui/qguiapplication.h>
20#include <QtGui/private/qguiapplication_p.h>
21#include <QtGui/qpa/qplatformtheme.h>
22#include <QtQml/qjsvalue.h>
23#include <QtQml/qqmlcontext.h>
24#include <QtQml/qqmlcomponent.h>
25#include <QtQml/private/qlazilyallocated_p.h>
26#include <private/qqmldelegatemodel_p.h>
27#include <QtQuick/private/qquickaccessibleattached_p.h>
28#include <QtQuick/private/qquickevents_p_p.h>
29#include <QtQuick/private/qquicktextinput_p.h>
30#include <QtQuick/private/qquicktextinput_p_p.h>
31#if QT_CONFIG(quick_itemview)
32#include <QtQuick/private/qquickitemview_p.h>
33#endif
34
36
37Q_STATIC_LOGGING_CATEGORY(lcCalculateWidestTextWidth, "qt.quick.controls.combobox.calculatewidesttextwidth")
38
39/*!
40 \qmltype ComboBox
41 \inherits Control
42//! \nativetype QQuickComboBox
43 \inqmlmodule QtQuick.Controls
44 \since 5.7
45 \ingroup qtquickcontrols-input
46 \ingroup qtquickcontrols-focusscopes
47 \brief Combined button and popup list for selecting options.
48
49 \image qtquickcontrols-combobox.gif
50 {Combo box expanding to show dropdown list}
51
52 ComboBox is a combined button and popup list. It provides a means of
53 presenting a list of options to the user in a way that takes up the
54 minimum amount of screen space.
55
56 ComboBox is populated with a data model. The data model is commonly
57 a JavaScript array, a \l ListModel or an integer, but other types
58 of \l {qml-data-models}{data models} are also supported.
59
60 \code
61 ComboBox {
62 model: ["First", "Second", "Third"]
63 }
64 \endcode
65
66 \section1 Editable ComboBox
67
68 ComboBox can be made \l editable. An editable combo box auto-completes
69 its text based on what is available in the model.
70
71 The following example demonstrates appending content to an editable
72 combo box by reacting to the \l accepted signal.
73
74 \snippet qtquickcontrols-combobox-accepted.qml combobox
75
76 \section1 ComboBox's Popup
77
78 By default, clicking outside of ComboBox's popup will close it, and the
79 event is propagated to items lower in the stacking order. To prevent the
80 popup from closing, set its \l {Popup::}{closePolicy}:
81
82 \snippet qtquickcontrols-combobox-popup.qml closePolicy
83
84 To prevent event propagation, set its \l {Popup::}{modal} property to
85 \c true:
86
87 \snippet qtquickcontrols-combobox-popup.qml modal
88
89 \section1 ComboBox Model Roles
90
91 ComboBox is able to visualize standard \l {qml-data-models}{data models}
92 that provide the \c modelData role:
93 \list
94 \li models that have only one role
95 \li models that do not have named roles (JavaScript array, integer)
96 \endlist
97
98 When using models that have multiple named roles, ComboBox must be configured
99 to use a specific \l {textRole}{text role} for its \l {displayText}{display text}
100 and \l delegate instances. If you want to use a role of the model item
101 that corresponds to the text role, set \l valueRole. The \l currentValue
102 property and \l indexOfValue() method can then be used to get information
103 about those values.
104
105 For example:
106
107 \snippet qtquickcontrols-combobox-valuerole.qml file
108
109 \note If ComboBox is assigned a data model that has multiple named roles, but
110 \l textRole is not defined, ComboBox is unable to visualize it and throws a
111 \c {ReferenceError: modelData is not defined}.
112
113 \sa {Customizing ComboBox}, {Input Controls}, {Focus Management in Qt Quick Controls}
114*/
115
116/*!
117 \qmlsignal void QtQuick.Controls::ComboBox::activated(int index)
118
119 This signal is emitted when the item at \a index is activated by the user.
120
121 An item is activated when it is selected while the popup is open,
122 causing the popup to close (and \l currentIndex to change),
123 or while the popup is closed and the combo box is navigated via
124 keyboard, causing the \l currentIndex to change.
125 The \l currentIndex property is set to \a index.
126
127 \sa currentIndex
128*/
129
130/*!
131 \qmlsignal void QtQuick.Controls::ComboBox::highlighted(int index)
132
133 This signal is emitted when the item at \a index in the popup list is highlighted by the user.
134
135 The highlighted signal is only emitted when the popup is open and an item
136 is highlighted, but not necessarily \l activated.
137
138 \sa highlightedIndex
139*/
140
141/*!
142 \since QtQuick.Controls 2.2 (Qt 5.9)
143 \qmlsignal void QtQuick.Controls::ComboBox::accepted()
144
145 This signal is emitted when the \uicontrol Return or \uicontrol Enter key is pressed
146 on an \l editable combo box.
147
148 You can handle this signal in order to add the newly entered
149 item to the model, for example:
150
151 \snippet qtquickcontrols-combobox-accepted.qml combobox
152
153 Before the signal is emitted, a check is done to see if the string
154 exists in the model. If it does, \l currentIndex will be set to its index,
155 and \l currentText to the string itself.
156
157 After the signal has been emitted, and if the first check failed (that is,
158 the item did not exist), another check will be done to see if the item was
159 added by the signal handler. If it was, the \l currentIndex and
160 \l currentText are updated accordingly. Otherwise, they will be set to
161 \c -1 and \c "", respectively.
162
163 \note If there is a \l validator set on the combo box, the signal will only be
164 emitted if the input is in an acceptable state.
165*/
166
167namespace {
170}
171
172// ### Qt7: Remove this class. Use QQmlDelegateModel instead.
174{
175public:
176 explicit QQuickComboBoxDelegateModel(QQuickComboBox *combo);
177 QVariant variantValue(int index, const QString &role) override;
178
179private:
180 QQuickComboBox *combo = nullptr;
181};
182
188
189QVariant QQuickComboBoxDelegateModel::variantValue(int index, const QString &role)
190{
191 // ### Qt7: Get rid of this. Why do we special case lists of variant maps with
192 // exactly one entry? There are many other ways of producing a list of
193 // map-like things with exactly one entry. And what if some of the maps
194 // in the list have more than one entry? You get inconsistent results.
195 if (role == QLatin1String("modelData")) {
196 const QVariant model = combo->model();
197 if (model.metaType() == QMetaType::fromType<QVariantList>()) {
198 const QVariant object = model.toList().value(index);
199 if (object.metaType() == QMetaType::fromType<QVariantMap>()) {
200 const QVariantMap data = object.toMap();
201 if (data.size() == 1)
202 return data.first();
203 }
204 }
205 }
206
207 return QQmlDelegateModel::variantValue(index, role);
208}
209
211{
212public:
213 Q_DECLARE_PUBLIC(QQuickComboBox)
214
215 /*
216 This defines which criteria is used to determine the current model element.
217 The criteria is set by the currentIndex and currentValue setters.
218 With CurrentValue the currentIndex will be set to the index of the element
219 having the same value and currentText will be set to the text of that element.
220 With CurrentIndex or None (when none is explicitly set)
221 currentText and currentValue are set to the ones of the element at currentIndex.
222 Upon model changes the two other properties (those not set) are updated accordingly.
223 User interaction (choosing an item) doesn't change this criteria.
224 This means that if we start with a model containing the values [foo, bar, baz],
225 the user selecting "bar" (at index 1) and the model then being updated by inserting
226 a new element at the beginning, the end result will depend on currentElementCriteria:
227 - CurrentIndex or None:
228 currentIndex will still be 1 but currentValue will be "foo"
229 - CurrentValue:
230 currentValue will still be "bar" but currentIndex will be 2
231
232 The different criteria also have slight behavior changes upon initialization and
233 model changes. The following table depicts how the currentIndex is set in different
234 cases depending on the model count:
235
236 | CurrentValue | CurrentIndex | None
237 ---------------------------------------------------------------------
238 componentComplete | | | 0 if not empty
239 ---------------------------------------------------------------------
240 countChanged | | -1 if empty
241 ---------------------------------------------------------------------
242 modelChanged | | -1 if empty, 0 if not empty
243
244 Note that with CurrentValue the currentValue will only be changed by user interactions,
245 not by model changes.
246 */
252
253 bool isPopupVisible() const;
254 void showPopup();
255 void hidePopup(bool accept);
256 void togglePopup(bool accept);
259
262
263 void createdItem(int index, QObject *object);
266
267 QString effectiveTextRole() const;
274
275 void onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &roles);
276
277 bool isValidIndex(int index) const;
278
280 QString tryComplete(const QString &inputText);
281
285 void setCurrentIndex(int index);
287 void setHighlightedIndex(int index, Highlighting highlight);
288
289 void keySearch(const QString &text);
290 int match(int start, const QString &text, Qt::MatchFlags flags) const;
291
293
294 bool handlePress(const QPointF &point, ulong timestamp) override;
295 bool handleMove(const QPointF &point, ulong timestamp) override;
296 bool handleRelease(const QPointF &point, ulong timestamp) override;
298
300 void executeIndicator(bool complete = false);
301
303 void executePopup(bool complete = false);
304
305 void itemImplicitWidthChanged(QQuickItem *item) override;
306 void itemImplicitHeightChanged(QQuickItem *item) override;
307 void itemDestroyed(QQuickItem *item) override;
308
309 void setInputMethodHints(Qt::InputMethodHints hints, bool force = false);
310
311 virtual qreal getContentWidth() const override;
314
315 static void hideOldPopup(QQuickPopup *popup);
316
317 QPalette defaultPalette() const override { return QQuickTheme::palette(QQuickTheme::ComboBox); }
318
319 bool flat = false;
320 bool down = false;
321 bool hasDown = false;
322 bool pressed = false;
323 bool ownModel = false;
324 bool keyNavigating = false;
325 bool hasDisplayText = false;
329 int currentIndex = -1;
333 QString textRole;
334 QString currentText;
335 QString displayText;
336 QString valueRole;
341 QQmlInstanceModel *delegateModel = nullptr;
342 QQmlComponent *delegate = nullptr;
345 bool m_acceptableInput = true;
348 bool highlightOnHover = true;
349
350 struct ExtraData {
351 bool editable = false;
352 bool accepting = false;
353 bool allowComplete = false;
354 bool selectTextByMouse = false;
356 QString editText;
357#if QT_CONFIG(validator)
358 QValidator *validator = nullptr;
359#endif
360 };
362};
363
365{
366 return popup && popup->isVisible();
367}
368
370{
371 if (!popup)
372 executePopup(true);
373
374 if (popup && !popup->isVisible())
375 popup->open();
376}
377
379{
380 Q_Q(QQuickComboBox);
381 if (accept) {
383 // hiding the popup on user interaction should always emit activated,
384 // even if the current index didn't change
385 emit q->activated(highlightedIndex);
386 }
387 if (popup && popup->isVisible())
388 popup->close();
389}
390
392{
393 if (!popup || !popup->isVisible())
395 else
396 hidePopup(accept);
397}
398
400{
401 Q_Q(QQuickComboBox);
402 if (isPopupVisible())
403 QGuiApplication::inputMethod()->reset();
404
405#if QT_CONFIG(quick_itemview)
406 QQuickItemView *itemView = popup->findChild<QQuickItemView *>();
407 if (itemView)
408 itemView->setHighlightRangeMode(QQuickItemView::NoHighlightRange);
409#endif
410
412
413#if QT_CONFIG(quick_itemview)
414 if (itemView)
415 itemView->positionViewAtIndex(highlightedIndex, QQuickItemView::Beginning);
416#endif
417
418 if (!hasDown) {
419 q->setDown(pressed || isPopupVisible());
420 hasDown = false;
421 }
422}
423
425{
426 Q_Q(QQuickComboBox);
427 popup = nullptr;
428 emit q->popupChanged();
429}
430
432{
433 Q_Q(QQuickComboBox);
434 int index = delegateModel->indexOf(q->sender(), nullptr);
435 if (index != -1) {
437 hidePopup(true);
438 }
439}
440
442{
443 Q_Q(QQuickComboBox);
444 if (keyNavigating)
445 return;
446
447 QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(q->sender());
448 if (!button || !button->isHovered() || !button->isEnabled() || QQuickAbstractButtonPrivate::get(button)->touchId != -1)
449 return;
450
451 int index = delegateModel->indexOf(button, nullptr);
452 if (index != -1) {
455
456#if QT_CONFIG(quick_itemview)
457 if (QQuickItemView *itemView = popup->findChild<QQuickItemView *>())
458 itemView->positionViewAtIndex(index, QQuickItemView::Contain);
459#endif
460 }
461}
462
463void QQuickComboBoxPrivate::createdItem(int index, QObject *object)
464{
465 Q_Q(QQuickComboBox);
466 QQuickItem *item = qobject_cast<QQuickItem *>(object);
467 if (item && !item->parentItem()) {
468 if (popup)
469 item->setParentItem(popup->contentItem());
470 else
471 item->setParentItem(q);
472 QQuickItemPrivate::get(item)->setCulled(true);
473 }
474
475 QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(object);
476 if (button) {
477 button->setFocusPolicy(Qt::NoFocus);
478 connect(button, &QQuickAbstractButton::clicked, this, &QQuickComboBoxPrivate::itemClicked);
479 connect(button, &QQuickAbstractButton::hoveredChanged, this, &QQuickComboBoxPrivate::itemHovered);
480 }
481
482 if (!textFormat && !textFormatWarningDisplayed && Qt::mightBeRichText(q->textAt(index))) {
483 QQuickTemplatesUtils::warnAboutImplicitRichText(q);
485 }
486
487 if (index == currentIndex && !q->isEditable())
489}
490
492{
493 if (componentComplete && (!extra.isAllocated() || !extra->accepting)) {
495
496 if (implicitContentWidthPolicy == QQuickComboBox::WidestText)
497 updateImplicitContentSize();
498 }
499}
500
502{
503 Q_Q(QQuickComboBox);
504 if (q->count() == 0) {
507 else
509 }
510 emit q->countChanged();
511}
512
514{
515 return textRole.isEmpty() ? QStringLiteral("modelData") : textRole;
516}
517
519{
520 Q_Q(QQuickComboBox);
521 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(contentItem);
522 if (!input)
523 return;
524
525 const QString text = input->text();
526
527 if (extra.isAllocated() && extra->allowComplete && !text.isEmpty()) {
528 const QString completed = tryComplete(text);
529 if (completed.size() > text.size()) {
530 input->setText(completed);
531 // This will select the text backwards.
532 input->select(completed.size(), text.size());
533 return;
534 }
535 }
536 q->setEditText(text);
537}
538
540{
541 Q_Q(QQuickComboBox);
542 const int index = q->indexOfValue(currentValue);
543 if (currentIndex == index)
544 return;
545
546 currentIndex = index;
547 emit q->currentIndexChanged();
548}
549
551{
552 Q_Q(QQuickComboBox);
553 const QString text = q->textAt(currentIndex);
554 if (currentText != text) {
555 currentText = text;
556 if (!hasDisplayText)
557 q->maybeSetAccessibleName(text);
558 emit q->currentTextChanged();
559 }
560 if (!hasDisplayText && displayText != text) {
561 displayText = text;
562 emit q->displayTextChanged();
563 }
564 if (!extra.isAllocated() || !extra->accepting)
565 q->setEditText(currentText);
566}
567
569{
570 Q_Q(QQuickComboBox);
571 const QVariant value = q->valueAt(currentIndex);
572 if (currentValue == value)
573 return;
574
575 currentValue = value;
576 emit q->currentValueChanged();
577}
578
594
596{
597 Q_Q(QQuickComboBox);
598
599 if (!contentItem)
600 return;
601
602 const QQuickTextInput *textInputContentItem = qobject_cast<QQuickTextInput *>(contentItem);
603
604 if (!textInputContentItem)
605 return;
606
607 const bool newValue = textInputContentItem->hasAcceptableInput();
608
609 if (m_acceptableInput != newValue) {
610 m_acceptableInput = newValue;
611 emit q->acceptableInputChanged();
612 }
613}
614
615void QQuickComboBoxPrivate::onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList<int> &)
616{
617 const bool currentIndexIsInChangedRange = currentIndex >= topLeft.row() && currentIndex <= bottomRight.row();
618 if (currentIndex == -1 || currentIndexIsInChangedRange)
620}
621
623{
624 return delegateModel && index >= 0 && index < delegateModel->count();
625}
626
628{
629 Q_Q(QQuickComboBox);
630 int idx = q->find(extra.value().editText, Qt::MatchFixedString);
631 if (idx > -1) {
632 // The item that was accepted already exists, so make it the current item.
634 // After accepting text that matches an existing entry, the selection should be cleared.
635 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(contentItem);
636 if (input) {
637 const auto text = input->text();
638 input->select(text.size(), text.size());
639 }
640 }
641
642 extra.value().accepting = true;
643 emit q->accepted();
644
645 // The user might have added the item since it didn't exist, so check again
646 // to see if we can select that new item.
647 if (idx == -1) {
648 idx = q->find(extra.value().editText, Qt::MatchFixedString);
650 }
651 extra.value().accepting = false;
652}
653
654QString QQuickComboBoxPrivate::tryComplete(const QString &input)
655{
656 Q_Q(QQuickComboBox);
657 QString match;
658
659 const int itemCount = q->count();
660 for (int idx = 0; idx < itemCount; ++idx) {
661 const QString text = q->textAt(idx);
662 if (!text.startsWith(input, Qt::CaseInsensitive))
663 continue;
664
665 // either the first or the shortest match
666 if (match.isEmpty() || text.size() < match.size())
667 match = text;
668 }
669
670 if (match.isEmpty())
671 return input;
672
673 return input + match.mid(input.size());
674}
675
677{
678 Q_Q(QQuickComboBox);
679 if (currentIndex == index)
680 return;
681
682 currentIndex = index;
683 emit q->currentIndexChanged();
684
685 if (componentComplete)
687}
688
690{
691 Q_Q(QQuickComboBox);
692 if (currentIndex == index)
693 return;
694
695 currentIndex = index;
696 emit q->currentIndexChanged();
697
700
701 if (activate)
702 emit q->activated(index);
703}
704
706{
707 Q_Q(QQuickComboBox);
708 if (extra.isAllocated())
709 extra->allowComplete = false;
710 if (isPopupVisible()) {
711 if (highlightedIndex < q->count() - 1)
713 } else {
714 if (currentIndex < q->count() - 1)
716 }
717 if (extra.isAllocated())
718 extra->allowComplete = true;
719}
720
722{
723 if (extra.isAllocated())
724 extra->allowComplete = false;
725 if (isPopupVisible()) {
726 if (highlightedIndex > 0)
728 } else {
729 if (currentIndex > 0)
731 }
732 if (extra.isAllocated())
733 extra->allowComplete = true;
734}
735
737{
738 setHighlightedIndex(popup->isVisible() ? currentIndex : -1, NoHighlight);
739}
740
742{
743 Q_Q(QQuickComboBox);
744 if (highlightedIndex == index)
745 return;
746
747 highlightedIndex = index;
748 emit q->highlightedIndexChanged();
749
750 if (highlight)
751 emit q->highlighted(index);
752}
753
754void QQuickComboBoxPrivate::keySearch(const QString &text)
755{
756 const int startIndex = isPopupVisible() ? highlightedIndex : currentIndex;
757 const int index = match(startIndex + 1, text, Qt::MatchStartsWith | Qt::MatchWrap);
758 if (index != -1) {
761 else
763 }
764}
765
766int QQuickComboBoxPrivate::match(int start, const QString &text, Qt::MatchFlags flags) const
767{
768 Q_Q(const QQuickComboBox);
769 uint matchType = flags & 0x0F;
770 bool wrap = flags & Qt::MatchWrap;
771 Qt::CaseSensitivity cs = flags & Qt::MatchCaseSensitive ? Qt::CaseSensitive : Qt::CaseInsensitive;
772 QRegularExpression::PatternOptions options = flags & Qt::MatchCaseSensitive ? QRegularExpression::NoPatternOption
773 : QRegularExpression::CaseInsensitiveOption;
774 int from = start;
775 int to = q->count();
776
777 // iterates twice if wrapping
778 for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i) {
779 for (int idx = from; idx < to; ++idx) {
780 QString t = q->textAt(idx);
781 switch (matchType) {
782 case Qt::MatchExactly:
783 if (t == text)
784 return idx;
785 break;
786 case Qt::MatchRegularExpression: {
787 QRegularExpression rx(QRegularExpression::anchoredPattern(text), options);
788 if (rx.match(t).hasMatch())
789 return idx;
790 break;
791 }
792 case Qt::MatchWildcard: {
793 QRegularExpression rx(QRegularExpression::wildcardToRegularExpression(text),
794 options);
795 if (rx.match(t).hasMatch())
796 return idx;
797 break;
798 }
799 case Qt::MatchStartsWith:
800 if (t.startsWith(text, cs))
801 return idx;
802 break;
803 case Qt::MatchEndsWith:
804 if (t.endsWith(text, cs))
805 return idx;
806 break;
807 case Qt::MatchFixedString:
808 if (t.compare(text, cs) == 0)
809 return idx;
810 break;
811 case Qt::MatchContains:
812 default:
813 if (t.contains(text, cs))
814 return idx;
815 break;
816 }
817 }
818 // prepare for the next iteration
819 from = 0;
820 to = start;
821 }
822 return -1;
823}
824
826{
827 Q_Q(QQuickComboBox);
828 bool ownedOldModel = ownModel;
829 QQmlInstanceModel* oldModel = delegateModel;
830 if (oldModel) {
831 disconnect(delegateModel, &QQmlInstanceModel::countChanged, this, &QQuickComboBoxPrivate::countChanged);
832 disconnect(delegateModel, &QQmlInstanceModel::modelUpdated, this, &QQuickComboBoxPrivate::modelUpdated);
833 disconnect(delegateModel, &QQmlInstanceModel::createdItem, this, &QQuickComboBoxPrivate::createdItem);
834 }
835
836 ownModel = false;
837 delegateModel = model.value<QQmlInstanceModel *>();
838
839 if (!delegateModel && model.isValid()) {
840 QQmlDelegateModel *dataModel = new QQuickComboBoxDelegateModel(q);
841 dataModel->setModel(model);
842 dataModel->setDelegate(delegate);
843 if (q->isComponentComplete())
844 dataModel->componentComplete();
845
846 ownModel = true;
847 delegateModel = dataModel;
848 }
849
850 if (delegateModel) {
851 connect(delegateModel, &QQmlInstanceModel::countChanged, this, &QQuickComboBoxPrivate::countChanged);
852 connect(delegateModel, &QQmlInstanceModel::modelUpdated, this, &QQuickComboBoxPrivate::modelUpdated);
853 connect(delegateModel, &QQmlInstanceModel::createdItem, this, &QQuickComboBoxPrivate::createdItem);
854 }
855
856 emit q->delegateModelChanged();
857
858 if (ownedOldModel)
859 delete oldModel;
860}
861
862bool QQuickComboBoxPrivate::handlePress(const QPointF &point, ulong timestamp)
863{
864 Q_Q(QQuickComboBox);
865 QQuickControlPrivate::handlePress(point, timestamp);
866 q->setPressed(true);
867 return true;
868}
869
870bool QQuickComboBoxPrivate::handleMove(const QPointF &point, ulong timestamp)
871{
872 Q_Q(QQuickComboBox);
873 QQuickControlPrivate::handleMove(point, timestamp);
874 q->setPressed(q->contains(point));
875 return true;
876}
877
878bool QQuickComboBoxPrivate::handleRelease(const QPointF &point, ulong timestamp)
879{
880 Q_Q(QQuickComboBox);
881 QQuickControlPrivate::handleRelease(point, timestamp);
882 if (pressed) {
883 q->setPressed(false);
884 togglePopup(false);
885 }
886 return true;
887}
888
890{
891 Q_Q(QQuickComboBox);
892 QQuickControlPrivate::handleUngrab();
893 q->setPressed(false);
894}
895
897{
898 Q_Q(QQuickComboBox);
899 quickCancelDeferred(q, indicatorName());
900}
901
903{
904 Q_Q(QQuickComboBox);
905 if (indicator.wasExecuted())
906 return;
907
908 if (!indicator || complete)
909 quickBeginDeferred(q, indicatorName(), indicator);
910 if (complete)
911 quickCompleteDeferred(q, indicatorName(), indicator);
912}
913
914static inline QString popupName() { return QStringLiteral("popup"); }
915
917{
918 Q_Q(QQuickComboBox);
919 quickCancelDeferred(q, popupName());
920}
921
923{
924 Q_Q(QQuickComboBox);
925 if (popup.wasExecuted())
926 return;
927
928 if (!popup || complete)
929 quickBeginDeferred(q, popupName(), popup);
930 if (complete)
931 quickCompleteDeferred(q, popupName(), popup);
932}
933
935{
936 Q_Q(QQuickComboBox);
937 QQuickControlPrivate::itemImplicitWidthChanged(item);
938 if (item == indicator)
939 emit q->implicitIndicatorWidthChanged();
940}
941
942void QQuickComboBoxPrivate::setInputMethodHints(Qt::InputMethodHints hints, bool force)
943{
944 Q_Q(QQuickComboBox);
945 if (!force && hints == q->inputMethodHints())
946 return;
947
948 extra.value().inputMethodHints = hints;
949 emit q->inputMethodHintsChanged();
950}
951
953{
954 Q_Q(QQuickComboBox);
955 QQuickControlPrivate::itemImplicitHeightChanged(item);
956 if (item == indicator)
957 emit q->implicitIndicatorHeightChanged();
958}
959
961{
962 Q_Q(QQuickComboBox);
963 QQuickControlPrivate::itemDestroyed(item);
964 if (item == indicator) {
965 indicator = nullptr;
966 emit q->indicatorChanged();
967 }
968}
969
971{
972 if (componentComplete) {
973 switch (implicitContentWidthPolicy) {
974 case QQuickComboBox::WidestText:
975 return calculateWidestTextWidth();
976 case QQuickComboBox::WidestTextWhenCompleted:
977 if (!hasCalculatedWidestText)
978 return calculateWidestTextWidth();
979 break;
980 default:
981 break;
982 }
983 }
984
985 return QQuickControlPrivate::getContentWidth();
986}
987
989{
990 Q_Q(const QQuickComboBox);
991 if (!componentComplete)
992 return 0;
993
994 const int count = q->count();
995 if (count == 0)
996 return 0;
997
998 auto textInput = qobject_cast<QQuickTextInput*>(contentItem);
999 if (!textInput)
1000 return 0;
1001
1002 qCDebug(lcCalculateWidestTextWidth) << "calculating widest text from" << count << "items...";
1003
1004 // Avoid the index check and repeated calls to effectiveTextRole()
1005 // that would result from calling textAt() in a loop.
1006 const QString textRole = effectiveTextRole();
1007 auto textInputPrivate = QQuickTextInputPrivate::get(textInput);
1008 qreal widest = 0;
1009 for (int i = 0; i < count; ++i) {
1010 const QString text = delegateModel->stringValue(i, textRole);
1011 const qreal textImplicitWidth = textInputPrivate->calculateImplicitWidthForText(text);
1012 widest = qMax(widest, textImplicitWidth);
1013 }
1014
1015 qCDebug(lcCalculateWidestTextWidth) << "... widest text is" << widest;
1016 return widest;
1017}
1018
1019/*!
1020 \internal
1021
1022 If the user requested it (and we haven't already done it, depending on the policy),
1023 update the implicit content width to the largest text in the model.
1024*/
1026{
1027 if (!componentComplete)
1028 return;
1029
1030 if (implicitContentWidthPolicy == QQuickComboBox::ContentItemImplicitWidth
1031 || (implicitContentWidthPolicy == QQuickComboBox::WidestTextWhenCompleted && hasCalculatedWidestText))
1032 return;
1033
1034 updateImplicitContentWidth();
1036}
1037
1038void QQuickComboBoxPrivate::hideOldPopup(QQuickPopup *popup)
1039{
1040 if (!popup)
1041 return;
1042
1043 qCDebug(lcItemManagement) << "hiding old popup" << popup;
1044
1045 popup->setVisible(false);
1046 popup->setParentItem(nullptr);
1047#if QT_CONFIG(accessibility)
1048 // Remove the item from the accessibility tree.
1049 QQuickAccessibleAttached *accessible = accessibleAttached(popup);
1050 if (accessible)
1051 accessible->setIgnored(true);
1052#endif
1053}
1054
1055QQuickComboBox::QQuickComboBox(QQuickItem *parent)
1056 : QQuickControl(*(new QQuickComboBoxPrivate), parent)
1057{
1058 setFocusPolicy(Qt::StrongFocus);
1059 setFlag(QQuickItem::ItemIsFocusScope);
1060 setAcceptedMouseButtons(Qt::LeftButton);
1061#if QT_CONFIG(cursor)
1062 setCursor(Qt::ArrowCursor);
1063#endif
1064 Q_D(QQuickComboBox);
1065 d->setInputMethodHints(Qt::ImhNoPredictiveText, true);
1066 d->setSizePolicy(QLayoutPolicy::Preferred, QLayoutPolicy::Fixed);
1067}
1068
1069QQuickComboBox::~QQuickComboBox()
1070{
1071 Q_D(QQuickComboBox);
1072 d->removeImplicitSizeListener(d->indicator);
1073 if (d->popup) {
1074 // Disconnect visibleChanged() to avoid a spurious highlightedIndexChanged() signal
1075 // emission during the destruction of the (visible) popup. (QTBUG-57650)
1076 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::visibleChanged, d, &QQuickComboBoxPrivate::popupVisibleChanged);
1077 QQuickComboBoxPrivate::hideOldPopup(d->popup);
1078 d->popup = nullptr;
1079 }
1080}
1081
1082/*!
1083 \readonly
1084 \qmlproperty int QtQuick.Controls::ComboBox::count
1085
1086 This property holds the number of items in the combo box.
1087*/
1088int QQuickComboBox::count() const
1089{
1090 Q_D(const QQuickComboBox);
1091 return d->delegateModel ? d->delegateModel->count() : 0;
1092}
1093
1094/*!
1095 \qmlproperty model QtQuick.Controls::ComboBox::model
1096
1097 This property holds the model providing data for the combo box.
1098
1099 \code
1100 ComboBox {
1101 textRole: "key"
1102 model: ListModel {
1103 ListElement { key: "First"; value: 123 }
1104 ListElement { key: "Second"; value: 456 }
1105 ListElement { key: "Third"; value: 789 }
1106 }
1107 }
1108 \endcode
1109
1110 \sa textRole, {qml-data-models}{Data Models}
1111*/
1112QVariant QQuickComboBox::model() const
1113{
1114 Q_D(const QQuickComboBox);
1115 if (!d->qobjectModelGuard.has_value()) {
1116 // It's not a QObject-derived model; return it as-is.
1117 return d->model;
1118 }
1119
1120 // It is a QObject-derived model; only return it if it's still alive.
1121 return !d->qobjectModelGuard->isNull() ? d->model : QVariant();
1122}
1123
1124void QQuickComboBox::setModel(const QVariant& m)
1125{
1126 Q_D(QQuickComboBox);
1127 QVariant newModel = m;
1128 if (newModel.userType() == qMetaTypeId<QJSValue>())
1129 newModel = newModel.value<QJSValue>().toVariant();
1130
1131 if (d->model == newModel)
1132 return;
1133
1134 if (d->qobjectModelGuard.has_value() && !d->qobjectModelGuard->isNull()) {
1135 if (QAbstractItemModel* aim = qvariant_cast<QAbstractItemModel *>(d->model)) {
1136 QObjectPrivate::disconnect(aim, &QAbstractItemModel::dataChanged,
1137 d, &QQuickComboBoxPrivate::onDataChanged);
1138 }
1139 }
1140 if (QObject* newModelAsQObject = qvariant_cast<QObject *>(newModel)) {
1141 // Ensure that if the model is destroyed, we don't try to access it.
1142 // We store it in std::optional because model() needs to return the model
1143 // as-is if a non-QObject model is contained within it.
1144 d->qobjectModelGuard = QPointer<QObject>(newModelAsQObject);
1145
1146 if (QAbstractItemModel* aim = qvariant_cast<QAbstractItemModel *>(newModel)) {
1147 QObjectPrivate::connect(aim, &QAbstractItemModel::dataChanged,
1148 d, &QQuickComboBoxPrivate::onDataChanged);
1149 }
1150 } else {
1151 // It's not a QObject, so we don't need to worry about tracking its lifetime.
1152 d->qobjectModelGuard.reset();
1153 }
1154
1155 d->model = newModel;
1156 d->createDelegateModel();
1157 emit countChanged();
1158 if (isComponentComplete()) {
1159 if (d->currentElementCriteria != QQuickComboBoxPrivate::CurrentElementCriteria::CurrentValue)
1160 d->setCurrentIndex(count() > 0 ? 0 : -1);
1161 d->updateCurrentElements();
1162 }
1163 emit modelChanged();
1164
1165 d->maybeUpdateImplicitContentWidth();
1166}
1167
1168/*!
1169 \readonly
1170 \qmlproperty model QtQuick.Controls::ComboBox::delegateModel
1171
1172 This property holds the model that provides delegate instances for the combo box.
1173
1174 It is typically assigned to a \l ListView in the \l {Popup::}{contentItem}
1175 of the \l popup.
1176
1177 \sa {Customizing ComboBox}
1178*/
1179QQmlInstanceModel *QQuickComboBox::delegateModel() const
1180{
1181 Q_D(const QQuickComboBox);
1182 return d->delegateModel;
1183}
1184
1185
1186/*!
1187 \readonly
1188 \qmlproperty bool QtQuick.Controls::ComboBox::pressed
1189
1190 This property holds whether the combo box button is physically pressed.
1191 A button can be pressed by either touch or key events.
1192
1193 \sa down
1194*/
1195bool QQuickComboBox::isPressed() const
1196{
1197 Q_D(const QQuickComboBox);
1198 return d->pressed;
1199}
1200
1201void QQuickComboBox::setPressed(bool pressed)
1202{
1203 Q_D(QQuickComboBox);
1204 if (d->pressed == pressed)
1205 return;
1206
1207 d->pressed = pressed;
1208 emit pressedChanged();
1209
1210 if (!d->hasDown) {
1211 setDown(d->pressed || d->isPopupVisible());
1212 d->hasDown = false;
1213 }
1214}
1215
1216/*!
1217 \readonly
1218 \qmlproperty int QtQuick.Controls::ComboBox::highlightedIndex
1219
1220 This property holds the index of the highlighted item in the combo box popup list.
1221
1222 When a highlighted item is activated, the popup is closed, \l currentIndex
1223 is set to \c highlightedIndex, and the value of this property is reset to
1224 \c -1, as there is no longer a highlighted item.
1225
1226 \sa highlighted(), currentIndex
1227*/
1228int QQuickComboBox::highlightedIndex() const
1229{
1230 Q_D(const QQuickComboBox);
1231 return d->highlightedIndex;
1232}
1233
1234/*!
1235 \qmlproperty int QtQuick.Controls::ComboBox::currentIndex
1236
1237 This property holds the index of the current item in the combo box.
1238
1239 The default value is \c -1 when \l count is \c 0, and \c 0 otherwise.
1240
1241 \sa activated(), currentText, highlightedIndex
1242*/
1243int QQuickComboBox::currentIndex() const
1244{
1245 Q_D(const QQuickComboBox);
1246 return d->currentIndex;
1247}
1248
1249void QQuickComboBox::setCurrentIndex(int index)
1250{
1251 Q_D(QQuickComboBox);
1252 d->currentElementCriteria = QQuickComboBoxPrivate::CurrentElementCriteria::CurrentIndex;
1253 d->setCurrentIndex(index);
1254}
1255
1256/*!
1257 \readonly
1258 \qmlproperty string QtQuick.Controls::ComboBox::currentText
1259
1260 This property holds the text of the current item in the combo box.
1261
1262 \sa currentIndex, displayText, textRole, editText
1263*/
1264QString QQuickComboBox::currentText() const
1265{
1266 Q_D(const QQuickComboBox);
1267 return d->currentText;
1268}
1269
1270/*!
1271 \qmlproperty string QtQuick.Controls::ComboBox::displayText
1272
1273 This property holds the text that is displayed on the combo box button.
1274
1275 By default, the display text presents the current selection. That is,
1276 it follows the text of the current item. However, the default display
1277 text can be overridden with a custom value.
1278
1279 \code
1280 ComboBox {
1281 currentIndex: 1
1282 displayText: "Size: " + currentText
1283 model: ["S", "M", "L"]
1284 }
1285 \endcode
1286
1287 \sa currentText, textRole
1288*/
1289QString QQuickComboBox::displayText() const
1290{
1291 Q_D(const QQuickComboBox);
1292 return d->displayText;
1293}
1294
1295void QQuickComboBox::setDisplayText(const QString &text)
1296{
1297 Q_D(QQuickComboBox);
1298 d->hasDisplayText = true;
1299 if (d->displayText == text)
1300 return;
1301
1302 d->displayText = text;
1303 maybeSetAccessibleName(text);
1304 emit displayTextChanged();
1305}
1306
1307void QQuickComboBox::resetDisplayText()
1308{
1309 Q_D(QQuickComboBox);
1310 if (!d->hasDisplayText)
1311 return;
1312
1313 d->hasDisplayText = false;
1314 d->updateCurrentText();
1315}
1316
1317
1318/*!
1319 \qmlproperty string QtQuick.Controls::ComboBox::textRole
1320
1321 This property holds the model role used for populating the combo box.
1322
1323 When the model has multiple roles, \c textRole can be set to determine
1324 which role should be displayed.
1325
1326 \sa model, currentText, displayText, {ComboBox Model Roles}
1327*/
1328QString QQuickComboBox::textRole() const
1329{
1330 Q_D(const QQuickComboBox);
1331 return d->textRole;
1332}
1333
1334void QQuickComboBox::setTextRole(const QString &role)
1335{
1336 Q_D(QQuickComboBox);
1337 if (d->textRole == role)
1338 return;
1339
1340 d->textRole = role;
1341 if (isComponentComplete())
1342 d->updateCurrentText();
1343 emit textRoleChanged();
1344}
1345
1346/*!
1347 \since QtQuick.Controls 2.14 (Qt 5.14)
1348 \qmlproperty string QtQuick.Controls::ComboBox::valueRole
1349
1350 This property holds the model role used for storing the value associated
1351 with each item in the model.
1352
1353 For an example of how to use this property, see \l {ComboBox Model Roles}.
1354
1355 \sa model, currentValue
1356*/
1357QString QQuickComboBox::valueRole() const
1358{
1359 Q_D(const QQuickComboBox);
1360 return d->valueRole;
1361}
1362
1363void QQuickComboBox::setValueRole(const QString &role)
1364{
1365 Q_D(QQuickComboBox);
1366 if (d->valueRole == role)
1367 return;
1368
1369 d->valueRole = role;
1370 if (isComponentComplete())
1371 d->updateCurrentElements();
1372 emit valueRoleChanged();
1373}
1374
1375/*!
1376 \since QtQuick.Controls 6.13
1377 \qmlproperty enumeration QtQuick.Controls::ComboBox::textFormat
1378
1379 This property holds the format of the text of the items in the popup list.
1380
1381 The supported values are the same as for \l {Text::textFormat}{Text.textFormat}.
1382 The default value is \c Text.AutoText.
1383
1384 \note This property is applied by the default \l delegate. A custom delegate
1385 needs to take it into account itself.
1386
1387 \sa textRole
1388*/
1389QQuickText::TextFormat QQuickComboBox::textFormat() const
1390{
1391 Q_D(const QQuickComboBox);
1392 return d->textFormat.value_or(QQuickText::AutoText);
1393}
1394
1395void QQuickComboBox::setTextFormat(QQuickText::TextFormat textFormat)
1396{
1397 Q_D(QQuickComboBox);
1398 const bool changed = textFormat != this->textFormat();
1399 d->textFormat = textFormat;
1400 if (changed)
1401 emit textFormatChanged();
1402}
1403
1404void QQuickComboBox::resetTextFormat()
1405{
1406 Q_D(QQuickComboBox);
1407 const bool changed = textFormat() != QQuickText::AutoText;
1408 d->textFormat.reset();
1409 if (changed)
1410 emit textFormatChanged();
1411}
1412
1413/*!
1414 \qmlproperty Component QtQuick.Controls::ComboBox::delegate
1415
1416 This property holds a delegate that presents an item in the combo box popup.
1417
1418 It is recommended to use \l ItemDelegate (or any other \l AbstractButton
1419 derivatives) as the delegate. This ensures that the interaction works as
1420 expected, and the popup will automatically close when appropriate. When
1421 other types are used as the delegate, the popup must be closed manually.
1422 For example, if \l MouseArea is used:
1423
1424 \code
1425 delegate: Rectangle {
1426 // ...
1427 MouseArea {
1428 // ...
1429 onClicked: comboBox.popup.close()
1430 }
1431 }
1432 \endcode
1433
1434 \include delegate-ownership.qdocinc {no-ownership-since-6.11} {ComboBox}
1435
1436 \sa ItemDelegate, {Customizing ComboBox}
1437*/
1438QQmlComponent *QQuickComboBox::delegate() const
1439{
1440 Q_D(const QQuickComboBox);
1441 return d->delegate;
1442}
1443
1444void QQuickComboBox::setDelegate(QQmlComponent* delegate)
1445{
1446 Q_D(QQuickComboBox);
1447 if (d->delegate == delegate)
1448 return;
1449
1450 d->delegate = delegate;
1451 QQmlDelegateModel *delegateModel = qobject_cast<QQmlDelegateModel*>(d->delegateModel);
1452 if (delegateModel)
1453 delegateModel->setDelegate(d->delegate);
1454 emit delegateChanged();
1455}
1456
1457/*!
1458 \qmlproperty Item QtQuick.Controls::ComboBox::indicator
1459
1460 This property holds the drop indicator item.
1461
1462 \sa {Customizing ComboBox}
1463*/
1464QQuickItem *QQuickComboBox::indicator() const
1465{
1466 QQuickComboBoxPrivate *d = const_cast<QQuickComboBoxPrivate *>(d_func());
1467 if (!d->indicator)
1468 d->executeIndicator();
1469 return d->indicator;
1470}
1471
1472void QQuickComboBox::setIndicator(QQuickItem *indicator)
1473{
1474 Q_D(QQuickComboBox);
1475 if (d->indicator == indicator)
1476 return;
1477
1478 QQuickControlPrivate::warnIfCustomizationNotSupported(this, indicator, QStringLiteral("indicator"));
1479
1480 if (!d->indicator.isExecuting())
1481 d->cancelIndicator();
1482
1483 const qreal oldImplicitIndicatorWidth = implicitIndicatorWidth();
1484 const qreal oldImplicitIndicatorHeight = implicitIndicatorHeight();
1485
1486 d->removeImplicitSizeListener(d->indicator);
1487 QQuickControlPrivate::hideOldItem(d->indicator);
1488 d->indicator = indicator;
1489 if (indicator) {
1490 if (!indicator->parentItem())
1491 indicator->setParentItem(this);
1492 d->addImplicitSizeListener(indicator);
1493 }
1494
1495 if (!qFuzzyCompare(oldImplicitIndicatorWidth, implicitIndicatorWidth()))
1496 emit implicitIndicatorWidthChanged();
1497 if (!qFuzzyCompare(oldImplicitIndicatorHeight, implicitIndicatorHeight()))
1498 emit implicitIndicatorHeightChanged();
1499 if (!d->indicator.isExecuting())
1500 emit indicatorChanged();
1501}
1502
1503/*!
1504 \qmlproperty Popup QtQuick.Controls::ComboBox::popup
1505
1506 This property holds the popup.
1507
1508 The popup can be opened or closed manually, if necessary:
1509
1510 \code
1511 onSpecialEvent: comboBox.popup.close()
1512 \endcode
1513
1514 \sa {Customizing ComboBox}
1515*/
1516QQuickPopup *QQuickComboBox::popup() const
1517{
1518 QQuickComboBoxPrivate *d = const_cast<QQuickComboBoxPrivate *>(d_func());
1519 if (!d->popup)
1520 d->executePopup(isComponentComplete());
1521 return d->popup;
1522}
1523
1524void QQuickComboBox::setPopup(QQuickPopup *popup)
1525{
1526 Q_D(QQuickComboBox);
1527 if (d->popup == popup)
1528 return;
1529
1530 if (!d->popup.isExecuting())
1531 d->cancelPopup();
1532
1533 if (d->popup) {
1534 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::destroyed, d, &QQuickComboBoxPrivate::popupDestroyed);
1535 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::visibleChanged, d, &QQuickComboBoxPrivate::popupVisibleChanged);
1536 QQuickComboBoxPrivate::hideOldPopup(d->popup);
1537 }
1538 if (popup) {
1539#if QT_CONFIG(wayland)
1540 QQuickPopupPrivate::get(popup)->extendedWindowType = QNativeInterface::Private::QWaylandWindow::ComboBox;
1541#endif
1542#if QT_CONFIG(xcb)
1543 QQuickPopupPrivate::get(popup)->wmWindowType = QNativeInterface::Private::QXcbWindow::Combo;
1544#endif
1545 QQuickPopupPrivate::get(popup)->allowVerticalFlip = true;
1546 popup->setClosePolicy(QQuickPopup::CloseOnEscape | QQuickPopup::CloseOnPressOutsideParent);
1547 QObjectPrivate::connect(popup, &QQuickPopup::visibleChanged, d, &QQuickComboBoxPrivate::popupVisibleChanged);
1548 // QQuickPopup does not derive from QQuickItemChangeListener, so we cannot use
1549 // QQuickItemChangeListener::itemDestroyed so we have to use QObject::destroyed
1550 QObjectPrivate::connect(popup, &QQuickPopup::destroyed, d, &QQuickComboBoxPrivate::popupDestroyed);
1551
1552#if QT_CONFIG(quick_itemview)
1553 if (QQuickItemView *itemView = popup->findChild<QQuickItemView *>())
1554 itemView->setHighlightRangeMode(QQuickItemView::NoHighlightRange);
1555#endif
1556 }
1557 d->popup = popup;
1558 if (!d->popup.isExecuting())
1559 emit popupChanged();
1560}
1561
1562/*!
1563 \since QtQuick.Controls 2.1 (Qt 5.8)
1564 \qmlproperty bool QtQuick.Controls::ComboBox::flat
1565
1566 This property holds whether the combo box button is flat.
1567
1568 A flat combo box button does not draw a background unless it is interacted
1569 with. In comparison to normal combo boxes, flat combo boxes provide looks
1570 that make them stand out less from the rest of the UI. For instance, when
1571 placing a combo box into a tool bar, it may be desirable to make the combo
1572 box flat so it matches better with the flat looks of tool buttons.
1573
1574 The default value is \c false.
1575*/
1576bool QQuickComboBox::isFlat() const
1577{
1578 Q_D(const QQuickComboBox);
1579 return d->flat;
1580}
1581
1582void QQuickComboBox::setFlat(bool flat)
1583{
1584 Q_D(QQuickComboBox);
1585 if (d->flat == flat)
1586 return;
1587
1588 d->flat = flat;
1589 emit flatChanged();
1590}
1591
1592/*!
1593 \since QtQuick.Controls 2.2 (Qt 5.9)
1594 \qmlproperty bool QtQuick.Controls::ComboBox::down
1595
1596 This property holds whether the combo box button is visually down.
1597
1598 Unless explicitly set, this property is \c true when either \c pressed
1599 or \c popup.visible is \c true. To return to the default value, set this
1600 property to \c undefined.
1601
1602 \sa pressed, popup
1603*/
1604bool QQuickComboBox::isDown() const
1605{
1606 Q_D(const QQuickComboBox);
1607 return d->down;
1608}
1609
1610void QQuickComboBox::setDown(bool down)
1611{
1612 Q_D(QQuickComboBox);
1613 d->hasDown = true;
1614
1615 if (d->down == down)
1616 return;
1617
1618 d->down = down;
1619 emit downChanged();
1620}
1621
1622void QQuickComboBox::resetDown()
1623{
1624 Q_D(QQuickComboBox);
1625 if (!d->hasDown)
1626 return;
1627
1628 setDown(d->pressed || d->isPopupVisible());
1629 d->hasDown = false;
1630}
1631
1632/*!
1633 \since QtQuick.Controls 2.2 (Qt 5.9)
1634 \qmlproperty bool QtQuick.Controls::ComboBox::editable
1635
1636 This property holds whether the combo box is editable.
1637
1638 The default value is \c false.
1639
1640 \sa validator
1641*/
1642bool QQuickComboBox::isEditable() const
1643{
1644 Q_D(const QQuickComboBox);
1645 return d->extra.isAllocated() && d->extra->editable;
1646}
1647
1648void QQuickComboBox::setEditable(bool editable)
1649{
1650 Q_D(QQuickComboBox);
1651 if (editable == isEditable())
1652 return;
1653
1654 if (d->contentItem) {
1655 if (editable) {
1656 d->contentItem->installEventFilter(this);
1657 if (QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem)) {
1658 QObjectPrivate::connect(input, &QQuickTextInput::textChanged, d, &QQuickComboBoxPrivate::updateEditText);
1659 QObjectPrivate::connect(input, &QQuickTextInput::accepted, d, &QQuickComboBoxPrivate::acceptInput);
1660 }
1661#if QT_CONFIG(cursor)
1662 d->contentItem->setCursor(Qt::IBeamCursor);
1663#endif
1664 } else {
1665 d->contentItem->removeEventFilter(this);
1666 if (QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem)) {
1667 QObjectPrivate::disconnect(input, &QQuickTextInput::textChanged, d, &QQuickComboBoxPrivate::updateEditText);
1668 QObjectPrivate::disconnect(input, &QQuickTextInput::accepted, d, &QQuickComboBoxPrivate::acceptInput);
1669 }
1670#if QT_CONFIG(cursor)
1671 d->contentItem->unsetCursor();
1672#endif
1673 }
1674 }
1675
1676 d->extra.value().editable = editable;
1677 setAccessibleProperty("editable", editable);
1678 emit editableChanged();
1679}
1680
1681/*!
1682 \since QtQuick.Controls 2.2 (Qt 5.9)
1683 \qmlproperty string QtQuick.Controls::ComboBox::editText
1684
1685 This property holds the text in the text field of an editable combo box.
1686
1687 \sa editable, currentText, displayText
1688*/
1689QString QQuickComboBox::editText() const
1690{
1691 Q_D(const QQuickComboBox);
1692 return d->extra.isAllocated() ? d->extra->editText : QString();
1693}
1694
1695void QQuickComboBox::setEditText(const QString &text)
1696{
1697 Q_D(QQuickComboBox);
1698 if (text == editText())
1699 return;
1700
1701 d->extra.value().editText = text;
1702 emit editTextChanged();
1703}
1704
1705void QQuickComboBox::resetEditText()
1706{
1707 setEditText(QString());
1708}
1709
1710#if QT_CONFIG(validator)
1711/*!
1712 \since QtQuick.Controls 2.2 (Qt 5.9)
1713 \qmlproperty Validator QtQuick.Controls::ComboBox::validator
1714
1715 This property holds an input text validator for an editable combo box.
1716
1717 When a validator is set, the text field will only accept input which
1718 leaves the text property in an intermediate state. The \l accepted signal
1719 will only be emitted if the text is in an acceptable state when the
1720 \uicontrol Return or \uicontrol Enter key is pressed.
1721
1722 The currently supported validators are \l[QtQuick]{IntValidator},
1723 \l[QtQuick]{DoubleValidator}, and \l[QtQuick]{RegularExpressionValidator}. An
1724 example of using validators is shown below, which allows input of
1725 integers between \c 0 and \c 10 into the text field:
1726
1727 \code
1728 ComboBox {
1729 model: 10
1730 editable: true
1731 validator: IntValidator {
1732 top: 9
1733 bottom: 0
1734 }
1735 }
1736 \endcode
1737
1738 \sa acceptableInput, accepted, editable
1739*/
1740QValidator *QQuickComboBox::validator() const
1741{
1742 Q_D(const QQuickComboBox);
1743 return d->extra.isAllocated() ? d->extra->validator : nullptr;
1744}
1745
1746void QQuickComboBox::setValidator(QValidator *validator)
1747{
1748 Q_D(QQuickComboBox);
1749 if (validator == QQuickComboBox::validator())
1750 return;
1751
1752 d->extra.value().validator = validator;
1753#if QT_CONFIG(validator)
1754 if (validator)
1755 validator->setLocale(d->locale);
1756#endif
1757 emit validatorChanged();
1758}
1759#endif
1760
1761/*!
1762 \since QtQuick.Controls 2.2 (Qt 5.9)
1763 \qmlproperty flags QtQuick.Controls::ComboBox::inputMethodHints
1764
1765 Provides hints to the input method about the expected content of the combo box and how it
1766 should operate.
1767
1768 The default value is \c Qt.ImhNoPredictiveText.
1769
1770 \include inputmethodhints.qdocinc
1771*/
1772Qt::InputMethodHints QQuickComboBox::inputMethodHints() const
1773{
1774 Q_D(const QQuickComboBox);
1775 return d->extra.isAllocated() ? d->extra->inputMethodHints : Qt::ImhNoPredictiveText;
1776}
1777
1778void QQuickComboBox::setInputMethodHints(Qt::InputMethodHints hints)
1779{
1780 Q_D(QQuickComboBox);
1781 d->setInputMethodHints(hints);
1782}
1783
1784/*!
1785 \since QtQuick.Controls 2.2 (Qt 5.9)
1786 \qmlproperty bool QtQuick.Controls::ComboBox::inputMethodComposing
1787 \readonly
1788
1789 This property holds whether an editable combo box has partial text input from an input method.
1790
1791 While it is composing, an input method may rely on mouse or key events from the combo box to
1792 edit or commit the partial text. This property can be used to determine when to disable event
1793 handlers that may interfere with the correct operation of an input method.
1794*/
1795bool QQuickComboBox::isInputMethodComposing() const
1796{
1797 Q_D(const QQuickComboBox);
1798 return d->contentItem && d->contentItem->property("inputMethodComposing").toBool();
1799}
1800
1801/*!
1802 \since QtQuick.Controls 2.2 (Qt 5.9)
1803 \qmlproperty bool QtQuick.Controls::ComboBox::acceptableInput
1804 \readonly
1805
1806 This property holds whether the combo box contains acceptable text in the editable text field.
1807
1808 If a validator has been set, the value is \c true only if the current text is acceptable
1809 to the validator as a final string (not as an intermediate string).
1810
1811 \sa validator, accepted
1812*/
1813bool QQuickComboBox::hasAcceptableInput() const
1814{
1815 Q_D(const QQuickComboBox);
1816 return d->m_acceptableInput;
1817}
1818
1819/*!
1820 \since QtQuick.Controls 2.5 (Qt 5.12)
1821 \qmlproperty real QtQuick.Controls::ComboBox::implicitIndicatorWidth
1822 \readonly
1823
1824 This property holds the implicit indicator width.
1825
1826 The value is equal to \c {indicator ? indicator.implicitWidth : 0}.
1827
1828 This is typically used, together with \l {Control::}{implicitContentWidth} and
1829 \l {Control::}{implicitBackgroundWidth}, to calculate the \l {Item::}{implicitWidth}.
1830
1831 \sa implicitIndicatorHeight
1832*/
1833qreal QQuickComboBox::implicitIndicatorWidth() const
1834{
1835 Q_D(const QQuickComboBox);
1836 if (!d->indicator)
1837 return 0;
1838 return d->indicator->implicitWidth();
1839}
1840
1841/*!
1842 \since QtQuick.Controls 2.5 (Qt 5.12)
1843 \qmlproperty real QtQuick.Controls::ComboBox::implicitIndicatorHeight
1844 \readonly
1845
1846 This property holds the implicit indicator height.
1847
1848 The value is equal to \c {indicator ? indicator.implicitHeight : 0}.
1849
1850 This is typically used, together with \l {Control::}{implicitContentHeight} and
1851 \l {Control::}{implicitBackgroundHeight}, to calculate the \l {Item::}{implicitHeight}.
1852
1853 \sa implicitIndicatorWidth
1854*/
1855qreal QQuickComboBox::implicitIndicatorHeight() const
1856{
1857 Q_D(const QQuickComboBox);
1858 if (!d->indicator)
1859 return 0;
1860 return d->indicator->implicitHeight();
1861}
1862
1863/*!
1864 \since QtQuick.Controls 2.14 (Qt 5.14)
1865 \qmlproperty var QtQuick.Controls::ComboBox::currentValue
1866
1867 This property holds the value of the current item in the combo box.
1868 Setting this property will set \l currentIndex to the item with the
1869 corresponding value or \c -1 if it is not found.
1870 Setting both \l currentIndex and \a currentValue declaratively will
1871 result in undefined behavior.
1872 Setting this property with a value that is not unique is not supported.
1873
1874 For an example of how to use this property, see \l {ComboBox Model Roles}.
1875
1876 \sa currentIndex, currentText, valueRole
1877*/
1878QVariant QQuickComboBox::currentValue() const
1879{
1880 Q_D(const QQuickComboBox);
1881 return d->currentValue;
1882}
1883
1884void QQuickComboBox::setCurrentValue(const QVariant &value)
1885{
1886 Q_D(QQuickComboBox);
1887 d->currentElementCriteria = QQuickComboBoxPrivate::CurrentElementCriteria::CurrentValue;
1888 if (value == d->currentValue)
1889 return;
1890
1891 d->currentValue = value;
1892 emit currentValueChanged();
1893
1894 if (d->componentComplete)
1895 d->updateCurrentElements();
1896}
1897
1898/*!
1899 \readonly
1900 \since QtQuick.Controls 2.14 (Qt 5.14)
1901 \qmlmethod var QtQuick.Controls::ComboBox::valueAt(int index)
1902
1903 Returns the value at position \a index in the combo box.
1904
1905 \sa indexOfValue
1906*/
1907QVariant QQuickComboBox::valueAt(int index) const
1908{
1909 Q_D(const QQuickComboBox);
1910 if (!d->isValidIndex(index))
1911 return QVariant();
1912
1913 const QString effectiveValueRole = d->valueRole.isEmpty() ? QStringLiteral("modelData") : d->valueRole;
1914 return d->delegateModel->variantValue(index, effectiveValueRole);
1915}
1916
1917/*!
1918 \since QtQuick.Controls 2.14 (Qt 5.14)
1919 \qmlmethod int QtQuick.Controls::ComboBox::indexOfValue(object value)
1920
1921 Returns the index of the specified \a value, or \c -1 if no match is found.
1922
1923 For an example of how to use this method, see \l {ComboBox Model Roles}.
1924
1925 \include qquickcombobox.qdocinc functions-after-component-completion
1926
1927 \sa find(), currentValue, currentIndex, valueRole, valueAt
1928*/
1929int QQuickComboBox::indexOfValue(const QVariant &value) const
1930{
1931 for (int i = 0; i < count(); ++i) {
1932 const QVariant ourValue = valueAt(i);
1933 if (value == ourValue)
1934 return i;
1935 }
1936 return -1;
1937}
1938
1939/*!
1940 \since QtQuick.Controls 2.15 (Qt 5.15)
1941 \qmlproperty bool QtQuick.Controls::ComboBox::selectTextByMouse
1942
1943 This property holds whether the text field for an editable ComboBox
1944 can be selected with the mouse.
1945
1946 The default value is \c false.
1947*/
1948bool QQuickComboBox::selectTextByMouse() const
1949{
1950 Q_D(const QQuickComboBox);
1951 return d->extra.isAllocated() ? d->extra->selectTextByMouse : false;
1952}
1953
1954void QQuickComboBox::setSelectTextByMouse(bool canSelect)
1955{
1956 Q_D(QQuickComboBox);
1957 if (canSelect == selectTextByMouse())
1958 return;
1959
1960 d->extra.value().selectTextByMouse = canSelect;
1961 emit selectTextByMouseChanged();
1962}
1963
1964/*!
1965 \since QtQuick.Controls 6.0 (Qt 6.0)
1966 \qmlproperty enumeration QtQuick.Controls::ComboBox::implicitContentWidthPolicy
1967
1968 This property controls how the \l{Control::}{implicitContentWidth} of the ComboBox is
1969 calculated.
1970
1971 When the width of a ComboBox is not large enough to display text, that text
1972 is elided. Depending on which parts of the text are elided, this can make
1973 selecting an item difficult for the end user. An efficient way of ensuring
1974 that a ComboBox is wide enough to avoid text being elided is to set a width
1975 that is known to be large enough:
1976
1977 \code
1978 width: 300
1979 implicitContentWidthPolicy: ComboBox.ContentItemImplicitWidth
1980 \endcode
1981
1982 However, it is often not possible to know whether or not a hard-coded value
1983 will be large enough, as the size of text depends on many factors, such as
1984 font family, font size, translations, and so on.
1985
1986 implicitContentWidthPolicy provides an easy way to control how the
1987 implicitContentWidth is calculated, which in turn affects the
1988 \l{Item::}{implicitWidth} of the ComboBox and ensures that text will not be elided.
1989
1990 The available values are:
1991
1992 \value ContentItemImplicitWidth
1993 The implicitContentWidth will default to that of the \l{Control::}{contentItem}.
1994 This is the most efficient option, as no extra text layout is done.
1995 \value WidestText
1996 The implicitContentWidth will be set to the implicit width of the
1997 the largest text for the given \l textRole every time the model
1998 changes.
1999 This option should be used with smaller models, as it can be expensive.
2000 \value WidestTextWhenCompleted
2001 The implicitContentWidth will be set to the implicit width of the
2002 the largest text for the given \l textRole once after
2003 \l {QQmlParserStatus::componentComplete()}{component completion}.
2004 This option should be used with smaller models, as it can be expensive.
2005
2006 The default value is \c ContentItemImplicitWidth.
2007
2008 As this property only affects the \c implicitWidth of the ComboBox, setting
2009 an explicit \l{Item::}{width} can still result in eliding.
2010
2011 \note This feature requires the contentItem to be a type derived from
2012 \l TextInput.
2013
2014 \note This feature requires text to be laid out, and can therefore be
2015 expensive for large models or models whose contents are updated
2016 frequently.
2017*/
2018QQuickComboBox::ImplicitContentWidthPolicy QQuickComboBox::implicitContentWidthPolicy() const
2019{
2020 Q_D(const QQuickComboBox);
2021 return d->implicitContentWidthPolicy;
2022}
2023
2024void QQuickComboBox::setImplicitContentWidthPolicy(QQuickComboBox::ImplicitContentWidthPolicy policy)
2025{
2026 Q_D(QQuickComboBox);
2027 if (policy == d->implicitContentWidthPolicy)
2028 return;
2029
2030 d->implicitContentWidthPolicy = policy;
2031 d->maybeUpdateImplicitContentWidth();
2032 emit implicitContentWidthPolicyChanged();
2033}
2034
2035/*!
2036 \since QtQuick.Controls 6.12 (Qt 6.12)
2037 \qmlproperty bool QtQuick.Controls::ComboBox::highlightOnHover
2038
2039 This property holds whether hovering over items should highlight
2040 them.
2041
2042 The default value is \c true.
2043*/
2044bool QQuickComboBox::highlightOnHover() const
2045{
2046 Q_D(const QQuickComboBox);
2047 return d->highlightOnHover;
2048}
2049
2050void QQuickComboBox::setHighlightOnHover(bool value)
2051{
2052 Q_D(QQuickComboBox);
2053 if (value == highlightOnHover())
2054 return;
2055
2056 d->highlightOnHover = value;
2057 emit highlightOnHoverChanged();
2058}
2059/*!
2060 \qmlmethod string QtQuick.Controls::ComboBox::textAt(int index)
2061
2062 Returns the text for the specified \a index, or an empty string
2063 if the index is out of bounds.
2064
2065 \include qquickcombobox.qdocinc functions-after-component-completion
2066 For example:
2067 \snippet qtquickcontrols-combobox-textat.qml textat
2068
2069 \sa textRole
2070*/
2071QString QQuickComboBox::textAt(int index) const
2072{
2073 Q_D(const QQuickComboBox);
2074 if (!d->isValidIndex(index))
2075 return QString();
2076
2077 return d->delegateModel->stringValue(index, d->effectiveTextRole());
2078}
2079
2080/*!
2081 \qmlmethod int QtQuick.Controls::ComboBox::find(string text, enumeration flags)
2082
2083 Returns the index of the specified \a text, or \c -1 if no match is found.
2084
2085 The way the search is performed is defined by the specified match \a flags. By default,
2086 combo box performs case sensitive exact matching (\c Qt.MatchExactly). All other match
2087 types are case-insensitive unless the \c Qt.MatchCaseSensitive flag is also specified.
2088
2089 \value Qt.MatchExactly The search term matches exactly (default).
2090 \value Qt.MatchRegularExpression The search term matches as a regular expression.
2091 \value Qt.MatchWildcard The search term matches using wildcards.
2092 \value Qt.MatchFixedString The search term matches as a fixed string.
2093 \value Qt.MatchStartsWith The search term matches the start of the item.
2094 \value Qt.MatchEndsWith The search term matches the end of the item.
2095 \value Qt.MatchContains The search term is contained in the item.
2096 \value Qt.MatchCaseSensitive The search is case sensitive.
2097
2098 \include qquickcombobox.qdocinc functions-after-component-completion
2099 For example:
2100 \snippet qtquickcontrols-combobox-find.qml find
2101
2102 \sa textRole
2103*/
2104int QQuickComboBox::find(const QString &text, Qt::MatchFlags flags) const
2105{
2106 Q_D(const QQuickComboBox);
2107 return d->match(0, text, flags);
2108}
2109
2110/*!
2111 \qmlmethod void QtQuick.Controls::ComboBox::incrementCurrentIndex()
2112
2113 Increments the current index of the combo box, or the highlighted
2114 index if the popup list is visible.
2115
2116 \sa currentIndex, highlightedIndex
2117*/
2118void QQuickComboBox::incrementCurrentIndex()
2119{
2120 Q_D(QQuickComboBox);
2121 d->incrementCurrentIndex();
2122}
2123
2124/*!
2125 \qmlmethod void QtQuick.Controls::ComboBox::decrementCurrentIndex()
2126
2127 Decrements the current index of the combo box, or the highlighted
2128 index if the popup list is visible.
2129
2130 \sa currentIndex, highlightedIndex
2131*/
2132void QQuickComboBox::decrementCurrentIndex()
2133{
2134 Q_D(QQuickComboBox);
2135 d->decrementCurrentIndex();
2136}
2137
2138/*!
2139 \since QtQuick.Controls 2.2 (Qt 5.9)
2140 \qmlmethod void QtQuick.Controls::ComboBox::selectAll()
2141
2142 Selects all the text in the editable text field of the combo box.
2143
2144 \sa editText
2145*/
2146void QQuickComboBox::selectAll()
2147{
2148 Q_D(QQuickComboBox);
2149 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
2150 if (!input)
2151 return;
2152 input->selectAll();
2153}
2154
2155bool QQuickComboBox::eventFilter(QObject *object, QEvent *event)
2156{
2157 Q_D(QQuickComboBox);
2158 switch (event->type()) {
2159 case QEvent::MouseButtonRelease:
2160 if (d->isPopupVisible())
2161 d->hidePopup(false);
2162 break;
2163 case QEvent::KeyPress: {
2164 QKeyEvent *ke = static_cast<QKeyEvent *>(event);
2165 if (d->filterKeyEvent(ke, false))
2166 return true;
2167 event->accept();
2168 if (d->extra.isAllocated())
2169 d->extra->allowComplete = ke->key() != Qt::Key_Backspace && ke->key() != Qt::Key_Delete;
2170 break;
2171 }
2172 case QEvent::FocusOut: {
2173 const bool hasActiveFocus = d->popup && d->popup->hasActiveFocus();
2174 const bool usingPopupWindows =
2175 d->popup ? QQuickPopupPrivate::get(d->popup)->usePopupWindow() : false;
2176 if (qGuiApp->focusObject() != this && !(hasActiveFocus && !usingPopupWindows)) {
2177 // Only close the popup if focus was transferred somewhere else
2178 // than to the popup or the popup button (which normally means that
2179 // the user clicked on the popup button to open it, not close it).
2180 d->hidePopup(false);
2181 setPressed(false);
2182
2183 // The focus left the text field, so if the edit text matches an item in the model,
2184 // change our currentIndex to that. This matches widgets' behavior.
2185 const int indexForEditText = find(d->extra.value().editText, Qt::MatchFixedString);
2186 if (indexForEditText > -1)
2187 d->setCurrentItemAtIndex(indexForEditText, Activate);
2188 }
2189 break;
2190 }
2191#if QT_CONFIG(im)
2192 case QEvent::InputMethod:
2193 if (d->extra.isAllocated())
2194 d->extra->allowComplete = !static_cast<QInputMethodEvent*>(event)->commitString().isEmpty();
2195 break;
2196#endif
2197 default:
2198 break;
2199 }
2200 return QQuickControl::eventFilter(object, event);
2201}
2202
2203void QQuickComboBox::focusInEvent(QFocusEvent *event)
2204{
2205 Q_D(QQuickComboBox);
2206 QQuickControl::focusInEvent(event);
2207 // Setting focus on TextField should not be done when drop down indicator was clicked
2208 // That is why, if focus is not set with key reason, it should not be passed to textEdit by default.
2209 // Focus on Edit Text should be set only intentionally by user.
2210 if ((event->reason() == Qt::TabFocusReason || event->reason() == Qt::BacktabFocusReason ||
2211 event->reason() == Qt::ShortcutFocusReason) && d->contentItem && isEditable())
2212 d->contentItem->forceActiveFocus(event->reason());
2213}
2214
2215void QQuickComboBox::focusOutEvent(QFocusEvent *event)
2216{
2217 Q_D(QQuickComboBox);
2218 QQuickControl::focusOutEvent(event);
2219
2220 const bool hasActiveFocus = d->popup && d->popup->hasActiveFocus();
2221 const bool usingPopupWindows = d->popup && QQuickPopupPrivate::get(d->popup)->usePopupWindow();
2222 if (qGuiApp->focusObject() != d->contentItem && !(hasActiveFocus && !usingPopupWindows)) {
2223 // Only close the popup if focus was transferred
2224 // somewhere else than to the popup or the inner line edit (which is
2225 // normally done from QQuickComboBox::focusInEvent).
2226 d->hidePopup(false);
2227 setPressed(false);
2228 }
2229}
2230
2231#if QT_CONFIG(im)
2232void QQuickComboBox::inputMethodEvent(QInputMethodEvent *event)
2233{
2234 Q_D(QQuickComboBox);
2235 QQuickControl::inputMethodEvent(event);
2236 if (!isEditable() && !event->commitString().isEmpty())
2237 d->keySearch(event->commitString());
2238 else
2239 event->ignore();
2240}
2241#endif
2242
2243void QQuickComboBox::keyPressEvent(QKeyEvent *event)
2244{
2245 Q_D(QQuickComboBox);
2246 QQuickControl::keyPressEvent(event);
2247
2248 const auto key = event->key();
2249 if (!isEditable()) {
2250 const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ButtonPressKeys).value<QList<Qt::Key>>();
2251 if (buttonPressKeys.contains(key)) {
2252 if (!event->isAutoRepeat())
2253 setPressed(true);
2254 event->accept();
2255 return;
2256 }
2257 }
2258
2259 switch (key) {
2260 case Qt::Key_Escape:
2261 case Qt::Key_Back:
2262 d->acceptedEscKeyPress = d->isPopupVisible();
2263 d->receivedEscKeyPress = true;
2264 if (d->acceptedEscKeyPress) {
2265 d->hidePopup(false);
2266 setPressed(false);
2267 event->accept();
2268 }
2269 break;
2270 case Qt::Key_Enter:
2271 case Qt::Key_Return:
2272 if (d->isPopupVisible())
2273 setPressed(true);
2274 event->accept();
2275 break;
2276 case Qt::Key_Up:
2277 d->keyNavigating = true;
2278 d->decrementCurrentIndex();
2279 event->accept();
2280 break;
2281 case Qt::Key_Down:
2282 d->keyNavigating = true;
2283 d->incrementCurrentIndex();
2284 event->accept();
2285 break;
2286 case Qt::Key_Home:
2287 d->keyNavigating = true;
2288 if (d->isPopupVisible())
2289 d->setHighlightedIndex(0, Highlight);
2290 else
2291 d->setCurrentItemAtIndex(0, Activate);
2292 event->accept();
2293 break;
2294 case Qt::Key_End:
2295 d->keyNavigating = true;
2296 if (d->isPopupVisible())
2297 d->setHighlightedIndex(count() - 1, Highlight);
2298 else
2299 d->setCurrentItemAtIndex(count() - 1, Activate);
2300 event->accept();
2301 break;
2302 default:
2303 if (!isEditable() && !event->text().isEmpty())
2304 d->keySearch(event->text());
2305 else
2306 event->ignore();
2307 break;
2308 }
2309}
2310
2311void QQuickComboBox::keyReleaseEvent(QKeyEvent *event)
2312{
2313 Q_D(QQuickComboBox);
2314 QQuickControl::keyReleaseEvent(event);
2315 d->keyNavigating = false;
2316 if (event->isAutoRepeat())
2317 return;
2318
2319 const auto key = event->key();
2320 if (!isEditable()) {
2321 const auto buttonPressKeys = QGuiApplicationPrivate::platformTheme()->themeHint(QPlatformTheme::ButtonPressKeys).value<QList<Qt::Key>>();
2322 if (buttonPressKeys.contains(key)) {
2323 if (!isEditable() && isPressed())
2324 d->togglePopup(true);
2325 setPressed(false);
2326 event->accept();
2327 return;
2328 }
2329 }
2330
2331 switch (key) {
2332 case Qt::Key_Enter:
2333 case Qt::Key_Return:
2334 if (!isEditable() || d->isPopupVisible())
2335 d->hidePopup(d->isPopupVisible());
2336 setPressed(false);
2337 event->accept();
2338 break;
2339 case Qt::Key_Escape:
2340 case Qt::Key_Back:
2341 // If QQuickComboBox accepts the key press event, accept the key release event.
2342 // If QQuickComboBox doesn't receive the key press event, but does receive the
2343 // key release event, most likely the popup has popupType == Window and the window was
2344 // closed on key press, resulting in QQuickComboBox only receiving the release event.
2345 if (d->acceptedEscKeyPress || !d->receivedEscKeyPress)
2346 event->accept();
2347 d->acceptedEscKeyPress = false;
2348 d->receivedEscKeyPress = false;
2349 break;
2350 default:
2351 break;
2352 }
2353}
2354
2355#if QT_CONFIG(wheelevent)
2356void QQuickComboBox::wheelEvent(QWheelEvent *event)
2357{
2358 Q_D(QQuickComboBox);
2359 QQuickControl::wheelEvent(event);
2360 if (d->wheelEnabled && !d->isPopupVisible()) {
2361 if (event->angleDelta().y() > 0)
2362 d->decrementCurrentIndex();
2363 else
2364 d->incrementCurrentIndex();
2365 }
2366}
2367#endif
2368
2369bool QQuickComboBox::event(QEvent *e)
2370{
2371 Q_D(QQuickComboBox);
2372 if (e->type() == QEvent::LanguageChange)
2373 d->updateCurrentElements();
2374 return QQuickControl::event(e);
2375}
2376
2377void QQuickComboBox::componentComplete()
2378{
2379 Q_D(QQuickComboBox);
2380 d->executeIndicator(true);
2381 QQuickControl::componentComplete();
2382 if (d->popup)
2383 d->executePopup(true);
2384
2385 if (d->delegateModel && d->ownModel)
2386 static_cast<QQmlDelegateModel *>(d->delegateModel)->componentComplete();
2387
2388 if (count() > 0) {
2389 if (d->currentElementCriteria == QQuickComboBoxPrivate::CurrentElementCriteria::None && d->currentIndex == -1)
2390 d->setCurrentIndex(0);
2391 else
2392 d->updateCurrentElements();
2393
2394 // If the widest text was already calculated in the call to
2395 // QQmlDelegateModel::componentComplete() above, then we shouldn't do it here too.
2396 if (!d->hasCalculatedWidestText)
2397 d->maybeUpdateImplicitContentWidth();
2398 }
2399}
2400
2401void QQuickComboBox::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &value)
2402{
2403 Q_D(QQuickComboBox);
2404 QQuickControl::itemChange(change, value);
2405 if (change == ItemVisibleHasChanged && !value.boolValue) {
2406 d->hidePopup(false);
2407 setPressed(false);
2408 }
2409}
2410
2411void QQuickComboBox::fontChange(const QFont &newFont, const QFont &oldFont)
2412{
2413 Q_D(QQuickComboBox);
2414 QQuickControl::fontChange(newFont, oldFont);
2415 d->maybeUpdateImplicitContentWidth();
2416}
2417
2418void QQuickComboBox::contentItemChange(QQuickItem *newItem, QQuickItem *oldItem)
2419{
2420 Q_D(QQuickComboBox);
2421 if (oldItem) {
2422 oldItem->removeEventFilter(this);
2423 if (QQuickTextInput *oldInput = qobject_cast<QQuickTextInput *>(oldItem)) {
2424 QObjectPrivate::disconnect(oldInput, &QQuickTextInput::accepted, d, &QQuickComboBoxPrivate::acceptInput);
2425 QObjectPrivate::disconnect(oldInput, &QQuickTextInput::textChanged, d, &QQuickComboBoxPrivate::updateEditText);
2426 disconnect(oldInput, &QQuickTextInput::inputMethodComposingChanged, this, &QQuickComboBox::inputMethodComposingChanged);
2427 QObjectPrivate::disconnect(oldInput, &QQuickTextInput::acceptableInputChanged, d, &QQuickComboBoxPrivate::updateAcceptableInput);
2428 }
2429 }
2430 if (newItem && isEditable()) {
2431 newItem->installEventFilter(this);
2432 if (QQuickTextInput *newInput = qobject_cast<QQuickTextInput *>(newItem)) {
2433 QObjectPrivate::connect(newInput, &QQuickTextInput::accepted, d, &QQuickComboBoxPrivate::acceptInput);
2434 QObjectPrivate::connect(newInput, &QQuickTextInput::textChanged, d, &QQuickComboBoxPrivate::updateEditText);
2435 connect(newInput, &QQuickTextInput::inputMethodComposingChanged, this, &QQuickComboBox::inputMethodComposingChanged);
2436 QObjectPrivate::connect(newInput, &QQuickTextInput::acceptableInputChanged, d, &QQuickComboBoxPrivate::updateAcceptableInput);
2437 }
2438#if QT_CONFIG(cursor)
2439 newItem->setCursor(Qt::IBeamCursor);
2440#endif
2441 }
2442
2443 d->updateAcceptableInput();
2444}
2445
2446void QQuickComboBox::localeChange(const QLocale &newLocale, const QLocale &oldLocale)
2447{
2448 QQuickControl::localeChange(newLocale, oldLocale);
2449#if QT_CONFIG(validator)
2450 if (QValidator *v = validator())
2451 v->setLocale(newLocale);
2452#endif
2453}
2454
2455QFont QQuickComboBox::defaultFont() const
2456{
2457 return QQuickTheme::font(QQuickTheme::ComboBox);
2458}
2459
2460#if QT_CONFIG(accessibility)
2461QAccessible::Role QQuickComboBox::accessibleRole() const
2462{
2463 return QAccessible::ComboBox;
2464}
2465
2466void QQuickComboBox::accessibilityActiveChanged(bool active)
2467{
2468 Q_D(QQuickComboBox);
2469 QQuickControl::accessibilityActiveChanged(active);
2470
2471 if (active) {
2472 maybeSetAccessibleName(d->hasDisplayText ? d->displayText : d->currentText);
2473 setAccessibleProperty("editable", isEditable());
2474 }
2475}
2476#endif //
2477
2478QT_END_NAMESPACE
2479
2480#include "moc_qquickcombobox_p.cpp"
QQuickComboBoxDelegateModel(QQuickComboBox *combo)
QVariant variantValue(int index, const QString &role) override
void itemDestroyed(QQuickItem *item) override
bool handleRelease(const QPointF &point, ulong timestamp) override
CurrentElementCriteria currentElementCriteria
QQuickDeferredPointer< QQuickPopup > popup
qreal calculateWidestTextWidth() const
static void hideOldPopup(QQuickPopup *popup)
void setInputMethodHints(Qt::InputMethodHints hints, bool force=false)
void setHighlightedIndex(int index, Highlighting highlight)
void createdItem(int index, QObject *object)
QString effectiveTextRole() const
virtual qreal getContentWidth() const override
void keySearch(const QString &text)
std::optional< QQuickText::TextFormat > textFormat
void handleUngrab() override
int match(int start, const QString &text, Qt::MatchFlags flags) const
QPalette defaultPalette() const override
bool handleMove(const QPointF &point, ulong timestamp) override
QQmlInstanceModel * delegateModel
void itemImplicitHeightChanged(QQuickItem *item) override
void togglePopup(bool accept)
void executePopup(bool complete=false)
void itemImplicitWidthChanged(QQuickItem *item) override
void onDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight, const QList< int > &roles)
void executeIndicator(bool complete=false)
QQuickDeferredPointer< QQuickItem > indicator
void hidePopup(bool accept)
void setCurrentIndex(int index)
QLazilyAllocated< ExtraData > extra
std::optional< QPointer< QObject > > qobjectModelGuard
bool handlePress(const QPointF &point, ulong timestamp) override
void setCurrentItemAtIndex(int, Activation activate)
bool isValidIndex(int index) const
QString tryComplete(const QString &inputText)
Combined button and popup list for selecting options.
static QString popupName()
Qt::InputMethodHints inputMethodHints