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
qquicksearchfield.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 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
7#include <private/qquickindicatorbutton_p.h>
8#include <QtQuickTemplates2/private/qquicktextfield_p.h>
11#include <private/qqmldelegatemodel_p.h>
15#include <QtQml/qqmlcomponent.h>
16#include <QtGui/qtextdocument.h>
17#include <QtQuick/private/qquickaccessibleattached_p.h>
18#if QT_CONFIG(quick_itemview)
19# include <QtQuick/private/qquickitemview_p.h>
20#endif
21
23
24/*!
25 \qmltype SearchField
26 \inherits Control
27 //! \nativetype QQuickSearchField
28 \inqmlmodule QtQuick.Controls
29 \since 6.10
30 \ingroup qtquickcontrols-input
31 \ingroup qtquickcontrols-focusscopes
32 \brief A specialized input field designed to use for search functionality.
33
34 SearchField is a specialized input field designed to use for search functionality.
35 The control includes a text field, search and clear icons, and a popup that
36 displays suggestions or search results.
37
38 \note The iOS style does not provide a built-in popup for SearchField in
39 order to preserve the native look and feel. If a popup is still wanted,
40 it has to be defined by the user.
41
42 \image qtquickcontrols-searchfield.gif
43 {Search field with search icon and clear button}
44
45 \section1 SearchField's Indicators
46
47 SearchField provides two optional embedded indicator buttons: \l searchIndicator and
48 \l clearIndicator.
49
50 These are not indicators in the sense of \l BusyIndicator or \l ProgressBar. Instead,
51 they are interactive controls embedded into the field (similar to the up/down buttons
52 in \l SpinBox). Pressing \l searchIndicator triggers \l searchButtonPressed, and pressing
53 \l clearIndicator triggers \l clearButtonPressed.
54
55 In addition to exposing the actions, the indicator buttons provide interaction state
56 (pressed/hovered/focused, etc.) that can be used by styles.
57
58 \section2 Customizing indicator content
59
60 The \l searchIndicator and \l clearIndicator properties are read-only. Customization is
61 supported through their internal properties.
62
63 In particular, the button's visual content is provided by its \c indicator item, which is
64 writable. This allows the default content to be replaced or removed entirely.
65
66 For example, to remove both indicator icons:
67
68 \code
69 SearchField {
70 searchIndicator.indicator: null
71 clearIndicator.indicator: null
72 }
73 \endcode
74
75 This is a supported customization scenario. Different SearchField variants may omit one
76 of the buttons (for example, providing only a search button) or replace the indicator
77 content with an alternative item (for example, a microphone icon to trigger speech input).
78
79 \sa searchIndicator, clearIndicator, searchButtonPressed, clearButtonPressed
80
81 \section1 SearchField Model Roles
82
83 SearchField is able to visualize standard \l {qml-data-models}{data models}
84 that provide the \c modelData role:
85 \list
86 \li models that have only one role
87 \li models that do not have named roles (JavaScript array, integer)
88 \endlist
89
90 When using models that have multiple named roles, SearchField must be configured
91 to use a specific \l {textRole}{text role} for its \l {text}{text}
92 and \l delegate instances.
93
94 \code
95 ListModel {
96 id : fruitModel
97 ListElement { name: "Apple"; color: "green" }
98 ListElement { name: "Cherry"; color: "red" }
99 ListElement { name: "Banana"; color: "yellow" }
100 ListElement { name: "Orange"; color: "orange" }
101 ListElement { name: "WaterMelon"; color: "pink" }
102 }
103
104 SortFilterProxyModel {
105 id: fruitFilter
106 sourceModel: fruitModel
107 sorters: [
108 RoleSorter {
109 roleName: "name"
110 }
111 ]
112 filters: [
113 FunctionFilter {
114 property var regExp: new RegExp(fruitSearch.text, "i")
115 onRegExpChanged: invalidate()
116 function filter(name: string): bool {
117 return regExp.test(name);
118 }
119 }
120 ]
121 }
122
123 SearchField {
124 id: fruitSearch
125 suggestionModel: fruitFilter
126 textRole: "name"
127 anchors.horizontalCenter: parent.horizontalCenter
128 }
129 \endcode
130 */
131
132/*!
133 \qmlsignal void QtQuick.Controls::SearchField::activated(int index)
134
135 This signal is emitted when the item at \a index is activated by the user.
136
137 An item is activated when it is selected while the popup is open,
138 causing the popup to close (and \l currentIndex to change).
139 The \l currentIndex property is set to \a index.
140
141 \sa currentIndex
142*/
143
144
145/*!
146 \qmlsignal void QtQuick.Controls::SearchField::highlighted(int index)
147
148 This signal is emitted when the item at \a index in the popup list is highlighted by the user.
149
150 The highlighted signal is only emitted when the popup is open and an item
151 is highlighted, but not necessarily \l activated.
152
153 \sa highlightedIndex
154*/
155
156/*!
157 \qmlsignal void QtQuick.Controls::SearchField::accepted()
158
159 This signal is emitted when the user confirms their input by pressing
160 the Enter or Return key.
161
162 This signal is typically used to trigger a search or action based on
163 the final text input, and it indicates the user's intention to complete
164 or submit the query.
165
166 \sa searchTriggered()
167 */
168
169/*!
170 \qmlsignal void QtQuick.Controls::SearchField::searchTriggered()
171
172 This signal is emitted when a search action is initiated.
173
174 It occurs in two cases:
175 1. When the Enter or Return key is pressed, it will be emitted together
176 with accepted() signal
177 2. When the text is edited and if the \l live property is set to \c true,
178 this signal will be emitted.
179
180 This signal is ideal for initiating searches both on-demand and in real-time as
181 the user types, depending on the desired interaction model.
182
183 \sa accepted(), textEdited()
184 */
185
186/*!
187 \qmlsignal void QtQuick.Controls::SearchField::textEdited()
188
189 This signal is emitted every time the user modifies the text in the
190 search field, typically with each keystroke.
191
192 \sa searchTriggered()
193 */
194
195/*!
196 \qmlsignal void QtQuick.Controls::SearchField::searchButtonPressed()
197
198 This signal is emitted when the search button is pressed.
199
200 \sa clearButtonPressed()
201*/
202
203/*!
204 \qmlsignal void QtQuick.Controls::SearchField::clearButtonPressed()
205
206 This signal is emitted when the clear button is pressed.
207
208 \sa searchButtonPressed()
209*/
210
211namespace {
214}
215
217{
218public:
219 Q_DECLARE_PUBLIC(QQuickSearchField)
220
221 bool isPopupVisible() const;
222 void showPopup();
223 void hidePopup(bool accept);
224 static void hideOldPopup(QQuickPopup *popup);
227
230
231 void createdItem(int index, QObject *object);
233
236 void setCurrentIndex(int index);
237 void setCurrentItemAtIndex(int index, Activation activate);
239 void setHighlightedIndex(int index, Highlighting highlight);
240
242
244
245 QString currentTextRole() const;
248 QString textAt(int index) const;
249 bool isValidIndex(int index) const;
250
252 void executePopup(bool complete = false);
253
254 bool handlePress(const QPointF &point, ulong timestamp) override;
255 bool handleRelease(const QPointF &point, ulong timestamp) override;
256
259
260 void itemImplicitWidthChanged(QQuickItem *item) override;
261 void itemImplicitHeightChanged(QQuickItem *item) override;
262 void itemDestroyed(QQuickItem *item) override;
263
264 static inline QString popupName() { return QStringLiteral("popup"); }
265
268 int currentIndex = -1;
270 QString text;
271 QString textRole;
275 bool hasCurrentIndex = false;
276 bool live = true;
277 bool searchPressed = false;
278 bool clearPressed = false;
279 bool searchFlat = false;
280 bool clearFlat = false;
281 bool searchDown = false;
282 bool clearDown = false;
283 bool hasSearchDown = false;
284 bool hasClearDown = false;
285 bool ownModel = false;
286 bool selectTextByMouse = true;
287 QQmlInstanceModel *delegateModel = nullptr;
288 QQmlComponent *delegate = nullptr;
289 QQuickIndicatorButton *searchIndicator = nullptr;
290 QQuickIndicatorButton *clearIndicator = nullptr;
292};
293
295{
296 return popup && popup->isVisible();
297}
298
300{
301 if (!popup)
302 executePopup(true);
303
304 if (popup && !popup->isVisible())
305 popup->open();
306}
307
309{
310 Q_Q(QQuickSearchField);
311 if (accept) {
313 // hiding the popup on user interaction should always emit activated,
314 // even if the current index didn't change
315 emit q->activated(highlightedIndex);
316 }
317 if (popup && popup->isVisible())
318 popup->close();
319}
320
321void QQuickSearchFieldPrivate::hideOldPopup(QQuickPopup *popup)
322{
323 if (!popup)
324 return;
325
326 qCDebug(lcItemManagement) << "hiding old popup" << popup;
327
328 popup->setVisible(false);
329 popup->setParentItem(nullptr);
330#if QT_CONFIG(accessibility)
331 // Remove the item from the accessibility tree.
332 QQuickAccessibleAttached *accessible = accessibleAttached(popup);
333 if (accessible)
334 accessible->setIgnored(true);
335#endif
336}
337
339{
340 if (isPopupVisible())
341 QGuiApplication::inputMethod()->reset();
342
343#if QT_CONFIG(quick_itemview)
344 QQuickItemView *itemView = popup->findChild<QQuickItemView *>();
345 if (itemView)
346 itemView->setHighlightRangeMode(QQuickItemView::NoHighlightRange);
347#endif
348
350
351#if QT_CONFIG(quick_itemview)
352 if (itemView)
353 itemView->positionViewAtIndex(highlightedIndex, QQuickItemView::Beginning);
354#endif
355}
356
358{
359 Q_Q(QQuickSearchField);
360 popup = nullptr;
361 emit q->popupChanged();
362}
363
365{
366 Q_Q(QQuickSearchField);
367 int index = delegateModel->indexOf(q->sender(), nullptr);
368 if (index != -1) {
370 hidePopup(true);
371 }
372}
373
375{
376 Q_Q(QQuickSearchField);
377
378 QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(q->sender());
379 if (!button || !button->isHovered() || !button->isEnabled()
380 || QQuickAbstractButtonPrivate::get(button)->touchId != -1)
381 return;
382
383 int index = delegateModel->indexOf(button, nullptr);
384 if (index != -1) {
386
387#if QT_CONFIG(quick_itemview)
388 if (QQuickItemView *itemView = popup->findChild<QQuickItemView *>())
389 itemView->positionViewAtIndex(index, QQuickItemView::Contain);
390#endif
391 }
392}
393
394void QQuickSearchFieldPrivate::createdItem(int index, QObject *object)
395{
396 Q_Q(QQuickSearchField);
397 QQuickItem *item = qobject_cast<QQuickItem *>(object);
398 if (item && !item->parentItem()) {
399 if (popup)
400 item->setParentItem(popup->contentItem());
401 else
402 item->setParentItem(q);
403 QQuickItemPrivate::get(item)->setCulled(true);
404 }
405
406 QQuickAbstractButton *button = qobject_cast<QQuickAbstractButton *>(object);
407 if (button) {
408 button->setFocusPolicy(Qt::NoFocus);
409 connect(button, &QQuickAbstractButton::clicked, this,
411 connect(button, &QQuickAbstractButton::hoveredChanged, this,
413 }
414
415 if (!textFormat && !textFormatWarningDisplayed && Qt::mightBeRichText(textAt(index))) {
416 QQuickTemplatesUtils::warnAboutImplicitRichText(q);
418 }
419}
420
422{
423 Q_Q(QQuickSearchField);
424
425 if (q->suggestionCount() == 0) {
428 emit q->suggestionCountChanged();
429 return;
430 }
431
432 // If the suggestionModel has been updated and the current text matches an item in
433 // the model, update currentIndex and highlightedIndex to the index of that item.
434 if (!text.isEmpty()) {
435 for (int idx = 0; idx < q->suggestionCount(); ++idx) {
436 if (textAt(idx) == text) {
439 break;
440 }
441 }
442 }
443
444 emit q->suggestionCountChanged();
445}
446
448{
449 Q_Q(QQuickSearchField);
450 if (isPopupVisible()) {
451 if (highlightedIndex < q->suggestionCount() - 1)
453 }
454}
455
463
465{
466 Q_Q(QQuickSearchField);
467 if (currentIndex == index)
468 return;
469
470 currentIndex = index;
471 emit q->currentIndexChanged();
472}
473
475{
476 Q_Q(QQuickSearchField);
477 if (currentIndex == index)
478 return;
479
480 currentIndex = index;
481 emit q->currentIndexChanged();
482
484
485 if (activate)
486 emit q->activated(index);
487}
488
490{
491 Q_Q(QQuickSearchField);
492 int index = -1;
493
494 if (isPopupVisible()) {
495 if (currentIndex >= 0)
496 index = currentIndex;
497 else if (q->suggestionCount() > 0)
498 index = 0; // auto-highlight first suggestion
499 }
500
502}
503
505{
506 Q_Q(QQuickSearchField);
507 if (highlightedIndex == index)
508 return;
509
510 highlightedIndex = index;
511 emit q->highlightedIndexChanged();
512
513 if (highlight)
514 emit q->highlighted(index);
515}
516
518{
519 Q_Q(QQuickSearchField);
520
521 if (!contentItem)
522 return;
523
524 const QQuickTextInput *input = qobject_cast<QQuickTextInput *>(contentItem);
525 if (!input)
526 return;
527
528 const int pos = input->cursorPosition();
529 if (cursorPosition == pos)
530 return;
531
532 cursorPosition = pos;
533 emit q->cursorPositionChanged();
534}
535
537{
538 Q_Q(QQuickSearchField);
539 bool ownedOldModel = ownModel;
540 QQmlInstanceModel *oldModel = delegateModel;
541
542 if (oldModel) {
543 disconnect(delegateModel, &QQmlInstanceModel::countChanged, this,
545 disconnect(delegateModel, &QQmlInstanceModel::createdItem, this,
547 }
548
549 ownModel = false;
550 delegateModel = suggestionModel.value<QQmlInstanceModel *>();
551
552 if (!delegateModel && suggestionModel.isValid()) {
553 QQmlDelegateModel *dataModel = new QQmlDelegateModel(qmlContext(q), q);
554 dataModel->setModel(suggestionModel);
555 dataModel->setDelegate(delegate);
556 if (q->isComponentComplete())
557 dataModel->componentComplete();
558
559 ownModel = true;
560 delegateModel = dataModel;
561 }
562
563 if (delegateModel) {
564 connect(delegateModel, &QQmlInstanceModel::countChanged, this,
566 connect(delegateModel, &QQmlInstanceModel::createdItem, this,
568 }
569
570 emit q->delegateModelChanged();
571
572 if (ownedOldModel)
573 delete oldModel;
574}
575
577{
578 return textRole.isEmpty() ? QStringLiteral("modelData") : textRole;
579}
580
582{
583 Q_Q(QQuickSearchField);
584 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(contentItem);
585 if (!input)
586 return;
587
588 const QString textInput = input->text();
589
590 if (text != textInput) {
591 q->setText(textInput);
592 emit q->textEdited();
593
596
597 if (live)
598 emit q->searchTriggered();
599 }
600
601 if (text.isEmpty()) {
603 hidePopup(false);
604 } else {
605 if (delegateModel && delegateModel->count() > 0) {
606 if (!isPopupVisible())
608 } else {
610 hidePopup(false);
611 }
612 }
613}
614
616{
617 Q_Q(QQuickSearchField);
618 if (currentIndex < 0)
619 return;
620
621 const QString currentText = textAt(currentIndex);
622 if (text != currentText)
623 q->setText(currentText);
624}
625
626QString QQuickSearchFieldPrivate::textAt(int index) const
627{
628 if (!isValidIndex(index))
629 return QString();
630
631 return delegateModel->stringValue(index, currentTextRole());
632}
633
635{
636 return delegateModel && index >= 0 && index < delegateModel->count();
637}
638
640{
641 Q_Q(QQuickSearchField);
642 quickCancelDeferred(q, popupName());
643}
644
646{
647 Q_Q(QQuickSearchField);
648 if (popup.wasExecuted())
649 return;
650
651 if (!popup || complete)
652 quickBeginDeferred(q, popupName(), popup);
653 if (complete)
654 quickCompleteDeferred(q, popupName(), popup);
655}
656
657bool QQuickSearchFieldPrivate::handlePress(const QPointF &point, ulong timestamp)
658{
659 Q_Q(QQuickSearchField);
660 QQuickControlPrivate::handlePress(point, timestamp);
661
662 QQuickItem *si = searchIndicator->indicator();
663 QQuickItem *ci = clearIndicator->indicator();
664 const bool isSearch = si && si->isEnabled() && si->contains(q->mapToItem(si, point));
665 const bool isClear = ci && ci->isEnabled() && ci->contains(q->mapToItem(ci, point));
666
667 if (isSearch) {
668 searchIndicator->setPressed(true);
670 } else if (isClear) {
671 clearIndicator->setPressed(true);
673 }
674
675 return true;
676}
677
678bool QQuickSearchFieldPrivate::handleRelease(const QPointF &point, ulong timestamp)
679{
680 QQuickControlPrivate::handleRelease(point, timestamp);
681 if (searchIndicator->isPressed())
682 searchIndicator->setPressed(false);
683 else if (clearIndicator->isPressed())
684 clearIndicator->setPressed(false);
685 return true;
686}
687
689{
690 Q_Q(QQuickSearchField);
691
692 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(contentItem);
693 if (!input)
694 return;
695
696 input->forceActiveFocus();
697 emit q->searchButtonPressed();
698}
699
701{
702 Q_Q(QQuickSearchField);
703
704 if (text.isEmpty())
705 return;
706
707 // if text is not null then clear text, also reset highlightedIndex and currentIndex
708 if (!text.isEmpty()) {
711 q->setText(QString());
712
714 hidePopup(false);
715
716 emit q->clearButtonPressed();
717 }
718}
719
721{
722 QQuickControlPrivate::itemImplicitWidthChanged(item);
723 if (item == searchIndicator->indicator())
724 emit searchIndicator->implicitIndicatorWidthChanged();
725 if (item == clearIndicator->indicator())
726 emit clearIndicator->implicitIndicatorWidthChanged();
727}
728
730{
731 QQuickControlPrivate::itemImplicitHeightChanged(item);
732 if (item == searchIndicator->indicator())
733 emit searchIndicator->implicitIndicatorHeightChanged();
734 if (item == clearIndicator->indicator())
735 emit clearIndicator->implicitIndicatorHeightChanged();
736}
737
739{
740 QQuickControlPrivate::itemDestroyed(item);
741 if (item == searchIndicator->indicator())
742 searchIndicator->setIndicator(nullptr);
743 if (item == clearIndicator->indicator())
744 clearIndicator->setIndicator(nullptr);
745}
746
747QQuickSearchField::QQuickSearchField(QQuickItem *parent)
748 : QQuickControl(*(new QQuickSearchFieldPrivate), parent)
749{
750 Q_D(QQuickSearchField);
751 d->searchIndicator = new QQuickIndicatorButton(this);
752 d->clearIndicator = new QQuickIndicatorButton(this);
753
754 setFocusPolicy(Qt::StrongFocus);
755 setFlag(QQuickItem::ItemIsFocusScope);
756 setAcceptedMouseButtons(Qt::LeftButton);
757#if QT_CONFIG(cursor)
758 setCursor(Qt::ArrowCursor);
759#endif
760
761 d->init();
762}
763
764QQuickSearchField::~QQuickSearchField()
765{
766 Q_D(QQuickSearchField);
767 d->removeImplicitSizeListener(d->searchIndicator->indicator());
768 d->removeImplicitSizeListener(d->clearIndicator->indicator());
769
770 if (d->popup) {
771 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::visibleChanged, d,
772 &QQuickSearchFieldPrivate::popupVisibleChanged);
773 d->hideOldPopup(d->popup);
774 d->popup = nullptr;
775 }
776}
777
778/*!
779 \qmlproperty model QtQuick.Controls::SearchField::suggestionModel
780
781 This property holds the data model used to display search suggestions in the popup menu.
782
783 \code
784 SearchField {
785 textRole: "age"
786 suggestionModel: ListModel {
787 ListElement { name: "Karen"; age: "66" }
788 ListElement { name: "Jim"; age: "32" }
789 ListElement { name: "Pamela"; age: "28" }
790 }
791 }
792 \endcode
793
794 \sa textRole
795 */
796
797QVariant QQuickSearchField::suggestionModel() const
798{
799 Q_D(const QQuickSearchField);
800 return d->suggestionModel;
801}
802
803void QQuickSearchField::setSuggestionModel(const QVariant &model)
804{
805 Q_D(QQuickSearchField);
806
807 QVariant suggestionModel;
808 if (QJSValue *value = get_if<QJSValue>(&suggestionModel))
809 suggestionModel = value->toVariant();
810 else
811 suggestionModel = model;
812
813 if (d->suggestionModel == suggestionModel)
814 return;
815
816 d->suggestionModel = suggestionModel;
817 d->createDelegateModel();
818 emit suggestionCountChanged();
819 emit suggestionModelChanged();
820}
821
822/*!
823 \readonly
824 \qmlproperty model QtQuick.Controls::SearchField::delegateModel
825
826 This property holds the model that provides delegate instances for the search field.
827
828 It is typically assigned to a \l ListView in the \l {Popup::}{contentItem}
829 of the \l popup.
830
831 */
832QQmlInstanceModel *QQuickSearchField::delegateModel() const
833{
834 Q_D(const QQuickSearchField);
835 return d->delegateModel;
836}
837
838/*!
839 \readonly
840 \qmlproperty int QtQuick.Controls::SearchField::suggestionCount
841
842 This property holds the number of suggestions to display from the suggestion model.
843 */
844int QQuickSearchField::suggestionCount() const
845{
846 Q_D(const QQuickSearchField);
847 return d->delegateModel ? d->delegateModel->count() : 0;
848}
849
850/*!
851 \qmlproperty int QtQuick.Controls::SearchField::currentIndex
852
853 This property holds the index of the currently selected suggestion in the popup list.
854
855 Its value is \c -1 when no suggestion is selected.
856
857 currentIndex is not modified automatically when the model changes or when the user types
858 or edits text. It is updated only when the user explicitly selects a suggestion, either
859 by clicking an item in the popup, or by pressing Enter on a highlighted item.
860
861 currentIndex can be set; for example, to display the first item in the model at startup.
862 Before doing so, ensure that the model is not empty:
863
864 \snippet qtquickcontrols-searchfield-currentIndex.qml currentIndex
865
866 \sa activated(), text, highlightedIndex
867 */
868int QQuickSearchField::currentIndex() const
869{
870 Q_D(const QQuickSearchField);
871 return d->currentIndex;
872}
873
874void QQuickSearchField::setCurrentIndex(int index)
875{
876 Q_D(QQuickSearchField);
877 d->hasCurrentIndex = true;
878 d->setCurrentIndex(index);
879}
880
881/*!
882 \readonly
883 \qmlproperty int QtQuick.Controls::SearchField::highlightedIndex
884
885 This property holds the index of the currently highlighted item in
886 the popup list.
887
888 When the highlighted item is activated, the popup closes, \l currentIndex
889 is updated to match \c highlightedIndex, and this property is reset to
890 \c -1, indicating that no item is currently highlighted.
891
892 \sa highlighted(), currentIndex
893*/
894int QQuickSearchField::highlightedIndex() const
895{
896 Q_D(const QQuickSearchField);
897 return d->highlightedIndex;
898}
899
900/*!
901 \qmlproperty string QtQuick.Controls::SearchField::text
902
903 This property holds the current input text in the search field.
904
905 Text is bound to the user input, triggering suggestion updates or search logic.
906
907 \sa searchTriggered(), textEdited()
908 */
909QString QQuickSearchField::text() const
910{
911 Q_D(const QQuickSearchField);
912 return d->text;
913}
914
915void QQuickSearchField::setText(const QString &text)
916{
917 Q_D(QQuickSearchField);
918 if (d->text == text)
919 return;
920
921 d->text = text;
922 emit textChanged();
923}
924
925/*!
926 \qmlproperty string QtQuick.Controls::SearchField::textRole
927
928 This property holds the model role used to display items in the suggestion model
929 shown in the popup list.
930
931 When the model has multiple roles, \c textRole can be set to determine
932 which role should be displayed.
933 */
934QString QQuickSearchField::textRole() const
935{
936 Q_D(const QQuickSearchField);
937 return d->textRole;
938}
939
940void QQuickSearchField::setTextRole(const QString &textRole)
941{
942 Q_D(QQuickSearchField);
943 if (d->textRole == textRole)
944 return;
945
946 d->textRole = textRole;
947}
948
949/*!
950 \since 6.13
951 \qmlproperty enumeration QtQuick.Controls::SearchField::textFormat
952
953 This property holds the format of the text of the items in the suggestion
954 model shown in the popup list.
955
956 The supported values are the same as for \l {Text::textFormat}{Text.textFormat}.
957 The default value is \c Text.AutoText.
958
959 \note This property is applied by the default \l delegate. A custom delegate
960 needs to take it into account itself.
961
962 \sa textRole
963*/
964QQuickText::TextFormat QQuickSearchField::textFormat() const
965{
966 Q_D(const QQuickSearchField);
967 return d->textFormat.value_or(QQuickText::AutoText);
968}
969
970void QQuickSearchField::setTextFormat(QQuickText::TextFormat textFormat)
971{
972 Q_D(QQuickSearchField);
973 const bool changed = textFormat != this->textFormat();
974 d->textFormat = textFormat;
975 if (changed)
976 emit textFormatChanged();
977}
978
979void QQuickSearchField::resetTextFormat()
980{
981 Q_D(QQuickSearchField);
982 const bool changed = textFormat() != QQuickText::AutoText;
983 d->textFormat.reset();
984 if (changed)
985 emit textFormatChanged();
986}
987
988/*!
989 \qmlproperty bool QtQuick.Controls::SearchField::live
990
991 This property holds a boolean value that determines whether the search is triggered
992 on every text edit.
993
994 When set to \c true, the \l searchTriggered() signal is emitted on each text change,
995 allowing you to respond to every keystroke.
996 When set to \c false, the \l searchTriggered() is only emitted when the user presses
997 the Enter or Return key.
998
999 \sa searchTriggered()
1000 */
1001
1002bool QQuickSearchField::isLive() const
1003{
1004 Q_D(const QQuickSearchField);
1005 return d->live;
1006}
1007
1008void QQuickSearchField::setLive(const bool live)
1009{
1010 Q_D(QQuickSearchField);
1011
1012 if (d->live == live)
1013 return;
1014
1015 d->live = live;
1016}
1017
1018/*!
1019 \include qquickindicatorbutton.qdocinc {properties} {SearchField} {searchIndicator}
1020
1021 This property holds the search indicator. Pressing it triggers
1022 \l searchButtonPressed.
1023
1024 It is exposed so that styles and applications can customize it through its
1025 internal properties (for example, replacing or removing the \c searchIndicator
1026 via \c searchIndicator.indicator, or reacting to interaction state such as
1027 pressed and hovered).
1028
1029 \sa {SearchField's Indicators}
1030 */
1031QQuickIndicatorButton *QQuickSearchField::searchIndicator() const
1032{
1033 Q_D(const QQuickSearchField);
1034 return d->searchIndicator;
1035}
1036
1037/*!
1038 \include qquickindicatorbutton.qdocinc {properties} {SearchField} {clearIndicator}
1039
1040 This property holds the clear indicator. Pressing it triggers
1041 \l clearButtonPressed.
1042
1043 It is exposed so that styles and applications can customize it through its
1044 internal properties (for example, replacing or removing the \c clearIndicator
1045 via \c clearIndicator.indicator, or reacting to interaction state such as
1046 pressed and hovered).
1047
1048 \sa {SearchField's Indicators}
1049*/
1050QQuickIndicatorButton *QQuickSearchField::clearIndicator() const
1051{
1052 Q_D(const QQuickSearchField);
1053 return d->clearIndicator;
1054}
1055
1056
1057/*!
1058 \qmlproperty Popup QtQuick.Controls::SearchField::popup
1059
1060 This property holds the popup.
1061
1062 The popup can be opened or closed manually, if necessary:
1063
1064 \code
1065 onSpecialEvent: searchField.popup.close()
1066 \endcode
1067 */
1068QQuickPopup *QQuickSearchField::popup() const
1069{
1070 QQuickSearchFieldPrivate *d = const_cast<QQuickSearchFieldPrivate *>(d_func());
1071 if (!d->popup)
1072 d->executePopup(isComponentComplete());
1073 return d->popup;
1074}
1075
1076void QQuickSearchField::setPopup(QQuickPopup *popup)
1077{
1078 Q_D(QQuickSearchField);
1079 if (d->popup == popup)
1080 return;
1081
1082 if (!d->popup.isExecuting())
1083 d->cancelPopup();
1084
1085 if (d->popup) {
1086 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::destroyed, d,
1087 &QQuickSearchFieldPrivate::popupDestroyed);
1088 QObjectPrivate::disconnect(d->popup.data(), &QQuickPopup::visibleChanged, d,
1089 &QQuickSearchFieldPrivate::popupVisibleChanged);
1090 QQuickSearchFieldPrivate::hideOldPopup(d->popup);
1091 }
1092
1093 if (popup) {
1094#if QT_CONFIG(wayland)
1095 QQuickPopupPrivate::get(popup)->extendedWindowType = QNativeInterface::Private::QWaylandWindow::ComboBox;
1096#endif
1097#if QT_CONFIG(xcb)
1098 QQuickPopupPrivate::get(popup)->wmWindowType = QNativeInterface::Private::QXcbWindow::Combo;
1099#endif
1100 QQuickPopupPrivate::get(popup)->allowVerticalFlip = true;
1101 popup->setClosePolicy(QQuickPopup::CloseOnEscape | QQuickPopup::CloseOnPressOutsideParent);
1102 QObjectPrivate::connect(popup, &QQuickPopup::visibleChanged, d,
1103 &QQuickSearchFieldPrivate::popupVisibleChanged);
1104 // QQuickPopup does not derive from QQuickItemChangeListener, so we cannot use
1105 // QQuickItemChangeListener::itemDestroyed so we have to use QObject::destroyed
1106 QObjectPrivate::connect(popup, &QQuickPopup::destroyed, d,
1107 &QQuickSearchFieldPrivate::popupDestroyed);
1108
1109#if QT_CONFIG(quick_itemview)
1110 if (QQuickItemView *itemView = popup->findChild<QQuickItemView *>())
1111 itemView->setHighlightRangeMode(QQuickItemView::NoHighlightRange);
1112#endif
1113 }
1114
1115 d->popup = popup;
1116 if (!d->popup.isExecuting())
1117 emit popupChanged();
1118}
1119
1120/*!
1121 \qmlproperty Component QtQuick.Controls::SearchField::delegate
1122
1123 This property holds a delegate that presents an item in the search field popup.
1124
1125 It is recommended to use \l ItemDelegate (or any other \l AbstractButton
1126 derivatives) as the delegate. This ensures that the interaction works as
1127 expected, and the popup will automatically close when appropriate. When
1128 other types are used as the delegate, the popup must be closed manually.
1129 For example, if \l MouseArea is used:
1130
1131 \code
1132 delegate: Rectangle {
1133 // ...
1134 MouseArea {
1135 // ...
1136 onClicked: searchField.popup.close()
1137 }
1138 }
1139 \endcode
1140
1141 \include delegate-ownership.qdocinc {no-ownership-since-6.11} {SearchField}
1142*/
1143QQmlComponent *QQuickSearchField::delegate() const
1144{
1145 Q_D(const QQuickSearchField);
1146 return d->delegate;
1147}
1148
1149void QQuickSearchField::setDelegate(QQmlComponent *delegate)
1150{
1151 Q_D(QQuickSearchField);
1152 if (d->delegate == delegate)
1153 return;
1154
1155 d->delegate = delegate;
1156 QQmlDelegateModel *delegateModel = qobject_cast<QQmlDelegateModel *>(d->delegateModel);
1157 if (delegateModel)
1158 delegateModel->setDelegate(d->delegate);
1159 emit delegateChanged();
1160}
1161
1162/*!
1163 \qmlproperty string QtQuick.Controls::SearchField::placeholderText
1164 \since 6.12
1165
1166 This property holds the hint that is displayed in the SearchField before the user
1167 enters text.
1168*/
1169QString QQuickSearchField::placeholderText() const
1170{
1171 Q_D(const QQuickSearchField);
1172 return d->placeholderText;
1173}
1174
1175void QQuickSearchField::setPlaceholderText(const QString &text)
1176{
1177 Q_D(QQuickSearchField);
1178 if (d->placeholderText == text)
1179 return;
1180
1181 d->placeholderText = text;
1182 emit placeholderTextChanged();
1183}
1184
1185/*!
1186 \qmlproperty bool QtQuick.Controls::SearchField::selectTextByMouse
1187 \since 6.12
1188
1189 This property holds whether the text can be selected with the mouse.
1190
1191 The default value is \c true.
1192*/
1193bool QQuickSearchField::selectTextByMouse() const
1194{
1195 Q_D(const QQuickSearchField);
1196 return d->selectTextByMouse;
1197}
1198
1199void QQuickSearchField::setSelectTextByMouse(const bool selectable)
1200{
1201 Q_D(QQuickSearchField);
1202 if (d->selectTextByMouse == selectable)
1203 return;
1204
1205 d->selectTextByMouse = selectable;
1206 emit selectTextByMouseChanged();
1207}
1208
1209/*!
1210 \readonly
1211 \qmlproperty string QtQuick.Controls::SearchField::selectedText
1212 \since 6.12
1213
1214 This read-only property holds the currently selected text.
1215*/
1216QString QQuickSearchField::selectedText() const
1217{
1218 Q_D(const QQuickSearchField);
1219 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1220 if (!input)
1221 return QString();
1222 return input->selectedText();
1223}
1224
1225/*!
1226 \readonly
1227 \qmlproperty int QtQuick.Controls::SearchField::selectionStart
1228 \since 6.12
1229
1230 The cursor position before the first character in the current selection.
1231
1232 This property is read-only. To change the selection, use select(start, end),
1233 selectAll(), or selectWord().
1234
1235 \sa selectionEnd, cursorPosition, selectedText
1236*/
1237int QQuickSearchField::selectionStart() const
1238{
1239 Q_D(const QQuickSearchField);
1240 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1241 if (!input)
1242 return 0;
1243 return input->selectionStart();
1244}
1245
1246/*!
1247 \readonly
1248 \qmlproperty int QtQuick.Controls::SearchField::selectionEnd
1249 \since 6.12
1250
1251 The cursor position after the last character in the current selection.
1252
1253 This property is read-only. To change the selection, use select(start, end),
1254 selectAll(), or selectWord().
1255
1256 \sa selectionStart, cursorPosition, selectedText
1257*/
1258int QQuickSearchField::selectionEnd() const
1259{
1260 Q_D(const QQuickSearchField);
1261 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1262 if (!input)
1263 return 0;
1264 return input->selectionEnd();
1265}
1266
1267/*!
1268 \qmlproperty int QtQuick.Controls::SearchField::cursorPosition
1269 \since 6.12
1270
1271 The position of the cursor in the text field. The cursor is positioned between
1272 characters.
1273
1274 \note The \e characters in this case refer to the string of \l QChar objects,
1275 therefore 16-bit Unicode characters, and the position is considered an index
1276 into this string. This does not necessarily correspond to individual graphemes
1277 in the writing system, as a single grapheme may be represented by multiple
1278 Unicode characters, such as in the case of surrogate pairs, linguistic
1279 ligatures or diacritics.
1280*/
1281int QQuickSearchField::cursorPosition() const
1282{
1283 Q_D(const QQuickSearchField);
1284 return d->cursorPosition;
1285}
1286
1287void QQuickSearchField::setCursorPosition(int position)
1288{
1289 Q_D(QQuickSearchField);
1290 if (d->cursorPosition == position)
1291 return;
1292
1293 d->cursorPosition = position;
1294
1295 if (QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem)) {
1296 if (input->cursorPosition() != position)
1297 input->setCursorPosition(position);
1298 }
1299
1300 emit cursorPositionChanged();
1301}
1302
1303/*!
1304 \qmlmethod void QtQuick.Controls::SearchField::selectAll()
1305 \since 6.12
1306
1307 Selects all text in the text field of the control.
1308*/
1309void QQuickSearchField::selectAll()
1310{
1311 Q_D(QQuickSearchField);
1312 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1313 if (!input)
1314 return;
1315 input->selectAll();
1316}
1317
1318/*!
1319 \qmlmethod void QtQuick.Controls::SearchField::select(int start, int end)
1320 \since 6.12
1321
1322 Causes the text from \a start to \a end to be selected.
1323
1324 If either \a start or \a end is out of range, the selection is not changed.
1325
1326 After calling this, selectionStart will become the lesser
1327 and selectionEnd will become the greater (regardless of the order passed
1328 to this method).
1329
1330 \sa selectionStart, selectionEnd
1331*/
1332void QQuickSearchField::select(int start, int end)
1333{
1334 Q_D(QQuickSearchField);
1335 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1336 if (!input)
1337 return;
1338 input->select(start, end);
1339}
1340
1341/*!
1342 \qmlmethod void QtQuick.Controls::SearchField::selectWord()
1343 \since 6.12
1344
1345 Causes the word closest to the current cursor position to be selected.
1346
1347 \sa cursorPosition, selectedText
1348*/
1349void QQuickSearchField::selectWord()
1350{
1351 Q_D(QQuickSearchField);
1352 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1353 if (!input)
1354 return;
1355 input->selectWord();
1356}
1357
1358/*!
1359 \qmlmethod void QtQuick.Controls::SearchField::deselect()
1360 \since 6.12
1361
1362 Removes the active text selection.
1363
1364 \sa selectedText, selectionStart, selectionEnd
1365*/
1366void QQuickSearchField::deselect()
1367{
1368 Q_D(QQuickSearchField);
1369 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1370 if (!input)
1371 return;
1372 input->deselect();
1373}
1374
1375bool QQuickSearchField::eventFilter(QObject *object, QEvent *event)
1376{
1377 Q_D(QQuickSearchField);
1378
1379 switch (event->type()) {
1380 case QEvent::MouseButtonRelease: {
1381 QQuickTextInput *input = qobject_cast<QQuickTextInput *>(d->contentItem);
1382 if (input->hasFocus() && !d->text.isEmpty() && !d->isPopupVisible()
1383 && (d->delegateModel && d->delegateModel->count() > 0)
1384 && static_cast<QMouseEvent*>(event)->button() == Qt::LeftButton) {
1385 d->showPopup();
1386 }
1387 break;
1388 }
1389 case QEvent::FocusOut: {
1390 const bool hasActiveFocus = d->popup && d->popup->hasActiveFocus();
1391 const bool usingPopupWindows =
1392 d->popup ? QQuickPopupPrivate::get(d->popup)->usePopupWindow() : false;
1393 if (qGuiApp->focusObject() != this && !(hasActiveFocus && !usingPopupWindows))
1394 d->hidePopup(false);
1395 break;
1396 }
1397 default:
1398 break;
1399 }
1400
1401 return QQuickControl::eventFilter(object, event);
1402}
1403
1404void QQuickSearchField::focusInEvent(QFocusEvent *event)
1405{
1406 Q_D(QQuickSearchField);
1407 QQuickControl::focusInEvent(event);
1408
1409 if (!d->contentItem)
1410 return;
1411
1412 const auto reason = event->reason();
1413 switch (reason) {
1414 case Qt::TabFocusReason:
1415 case Qt::BacktabFocusReason:
1416 case Qt::ShortcutFocusReason:
1417 case Qt::OtherFocusReason:
1418 if (reason != Qt::OtherFocusReason || !d->isPopupVisible())
1419 d->contentItem->forceActiveFocus(reason);
1420 break;
1421 default:
1422 break;
1423 }
1424}
1425
1426void QQuickSearchField::focusOutEvent(QFocusEvent *event)
1427{
1428 Q_D(QQuickSearchField);
1429 QQuickControl::focusOutEvent(event);
1430
1431 const bool hasActiveFocus = d->popup && d->popup->hasActiveFocus();
1432 const bool usingPopupWindows = d->popup && QQuickPopupPrivate::get(d->popup)->usePopupWindow();
1433
1434 if (qGuiApp->focusObject() != d->contentItem && !(hasActiveFocus && !usingPopupWindows))
1435 d->hidePopup(false);
1436}
1437
1438void QQuickSearchField::hoverEnterEvent(QHoverEvent *event)
1439{
1440 Q_D(QQuickSearchField);
1441 QQuickControl::hoverEnterEvent(event);
1442 QQuickItem *si = d->searchIndicator->indicator();
1443 QQuickItem *ci = d->clearIndicator->indicator();
1444 d->searchIndicator->setHovered(si && si->isEnabled() && si->contains(mapToItem(si, event->position())));
1445 d->clearIndicator->setHovered(ci && ci->isEnabled() && ci->contains(mapToItem(ci, event->position())));
1446 event->ignore();
1447}
1448
1449void QQuickSearchField::hoverMoveEvent(QHoverEvent *event)
1450{
1451 Q_D(QQuickSearchField);
1452 QQuickControl::hoverMoveEvent(event);
1453 QQuickItem *si = d->searchIndicator->indicator();
1454 QQuickItem *ci = d->clearIndicator->indicator();
1455 d->searchIndicator->setHovered(si && si->isEnabled() && si->contains(mapToItem(si, event->position())));
1456 d->clearIndicator->setHovered(ci && ci->isEnabled() && ci->contains(mapToItem(ci, event->position())));
1457 event->ignore();
1458}
1459
1460void QQuickSearchField::hoverLeaveEvent(QHoverEvent *event)
1461{
1462 Q_D(QQuickSearchField);
1463 QQuickControl::hoverLeaveEvent(event);
1464 d->searchIndicator->setHovered(false);
1465 d->clearIndicator->setHovered(false);
1466 event->ignore();
1467}
1468
1469void QQuickSearchField::keyPressEvent(QKeyEvent *event)
1470{
1471 Q_D(QQuickSearchField);
1472
1473 const auto key = event->key();
1474 const bool hasModel = !d->suggestionModel.isNull();
1475 const bool hasText = !d->text.isEmpty();
1476
1477 switch (key) {
1478 case Qt::Key_Escape:
1479 case Qt::Key_Back:
1480 if (d->isPopupVisible()) {
1481 d->hidePopup(false);
1482 event->accept();
1483 } else if (hasText) {
1484 setText(QString());
1485 event->accept();
1486 }
1487 break;
1488 case Qt::Key_Return:
1489 case Qt::Key_Enter:
1490 if (d->isPopupVisible())
1491 d->hidePopup(true);
1492 emit accepted();
1493 emit searchTriggered();
1494 event->accept();
1495 break;
1496 case Qt::Key_Up:
1497 if (hasModel) {
1498 d->decreaseCurrentIndex();
1499 event->accept();
1500 }
1501 break;
1502 case Qt::Key_Down:
1503 if (hasModel) {
1504 d->increaseCurrentIndex();
1505 event->accept();
1506 }
1507 break;
1508 case Qt::Key_Home:
1509 if (d->isPopupVisible()) {
1510 d->setHighlightedIndex(0, Highlight);
1511 event->accept();
1512 }
1513 break;
1514 case Qt::Key_End:
1515 if (d->isPopupVisible()) {
1516 d->setHighlightedIndex(suggestionCount() - 1, Highlight);
1517 event->accept();
1518 }
1519 break;
1520 default:
1521 QQuickControl::keyPressEvent(event);
1522 break;
1523 }
1524}
1525
1526void QQuickSearchField::classBegin()
1527{
1528 Q_D(QQuickSearchField);
1529 QQuickControl::classBegin();
1530
1531 QQmlContext *context = qmlContext(this);
1532 if (context) {
1533 QQmlEngine::setContextForObject(d->searchIndicator, context);
1534 QQmlEngine::setContextForObject(d->clearIndicator, context);
1535 }
1536}
1537
1538void QQuickSearchField::componentComplete()
1539{
1540 Q_D(QQuickSearchField);
1541 QQuickIndicatorButtonPrivate::get(d->searchIndicator)->executeIndicator(true);
1542 QQuickIndicatorButtonPrivate::get(d->clearIndicator)->executeIndicator(true);
1543 QQuickControl::componentComplete();
1544
1545 if (d->popup)
1546 d->executePopup(true);
1547
1548 if (d->delegateModel && d->ownModel)
1549 static_cast<QQmlDelegateModel *>(d->delegateModel)->componentComplete();
1550}
1551
1552void QQuickSearchField::contentItemChange(QQuickItem *newItem, QQuickItem *oldItem)
1553{
1554 Q_D(QQuickSearchField);
1555 if (oldItem) {
1556 oldItem->removeEventFilter(this);
1557 if (QQuickTextInput *oldInput = qobject_cast<QQuickTextInput *>(oldItem)) {
1558 QObjectPrivate::disconnect(oldInput, &QQuickTextInput::textChanged, d,
1559 &QQuickSearchFieldPrivate::updateText);
1560 QObjectPrivate::disconnect(oldInput, &QQuickTextInput::cursorPositionChanged,
1561 d, &QQuickSearchFieldPrivate::updateCursorPosition);
1562 }
1563 }
1564
1565 if (newItem) {
1566 newItem->installEventFilter(this);
1567 if (QQuickTextInput *newInput = qobject_cast<QQuickTextInput *>(newItem)) {
1568 QObjectPrivate::connect(newInput, &QQuickTextInput::textChanged, d,
1569 &QQuickSearchFieldPrivate::updateText);
1570 QObjectPrivate::connect(newInput, &QQuickTextInput::cursorPositionChanged,
1571 d, &QQuickSearchFieldPrivate::updateCursorPosition);
1572 }
1573 #if QT_CONFIG(cursor)
1574 newItem->setCursor(Qt::IBeamCursor);
1575 #endif
1576 }
1577}
1578
1579void QQuickSearchField::itemChange(ItemChange change, const ItemChangeData &data)
1580{
1581 Q_D(QQuickSearchField);
1582 QQuickControl::itemChange(change, data);
1583 if (change == ItemVisibleHasChanged && !data.boolValue) {
1584 d->hidePopup(false);
1585 d->setCurrentItemAtIndex(-1, NoActivate);
1586 }
1587}
1588
1589QT_END_NAMESPACE
1590
1591#include "moc_qquicksearchfield_p.cpp"
void createdItem(int index, QObject *object)
QQuickIndicatorButton * clearIndicator
bool handleRelease(const QPointF &point, ulong timestamp) override
std::optional< QQuickText::TextFormat > textFormat
void itemDestroyed(QQuickItem *item) override
bool isValidIndex(int index) const
static void hideOldPopup(QQuickPopup *popup)
QQuickDeferredPointer< QQuickPopup > popup
void itemImplicitWidthChanged(QQuickItem *item) override
void itemImplicitHeightChanged(QQuickItem *item) override
void setCurrentItemAtIndex(int index, Activation activate)
bool handlePress(const QPointF &point, ulong timestamp) override
void setHighlightedIndex(int index, Highlighting highlight)
QString textAt(int index) const
void executePopup(bool complete=false)
QQmlInstanceModel * delegateModel
QQuickIndicatorButton * searchIndicator
Combined button and popup list for selecting options.