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
qcompleter.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
5/*!
6 \class QCompleter
7 \brief The QCompleter class provides completions based on an item model.
8 \since 4.2
9
10 \inmodule QtWidgets
11
12 You can use QCompleter to provide auto completions in any Qt
13 widget, such as QLineEdit and QComboBox.
14 When the user starts typing a word, QCompleter suggests possible ways of
15 completing the word, based on a word list. The word list is
16 provided as a QAbstractItemModel. (For simple applications, where
17 the word list is static, you can pass a QStringList to
18 QCompleter's constructor.)
19
20 \section1 Basic Usage
21
22 A QCompleter is used typically with a QLineEdit or QComboBox.
23 For example, here's how to provide auto completions from a simple
24 word list in a QLineEdit:
25
26 \snippet code/src_gui_util_qcompleter.cpp 0
27
28 A QFileSystemModel can be used to provide auto completion of file names.
29 For example:
30
31 \snippet code/src_gui_util_qcompleter.cpp 1
32
33 To set the model on which QCompleter should operate, call
34 setModel(). By default, QCompleter will attempt to match the \l
35 {completionPrefix}{completion prefix} (i.e., the word that the
36 user has started typing) against the Qt::EditRole data stored in
37 column 0 in the model case sensitively. This can be changed
38 using setCompletionRole(), setCompletionColumn(), and
39 setCaseSensitivity().
40
41 If the model is sorted on the column and role that are used for completion,
42 you can call setModelSorting() with either
43 QCompleter::CaseSensitivelySortedModel or
44 QCompleter::CaseInsensitivelySortedModel as the argument. On large models,
45 this can lead to significant performance improvements, because QCompleter
46 can then use binary search instead of linear search. The binary search only
47 works when the filterMode is Qt::MatchStartsWith.
48
49 The model can be a \l{QAbstractListModel}{list model},
50 a \l{QAbstractTableModel}{table model}, or a
51 \l{QAbstractItemModel}{tree model}. Completion on tree models
52 is slightly more involved and is covered in the \l{Handling
53 Tree Models} section below.
54
55 The completionMode() determines the mode used to provide completions to
56 the user.
57
58 \section1 Iterating Through Completions
59
60 To retrieve a single candidate string, call setCompletionPrefix()
61 with the text that needs to be completed and call
62 currentCompletion(). You can iterate through the list of
63 completions as below:
64
65 \snippet code/src_gui_util_qcompleter.cpp 2
66
67 completionCount() returns the total number of completions for the
68 current prefix. completionCount() should be avoided when possible,
69 since it requires a scan of the entire model.
70
71 \section1 The Completion Model
72
73 completionModel() return a list model that contains all possible
74 completions for the current completion prefix, in the order in which
75 they appear in the model. This model can be used to display the current
76 completions in a custom view. Calling setCompletionPrefix() automatically
77 refreshes the completion model.
78
79 \section1 Handling Tree Models
80
81 QCompleter can look for completions in tree models, assuming
82 that any item (or sub-item or sub-sub-item) can be unambiguously
83 represented as a string by specifying the path to the item. The
84 completion is then performed one level at a time.
85
86 Let's take the example of a user typing in a file system path.
87 The model is a (hierarchical) QFileSystemModel. The completion
88 occurs for every element in the path. For example, if the current
89 text is \c C:\Wind, QCompleter might suggest \c Windows to
90 complete the current path element. Similarly, if the current text
91 is \c C:\Windows\Sy, QCompleter might suggest \c System.
92
93 For this kind of completion to work, QCompleter needs to be able to
94 split the path into a list of strings that are matched at each level.
95 For \c C:\Windows\Sy, it needs to be split as "C:", "Windows" and "Sy".
96 The default implementation of splitPath(), splits the completionPrefix
97 using QDir::separator() if the model is a QFileSystemModel.
98
99 To provide completions, QCompleter needs to know the path from an index.
100 This is provided by pathFromIndex(). The default implementation of
101 pathFromIndex(), returns the data for the \l{Qt::EditRole}{edit role}
102 for list models and the absolute file path if the mode is a QFileSystemModel.
103
104 \sa QAbstractItemModel, QLineEdit, QComboBox, {Completer Example}
105*/
106
107#include "qcompleter_p.h"
108
109#include "QtWidgets/qscrollbar.h"
110#include "QtCore/qdir.h"
111#if QT_CONFIG(stringlistmodel)
112#include "QtCore/qstringlistmodel.h"
113#endif
114#if QT_CONFIG(filesystemmodel)
115#include "QtGui/qfilesystemmodel.h"
116#endif
117#include "QtWidgets/qheaderview.h"
118#if QT_CONFIG(listview)
119#include "QtWidgets/qlistview.h"
120#endif
121#include "QtWidgets/qapplication.h"
122#include "QtGui/qevent.h"
123#include <private/qapplication_p.h>
124#include <private/qwidget_p.h>
125#include <qpa/qplatformwindow.h>
126#include <qpa/qplatformwindow_p.h>
127#if QT_CONFIG(lineedit)
128#include "QtWidgets/qlineedit.h"
129#endif
130#include "QtCore/qdir.h"
131
133
134using namespace Qt::StringLiterals;
135
136QCompletionModel::QCompletionModel(QCompleterPrivate *c, QObject *parent)
137 : QAbstractProxyModel(*new QCompletionModelPrivate, parent),
138 c(c), showAll(false)
139{
141}
142
143int QCompletionModel::columnCount(const QModelIndex &) const
144{
145 Q_D(const QCompletionModel);
146 return d->model->columnCount();
147}
148
149void QCompletionModel::setSourceModel(QAbstractItemModel *source)
150{
151 bool hadModel = (sourceModel() != nullptr);
152
153 if (hadModel)
154 QObject::disconnect(sourceModel(), nullptr, this, nullptr);
155
156 QAbstractProxyModel::setSourceModel(source);
157
158 if (source) {
159 // TODO: Optimize updates in the source model
160 connect(source, SIGNAL(modelReset()), this, SLOT(invalidate()));
161 connect(source, SIGNAL(destroyed()), this, SLOT(modelDestroyed()));
162 connect(source, SIGNAL(layoutChanged()), this, SLOT(invalidate()));
163 connect(source, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(rowsInserted()));
164 connect(source, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(invalidate()));
165 connect(source, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(invalidate()));
166 connect(source, SIGNAL(columnsRemoved(QModelIndex,int,int)), this, SLOT(invalidate()));
167 connect(source, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(invalidate()));
168 }
169
170 invalidate();
171}
172
174{
175 bool sortedEngine = false;
176 if (c->filterMode == Qt::MatchStartsWith) {
177 switch (c->sorting) {
178 case QCompleter::UnsortedModel:
179 sortedEngine = false;
180 break;
181 case QCompleter::CaseSensitivelySortedModel:
182 sortedEngine = c->cs == Qt::CaseSensitive;
183 break;
184 case QCompleter::CaseInsensitivelySortedModel:
185 sortedEngine = c->cs == Qt::CaseInsensitive;
186 break;
187 }
188 }
189
190 if (sortedEngine)
191 engine.reset(new QSortedModelEngine(c));
192 else
193 engine.reset(new QUnsortedModelEngine(c));
194}
195
196QModelIndex QCompletionModel::mapToSource(const QModelIndex& index) const
197{
198 Q_D(const QCompletionModel);
199 if (!index.isValid())
200 return engine->curParent;
201
202 int row;
203 QModelIndex parent = engine->curParent;
204 if (!showAll) {
205 if (!engine->matchCount())
206 return QModelIndex();
207 Q_ASSERT(index.row() < engine->matchCount());
208 QIndexMapper& rootIndices = engine->historyMatch.indices;
209 if (index.row() < rootIndices.count()) {
210 row = rootIndices[index.row()];
211 parent = QModelIndex();
212 } else {
213 row = engine->curMatch.indices[index.row() - rootIndices.count()];
214 }
215 } else {
216 row = index.row();
217 }
218
219 return d->model->index(row, index.column(), parent);
220}
221
222QModelIndex QCompletionModel::mapFromSource(const QModelIndex& idx) const
223{
224 if (!idx.isValid())
225 return QModelIndex();
226
227 int row = -1;
228 if (!showAll) {
229 if (!engine->matchCount())
230 return QModelIndex();
231
232 QIndexMapper& rootIndices = engine->historyMatch.indices;
233 if (idx.parent().isValid()) {
234 if (idx.parent() != engine->curParent)
235 return QModelIndex();
236 } else {
237 row = rootIndices.indexOf(idx.row());
238 if (row == -1 && engine->curParent.isValid())
239 return QModelIndex(); // source parent and our parent don't match
240 }
241
242 if (row == -1) {
243 QIndexMapper& indices = engine->curMatch.indices;
244 engine->filterOnDemand(idx.row() - indices.last());
245 row = indices.indexOf(idx.row()) + rootIndices.count();
246 }
247
248 if (row == -1)
249 return QModelIndex();
250 } else {
251 if (idx.parent() != engine->curParent)
252 return QModelIndex();
253 row = idx.row();
254 }
255
256 return createIndex(row, idx.column());
257}
258
260{
261 if (row < 0 || !engine->matchCount())
262 return false;
263
264 if (row >= engine->matchCount())
265 engine->filterOnDemand(row + 1 - engine->matchCount());
266
267 if (row >= engine->matchCount()) // invalid row
268 return false;
269
270 engine->curRow = row;
271 return true;
272}
273
275{
276 if (!engine->matchCount())
277 return QModelIndex();
278
279 int row = engine->curRow;
280 if (showAll)
281 row = engine->curMatch.indices[engine->curRow];
282
283 QModelIndex idx = createIndex(row, c->column);
284 if (!sourceIndex)
285 return idx;
286 return mapToSource(idx);
287}
288
289QModelIndex QCompletionModel::index(int row, int column, const QModelIndex& parent) const
290{
291 Q_D(const QCompletionModel);
292 if (row < 0 || column < 0 || column >= columnCount(parent) || parent.isValid())
293 return QModelIndex();
294
295 if (!showAll) {
296 if (!engine->matchCount())
297 return QModelIndex();
298 if (row >= engine->historyMatch.indices.count()) {
299 int want = row + 1 - engine->matchCount();
300 if (want > 0)
301 engine->filterOnDemand(want);
302 if (row >= engine->matchCount())
303 return QModelIndex();
304 }
305 } else {
306 if (row >= d->model->rowCount(engine->curParent))
307 return QModelIndex();
308 }
309
310 return createIndex(row, column);
311}
312
314{
315 if (!engine->matchCount())
316 return 0;
317
318 engine->filterOnDemand(INT_MAX);
319 return engine->matchCount();
320}
321
322int QCompletionModel::rowCount(const QModelIndex &parent) const
323{
324 Q_D(const QCompletionModel);
325 if (parent.isValid())
326 return 0;
327
328 if (showAll) {
329 // Show all items below current parent, even if we have no valid matches
330 if (engine->curParts.size() != 1 && !engine->matchCount()
331 && !engine->curParent.isValid())
332 return 0;
333 return d->model->rowCount(engine->curParent);
334 }
335
336 return completionCount();
337}
338
339void QCompletionModel::setFiltered(bool filtered)
340{
341 if (showAll == !filtered)
342 return;
343 beginResetModel();
344 showAll = !filtered;
345 endResetModel();
346}
347
348bool QCompletionModel::hasChildren(const QModelIndex &parent) const
349{
350 Q_D(const QCompletionModel);
351 if (parent.isValid())
352 return false;
353
354 if (showAll)
355 return d->model->hasChildren(mapToSource(parent));
356
357 if (!engine->matchCount())
358 return false;
359
360 return true;
361}
362
363QVariant QCompletionModel::data(const QModelIndex& index, int role) const
364{
365 Q_D(const QCompletionModel);
366 return d->model->data(mapToSource(index), role);
367}
368
369Qt::ItemFlags QCompletionModel::flags(const QModelIndex &index) const
370{
371 if (!index.isValid())
372 return Qt::NoItemFlags;
373 return QAbstractProxyModel::flags(index);
374}
375
377{
378 QAbstractProxyModel::setSourceModel(nullptr); // switch to static empty model
379 invalidate();
380}
381
383{
384 invalidate();
385 emit rowsAdded();
386}
387
388void QCompletionModel::invalidate()
389{
390 engine->cache.clear();
391 filter(engine->curParts);
392}
393
394void QCompletionModel::filter(const QStringList& parts)
395{
396 Q_D(QCompletionModel);
397 beginResetModel();
398 engine->filter(parts);
399 endResetModel();
400
401 if (d->model->canFetchMore(engine->curParent))
402 d->model->fetchMore(engine->curParent);
403
404#if QT_CONFIG(filesystemmodel)
405 // No match can mean the directory being completed within was never listed by
406 // the QFileSystemModel (e.g. a path set via setText() and then edited). Start
407 // its listing so directoryLoaded() re-runs the completion. (QTBUG-148220)
408 if (engine->matchCount() == 0 && parts.size() > 1) {
409 if (auto *fsModel = qobject_cast<QFileSystemModel *>(d->model)) {
410 const QModelIndex dirIndex = fsModel->index(QFileInfo(c->prefix).path());
411 if (dirIndex.isValid() && fsModel->canFetchMore(dirIndex))
412 fsModel->fetchMore(dirIndex);
413 }
414 }
415#endif
416}
417
418//////////////////////////////////////////////////////////////////////////////
419void QCompletionEngine::filter(const QStringList& parts)
420{
421 const QAbstractItemModel *model = c->proxy->sourceModel();
422 curParts = parts;
423 if (curParts.isEmpty())
424 curParts.append(QString());
425
426 curRow = -1;
427 curParent = QModelIndex();
428 curMatch = QMatchData();
429 historyMatch = filterHistory();
430
431 if (!model)
432 return;
433
434 QModelIndex parent;
435 for (int i = 0; i < curParts.size() - 1; i++) {
436 QString part = curParts.at(i);
437 int emi = filter(part, parent, -1).exactMatchIndex;
438 if (emi == -1)
439 return;
440 parent = model->index(emi, c->column, parent);
441 }
442
443 // Note that we set the curParent to a valid parent, even if we have no matches
444 // When filtering is disabled, we show all the items under this parent
445 curParent = parent;
446 if (curParts.constLast().isEmpty())
447 curMatch = QMatchData(QIndexMapper(0, model->rowCount(curParent) - 1), -1, false);
448 else
449 curMatch = filter(curParts.constLast(), curParent, 1); // build at least one
450 curRow = curMatch.isValid() ? 0 : -1;
451}
452
454{
455 QAbstractItemModel *source = c->proxy->sourceModel();
456 if (curParts.size() <= 1 || c->proxy->showAll || !source)
457 return QMatchData();
458
459#if QT_CONFIG(filesystemmodel)
460 const bool isFsModel = (qobject_cast<QFileSystemModel *>(source) != nullptr);
461#else
462 const bool isFsModel = false;
463#endif
464 Q_UNUSED(isFsModel);
465 QList<int> v;
466 QIndexMapper im(v);
467 QMatchData m(im, -1, true);
468
469 for (int i = 0; i < source->rowCount(); i++) {
470 QString str = source->index(i, c->column).data().toString();
471 if (str.startsWith(c->prefix, c->cs)
472#if !defined(Q_OS_WIN)
473 && (!isFsModel || QDir::toNativeSeparators(str) != QDir::separator())
474#endif
475 )
476 m.indices.append(i);
477 }
478 return m;
479}
480
481// Returns a match hint from the cache by chopping the search string
482bool QCompletionEngine::matchHint(const QString &part, const QModelIndex &parent, QMatchData *hint) const
483{
484 if (part.isEmpty())
485 return false; // early out to avoid cache[parent] lookup costs
486
487 const auto cit = cache.find(parent);
488 if (cit == cache.end())
489 return false;
490
491 const CacheItem& map = *cit;
492 const auto mapEnd = map.end();
493
494 QString key = c->cs == Qt::CaseInsensitive ? part.toLower() : part;
495
496 while (!key.isEmpty()) {
497 key.chop(1);
498 const auto it = map.find(key);
499 if (it != mapEnd) {
500 *hint = *it;
501 return true;
502 }
503 }
504
505 return false;
506}
507
508bool QCompletionEngine::lookupCache(const QString &part, const QModelIndex &parent, QMatchData *m) const
509{
510 if (part.isEmpty())
511 return false; // early out to avoid cache[parent] lookup costs
512
513 const auto cit = cache.find(parent);
514 if (cit == cache.end())
515 return false;
516
517 const CacheItem& map = *cit;
518
519 const QString key = c->cs == Qt::CaseInsensitive ? part.toLower() : part;
520
521 const auto it = map.find(key);
522 if (it == map.end())
523 return false;
524
525 *m = it.value();
526 return true;
527}
528
529// When the cache size exceeds 1MB, it clears out about 1/2 of the cache.
530void QCompletionEngine::saveInCache(QString part, const QModelIndex& parent, const QMatchData& m)
531{
532 if (c->filterMode == Qt::MatchEndsWith)
533 return;
534 QMatchData old = cache[parent].take(part);
535 cost = cost + m.indices.cost() - old.indices.cost();
536 if (cost * sizeof(int) > 1024 * 1024) {
537 QMap<QModelIndex, CacheItem>::iterator it1 = cache.begin();
538 while (it1 != cache.end()) {
539 CacheItem& ci = it1.value();
540 int sz = ci.size()/2;
541 QMap<QString, QMatchData>::iterator it2 = ci.begin();
542 int i = 0;
543 while (it2 != ci.end() && i < sz) {
544 cost -= it2.value().indices.cost();
545 it2 = ci.erase(it2);
546 i++;
547 }
548 if (ci.size() == 0) {
549 it1 = cache.erase(it1);
550 } else {
551 ++it1;
552 }
553 }
554 }
555
556 if (c->cs == Qt::CaseInsensitive)
557 part = std::move(part).toLower();
558 cache[parent][part] = m;
559}
560
561///////////////////////////////////////////////////////////////////////////////////
562QIndexMapper QSortedModelEngine::indexHint(QString part, const QModelIndex& parent, Qt::SortOrder order)
563{
564 const QAbstractItemModel *model = c->proxy->sourceModel();
565
566 if (c->cs == Qt::CaseInsensitive)
567 part = std::move(part).toLower();
568
569 const CacheItem& map = cache[parent];
570
571 // Try to find a lower and upper bound for the search from previous results
572 int to = model->rowCount(parent) - 1;
573 int from = 0;
574 const CacheItem::const_iterator it = map.lowerBound(part);
575
576 // look backward for first valid hint
577 for (CacheItem::const_iterator it1 = it; it1 != map.constBegin();) {
578 --it1;
579 const QMatchData& value = it1.value();
580 if (value.isValid()) {
581 if (order == Qt::AscendingOrder) {
582 from = value.indices.last() + 1;
583 } else {
584 to = value.indices.first() - 1;
585 }
586 break;
587 }
588 }
589
590 // look forward for first valid hint
591 for(CacheItem::const_iterator it2 = it; it2 != map.constEnd(); ++it2) {
592 const QMatchData& value = it2.value();
593 if (value.isValid() && !it2.key().startsWith(part)) {
594 if (order == Qt::AscendingOrder) {
595 to = value.indices.first() - 1;
596 } else {
597 from = value.indices.first() + 1;
598 }
599 break;
600 }
601 }
602
603 return QIndexMapper(from, to);
604}
605
606Qt::SortOrder QSortedModelEngine::sortOrder(const QModelIndex &parent) const
607{
608 const QAbstractItemModel *model = c->proxy->sourceModel();
609
610 int rowCount = model->rowCount(parent);
611 if (rowCount < 2)
612 return Qt::AscendingOrder;
613 QString first = model->data(model->index(0, c->column, parent), c->role).toString();
614 QString last = model->data(model->index(rowCount - 1, c->column, parent), c->role).toString();
615 return QString::compare(first, last, c->cs) <= 0 ? Qt::AscendingOrder : Qt::DescendingOrder;
616}
617
618QMatchData QSortedModelEngine::filter(const QString& part, const QModelIndex& parent, int)
619{
620 const QAbstractItemModel *model = c->proxy->sourceModel();
621
622 QMatchData hint;
623 if (lookupCache(part, parent, &hint))
624 return hint;
625
626 QIndexMapper indices;
627 Qt::SortOrder order = sortOrder(parent);
628
629 if (matchHint(part, parent, &hint)) {
630 if (!hint.isValid())
631 return QMatchData();
632 indices = hint.indices;
633 } else {
634 indices = indexHint(part, parent, order);
635 }
636
637 // binary search the model within 'indices' for 'part' under 'parent'
638 int high = indices.to() + 1;
639 int low = indices.from() - 1;
640 int probe;
641 QModelIndex probeIndex;
642 QString probeData;
643
644 while (high - low > 1)
645 {
646 probe = (high + low) / 2;
647 probeIndex = model->index(probe, c->column, parent);
648 probeData = model->data(probeIndex, c->role).toString();
649 const int cmp = QString::compare(probeData, part, c->cs);
650 if ((order == Qt::AscendingOrder && cmp >= 0)
651 || (order == Qt::DescendingOrder && cmp < 0)) {
652 high = probe;
653 } else {
654 low = probe;
655 }
656 }
657
658 if ((order == Qt::AscendingOrder && low == indices.to())
659 || (order == Qt::DescendingOrder && high == indices.from())) { // not found
660 saveInCache(part, parent, QMatchData());
661 return QMatchData();
662 }
663
664 probeIndex = model->index(order == Qt::AscendingOrder ? low+1 : high-1, c->column, parent);
665 probeData = model->data(probeIndex, c->role).toString();
666 if (!probeData.startsWith(part, c->cs)) {
667 saveInCache(part, parent, QMatchData());
668 return QMatchData();
669 }
670
671 const bool exactMatch = QString::compare(probeData, part, c->cs) == 0;
672 int emi = exactMatch ? (order == Qt::AscendingOrder ? low+1 : high-1) : -1;
673
674 int from = 0;
675 int to = 0;
676 if (order == Qt::AscendingOrder) {
677 from = low + 1;
678 high = indices.to() + 1;
679 low = from;
680 } else {
681 to = high - 1;
682 low = indices.from() - 1;
683 high = to;
684 }
685
686 while (high - low > 1)
687 {
688 probe = (high + low) / 2;
689 probeIndex = model->index(probe, c->column, parent);
690 probeData = model->data(probeIndex, c->role).toString();
691 const bool startsWith = probeData.startsWith(part, c->cs);
692 if ((order == Qt::AscendingOrder && startsWith)
693 || (order == Qt::DescendingOrder && !startsWith)) {
694 low = probe;
695 } else {
696 high = probe;
697 }
698 }
699
700 QMatchData m(order == Qt::AscendingOrder ? QIndexMapper(from, high - 1) : QIndexMapper(low+1, to), emi, false);
701 saveInCache(part, parent, m);
702 return m;
703}
704
705////////////////////////////////////////////////////////////////////////////////////////
706int QUnsortedModelEngine::buildIndices(const QString& str, const QModelIndex& parent, int n,
707 const QIndexMapper& indices, QMatchData* m)
708{
709 Q_ASSERT(m->partial);
710 Q_ASSERT(n != -1 || m->exactMatchIndex == -1);
711 const QAbstractItemModel *model = c->proxy->sourceModel();
712 int i, count = 0;
713
714 for (i = 0; i < indices.count() && count != n; ++i) {
715 QModelIndex idx = model->index(indices[i], c->column, parent);
716
717 if (!(model->flags(idx) & Qt::ItemIsSelectable))
718 continue;
719
720 QString data = model->data(idx, c->role).toString();
721
722 switch (c->filterMode) {
723 case Qt::MatchStartsWith:
724 if (!data.startsWith(str, c->cs))
725 continue;
726 break;
727 case Qt::MatchContains:
728 if (!data.contains(str, c->cs))
729 continue;
730 break;
731 case Qt::MatchEndsWith:
732 if (!data.endsWith(str, c->cs))
733 continue;
734 break;
735 case Qt::MatchExactly:
736 case Qt::MatchFixedString:
737 case Qt::MatchCaseSensitive:
738 case Qt::MatchRegularExpression:
739 case Qt::MatchWildcard:
740 case Qt::MatchWrap:
741 case Qt::MatchRecursive:
742 Q_UNREACHABLE();
743 break;
744 }
745 m->indices.append(indices[i]);
746 ++count;
747 if (m->exactMatchIndex == -1 && QString::compare(data, str, c->cs) == 0) {
748 m->exactMatchIndex = indices[i];
749 if (n == -1)
750 return indices[i];
751 }
752 }
753 return indices[i-1];
754}
755
757{
758 Q_ASSERT(matchCount());
759 if (!curMatch.partial)
760 return;
761 Q_ASSERT(n >= -1);
762 const QAbstractItemModel *model = c->proxy->sourceModel();
763 int lastRow = model->rowCount(curParent) - 1;
764 QIndexMapper im(curMatch.indices.last() + 1, lastRow);
765 int lastIndex = buildIndices(curParts.constLast(), curParent, n, im, &curMatch);
766 curMatch.partial = (lastRow != lastIndex);
767 saveInCache(curParts.constLast(), curParent, curMatch);
768}
769
770QMatchData QUnsortedModelEngine::filter(const QString& part, const QModelIndex& parent, int n)
771{
772 QMatchData hint;
773
774 QList<int> v;
775 QIndexMapper im(v);
776 QMatchData m(im, -1, true);
777
778 const QAbstractItemModel *model = c->proxy->sourceModel();
779 bool foundInCache = lookupCache(part, parent, &m);
780
781 if (!foundInCache) {
782 if (matchHint(part, parent, &hint) && !hint.isValid())
783 return QMatchData();
784 }
785
786 if (!foundInCache && !hint.isValid()) {
787 const int lastRow = model->rowCount(parent) - 1;
788 QIndexMapper all(0, lastRow);
789 int lastIndex = buildIndices(part, parent, n, all, &m);
790 m.partial = (lastIndex != lastRow);
791 } else {
792 if (!foundInCache) { // build from hint as much as we can
793 buildIndices(part, parent, INT_MAX, hint.indices, &m);
794 m.partial = hint.partial;
795 }
796 if (m.partial && ((n == -1 && m.exactMatchIndex == -1) || (m.indices.count() < n))) {
797 // need more and have more
798 const int lastRow = model->rowCount(parent) - 1;
799 QIndexMapper rest(hint.indices.last() + 1, lastRow);
800 int want = n == -1 ? -1 : n - m.indices.count();
801 int lastIndex = buildIndices(part, parent, want, rest, &m);
802 m.partial = (lastRow != lastIndex);
803 }
804 }
805
806 saveInCache(part, parent, m);
807 return m;
808}
809
810///////////////////////////////////////////////////////////////////////////////
811QCompleterPrivate::QCompleterPrivate()
812 : widget(nullptr),
813 proxy(nullptr),
814 popup(nullptr),
815 filterMode(Qt::MatchStartsWith),
816 cs(Qt::CaseSensitive),
817 role(Qt::EditRole),
818 column(0),
820 sorting(QCompleter::UnsortedModel),
821 wrap(true),
822 eatFocusOut(true),
824{
825}
826
827void QCompleterPrivate::init(QAbstractItemModel *m)
828{
829 Q_Q(QCompleter);
830 proxy = new QCompletionModel(this, q);
831 QObject::connect(proxy, SIGNAL(rowsAdded()), q, SLOT(_q_autoResizePopup()));
832 q->setModel(m);
833#if !QT_CONFIG(listview)
834 q->setCompletionMode(QCompleter::InlineCompletion);
835#else
836 q->setCompletionMode(QCompleter::PopupCompletion);
837#endif // QT_CONFIG(listview)
838}
839
840void QCompleterPrivate::setCurrentIndex(QModelIndex index, bool select)
841{
842 Q_Q(QCompleter);
843 if (!q->popup())
844 return;
845 if (!select) {
846 popup->selectionModel()->setCurrentIndex(index, QItemSelectionModel::NoUpdate);
847 } else {
848 if (!index.isValid())
849 popup->selectionModel()->clear();
850 else
851 popup->selectionModel()->setCurrentIndex(index, QItemSelectionModel::Select
852 | QItemSelectionModel::Rows);
853 }
854 index = popup->selectionModel()->currentIndex();
855 if (!index.isValid())
856 popup->scrollToTop();
857 else
858 popup->scrollTo(index, QAbstractItemView::PositionAtTop);
859}
860
861void QCompleterPrivate::_q_completionSelected(const QItemSelection& selection)
862{
863 QModelIndex index;
864 if (const auto indexes = selection.indexes(); !indexes.isEmpty())
865 index = indexes.first();
866
867 _q_complete(index, true);
868}
869
870void QCompleterPrivate::_q_complete(QModelIndex index, bool highlighted)
871{
872 Q_Q(QCompleter);
873 QString completion;
874
875 if (!index.isValid() || (!proxy->showAll && (index.row() >= proxy->engine->matchCount()))) {
876 completion = prefix;
877 index = QModelIndex();
878 } else {
879 if (!(index.flags() & Qt::ItemIsEnabled))
880 return;
881 QModelIndex si = proxy->mapToSource(index);
882 si = si.sibling(si.row(), column); // for clicked()
883 completion = q->pathFromIndex(si);
884#if QT_CONFIG(filesystemmodel)
885 // add a trailing separator in inline
886 if (mode == QCompleter::InlineCompletion) {
887 if (qobject_cast<QFileSystemModel *>(proxy->sourceModel()) && QFileInfo(completion).isDir())
888 completion += QDir::separator();
889 }
890#endif
891 }
892
893 if (highlighted) {
894 emit q->highlighted(index);
895 emit q->highlighted(completion);
896 } else {
897 emit q->activated(index);
898 emit q->activated(completion);
899 }
900}
901
903{
904 if (!popup || !popup->isVisible())
905 return;
906 showPopup(popupRect);
907}
908
909void QCompleterPrivate::showPopup(const QRect& rect)
910{
911 const QRect screen = widget->screen()->availableGeometry();
912 QPoint pos;
913 int rh, w;
914 int h = (popup->sizeHintForRow(0) * qMin(maxVisibleItems, popup->model()->rowCount()) + 3) + 3;
915 QScrollBar *hsb = popup->horizontalScrollBar();
916 if (hsb && hsb->isVisible())
917 h += popup->horizontalScrollBar()->sizeHint().height();
918
919 if (rect.isValid()) {
920 rh = rect.height();
921 w = rect.width();
922 pos = widget->mapToGlobal(rect.bottomLeft());
923 } else {
924 rh = widget->height();
925 pos = widget->mapToGlobal(QPoint(0, widget->height() - 2));
926 w = widget->width();
927 }
928
929 if (w > screen.width())
930 w = screen.width();
931 if ((pos.x() + w) > (screen.x() + screen.width()))
932 pos.setX(screen.x() + screen.width() - w);
933 if (pos.x() < screen.x())
934 pos.setX(screen.x());
935
936 int top = pos.y() - rh - screen.top() + 2;
937 int bottom = screen.bottom() - pos.y();
938 h = qMax(h, popup->minimumHeight());
939 if (h > bottom) {
940 h = qMin(qMax(top, bottom), h);
941
942 if (top > bottom)
943 pos.setY(pos.y() - h - rh + 2);
944 }
945
946 popup->setGeometry(pos.x(), pos.y(), w, h);
947
948 if (!popup->isVisible()) {
949#if QT_CONFIG(wayland)
950 popup->createWinId();
951 if (auto waylandWindow = dynamic_cast<QNativeInterface::Private::QWaylandWindow*>(popup->windowHandle()->handle())) {
952 popup->windowHandle()->setTransientParent(widget->window()->windowHandle());
953 if (!rect.isValid()) { // Automatically positioned popup
954 const QRect controlGeometry = QRect(
955 widget->mapTo(widget->topLevelWidget(), QPoint(0, 0)), widget->size());
956 waylandWindow->setParentControlGeometry(controlGeometry);
957 waylandWindow->setExtendedWindowType(
958 QNativeInterface::Private::QWaylandWindow::ComboBox);
959 }
960 }
961#endif
962 popup->show();
963 }
964}
965
966#if QT_CONFIG(filesystemmodel)
967static bool isRoot(const QFileSystemModel *model, const QString &path)
968{
969 const auto index = model->index(path);
970 return index.isValid() && model->fileInfo(index).isRoot();
971}
972
973static bool completeOnLoaded(const QFileSystemModel *model,
974 const QString &nativePrefix,
975 const QString &path,
976 Qt::CaseSensitivity caseSensitivity)
977{
978 const auto pathSize = path.size();
979 const auto prefixSize = nativePrefix.size();
980 if (prefixSize < pathSize)
981 return false;
982 const QString prefix = QDir::fromNativeSeparators(nativePrefix);
983 if (prefixSize == pathSize)
984 return path.compare(prefix, caseSensitivity) == 0 && isRoot(model, path);
985 // The user is typing something within that directory and is not in a subdirectory yet.
986 const auto separator = u'/';
987 return prefix.startsWith(path, caseSensitivity) && prefix.at(pathSize) == separator
988 && !QStringView{prefix}.right(prefixSize - pathSize - 1).contains(separator);
989}
990
991void QCompleterPrivate::_q_fileSystemModelDirectoryLoaded(const QString &path)
992{
993 Q_Q(QCompleter);
994 // Slot called when QFileSystemModel has finished loading.
995 // If we hide the popup because there was no match because the model was not loaded yet,
996 // we re-start the completion when we get the results (unless triggered by
997 // something else, see QTBUG-14292).
998 if (hiddenBecauseNoMatch && widget) {
999 if (auto model = qobject_cast<const QFileSystemModel *>(proxy->sourceModel())) {
1000 if (completeOnLoaded(model, prefix, path, cs))
1001 q->complete();
1002 }
1003 }
1004}
1005#else // QT_CONFIG(filesystemmodel)
1007#endif
1008
1009/*!
1010 Constructs a completer object with the given \a parent.
1011*/
1012QCompleter::QCompleter(QObject *parent)
1013: QObject(*new QCompleterPrivate(), parent)
1014{
1015 Q_D(QCompleter);
1016 d->init();
1017}
1018
1019/*!
1020 Constructs a completer object with the given \a parent that provides completions
1021 from the specified \a model.
1022*/
1023QCompleter::QCompleter(QAbstractItemModel *model, QObject *parent)
1024 : QObject(*new QCompleterPrivate(), parent)
1025{
1026 Q_D(QCompleter);
1027 d->init(model);
1028}
1029
1030#if QT_CONFIG(stringlistmodel)
1031/*!
1032 Constructs a QCompleter object with the given \a parent that uses the specified
1033 \a list as a source of possible completions.
1034*/
1035QCompleter::QCompleter(const QStringList& list, QObject *parent)
1036: QObject(*new QCompleterPrivate(), parent)
1037{
1038 Q_D(QCompleter);
1039 d->init(new QStringListModel(list, this));
1040}
1041#endif // QT_CONFIG(stringlistmodel)
1042
1043/*!
1044 Destroys the completer object.
1045*/
1046QCompleter::~QCompleter()
1047{
1048}
1049
1050/*!
1051 Sets the widget for which completion are provided for to \a widget. This
1052 function is automatically called when a QCompleter is set on a QLineEdit
1053 using QLineEdit::setCompleter() or on a QComboBox using
1054 QComboBox::setCompleter(). The widget needs to be set explicitly when
1055 providing completions for custom widgets.
1056
1057 \sa widget(), setModel(), setPopup()
1058 */
1059void QCompleter::setWidget(QWidget *widget)
1060{
1061 Q_D(QCompleter);
1062 if (widget == d->widget)
1063 return;
1064
1065 if (d->widget)
1066 d->widget->removeEventFilter(this);
1067 d->widget = widget;
1068 if (d->widget)
1069 d->widget->installEventFilter(this);
1070
1071 if (d->popup) {
1072 d->popup->hide();
1073 d->popup->setFocusProxy(d->widget);
1074 }
1075}
1076
1077/*!
1078 Returns the widget for which the completer object is providing completions.
1079
1080 \sa setWidget()
1081 */
1082QWidget *QCompleter::widget() const
1083{
1084 Q_D(const QCompleter);
1085 return d->widget;
1086}
1087
1088/*!
1089 Sets the model which provides completions to \a model. The \a model can
1090 be list model or a tree model. If a model has been already previously set
1091 and it has the QCompleter as its parent, it is deleted.
1092
1093 For convenience, if \a model is a QFileSystemModel, QCompleter switches its
1094 caseSensitivity to Qt::CaseInsensitive on Windows and Qt::CaseSensitive
1095 on other platforms.
1096
1097 \sa completionModel(), modelSorting, {Handling Tree Models}
1098*/
1099void QCompleter::setModel(QAbstractItemModel *model)
1100{
1101 Q_D(QCompleter);
1102 QAbstractItemModel *oldModel = d->proxy->sourceModel();
1103 if (oldModel == model)
1104 return;
1105#if QT_CONFIG(filesystemmodel)
1106 if (qobject_cast<const QFileSystemModel *>(oldModel))
1107 setCompletionRole(Qt::EditRole); // QTBUG-54642, clear FileNameRole set by QFileSystemModel
1108#endif
1109 d->proxy->setSourceModel(model);
1110 if (d->popup)
1111 setPopup(d->popup); // set the model and make new connections
1112 if (oldModel && oldModel->QObject::parent() == this)
1113 delete oldModel;
1114#if QT_CONFIG(filesystemmodel)
1115 QFileSystemModel *fsModel = qobject_cast<QFileSystemModel *>(model);
1116 if (fsModel) {
1117#if defined(Q_OS_WIN)
1118 setCaseSensitivity(Qt::CaseInsensitive);
1119#else
1120 setCaseSensitivity(Qt::CaseSensitive);
1121#endif
1122 setCompletionRole(QFileSystemModel::FileNameRole);
1123 connect(fsModel, SIGNAL(directoryLoaded(QString)), this, SLOT(_q_fileSystemModelDirectoryLoaded(QString)));
1124 }
1125#endif // QT_CONFIG(filesystemmodel)
1126}
1127
1128/*!
1129 Returns the model that provides completion strings.
1130
1131 \sa completionModel()
1132*/
1133QAbstractItemModel *QCompleter::model() const
1134{
1135 Q_D(const QCompleter);
1136 return d->proxy->sourceModel();
1137}
1138
1139/*!
1140 \enum QCompleter::CompletionMode
1141
1142 This enum specifies how completions are provided to the user.
1143
1144 \value PopupCompletion Current completions are displayed in a popup window.
1145 \value InlineCompletion Completions appear inline (as selected text).
1146 \value UnfilteredPopupCompletion All possible completions are displayed in a popup window with the most likely suggestion indicated as current.
1147
1148 \sa setCompletionMode()
1149*/
1150
1151/*!
1152 \property QCompleter::completionMode
1153 \brief how the completions are provided to the user
1154
1155 The default value is QCompleter::PopupCompletion.
1156*/
1157void QCompleter::setCompletionMode(QCompleter::CompletionMode mode)
1158{
1159 Q_D(QCompleter);
1160 d->mode = mode;
1161 d->proxy->setFiltered(mode != QCompleter::UnfilteredPopupCompletion);
1162
1163 if (mode == QCompleter::InlineCompletion) {
1164 if (d->widget)
1165 d->widget->removeEventFilter(this);
1166 if (d->popup) {
1167 d->popup->deleteLater();
1168 d->popup = nullptr;
1169 }
1170 } else {
1171 if (d->widget)
1172 d->widget->installEventFilter(this);
1173 }
1174}
1175
1176QCompleter::CompletionMode QCompleter::completionMode() const
1177{
1178 Q_D(const QCompleter);
1179 return d->mode;
1180}
1181
1182/*!
1183 \property QCompleter::filterMode
1184 \brief This property controls how filtering is performed.
1185 \since 5.2
1186
1187 If filterMode is set to Qt::MatchStartsWith, only those entries that start
1188 with the typed characters will be displayed. Qt::MatchContains will display
1189 the entries that contain the typed characters, and Qt::MatchEndsWith the
1190 ones that end with the typed characters.
1191
1192 Setting filterMode to any other Qt::MatchFlag will issue a warning, and no
1193 action will be performed. Because of this, the \c Qt::MatchCaseSensitive
1194 flag has no effect. Use the \l caseSensitivity property to control case
1195 sensitivity.
1196
1197 The default mode is Qt::MatchStartsWith.
1198
1199 \sa caseSensitivity
1200*/
1201
1202void QCompleter::setFilterMode(Qt::MatchFlags filterMode)
1203{
1204 Q_D(QCompleter);
1205
1206 if (d->filterMode == filterMode)
1207 return;
1208
1209 if (Q_UNLIKELY(filterMode != Qt::MatchStartsWith &&
1210 filterMode != Qt::MatchContains &&
1211 filterMode != Qt::MatchEndsWith)) {
1212 qWarning("Unhandled QCompleter::filterMode flag is used.");
1213 return;
1214 }
1215
1216 d->filterMode = filterMode;
1217 d->proxy->createEngine();
1218 d->proxy->invalidate();
1219}
1220
1221Qt::MatchFlags QCompleter::filterMode() const
1222{
1223 Q_D(const QCompleter);
1224 return d->filterMode;
1225}
1226
1227/*!
1228 Sets the popup used to display completions to \a popup. QCompleter takes
1229 ownership of the view.
1230
1231 A QListView is automatically created when the completionMode() is set to
1232 QCompleter::PopupCompletion or QCompleter::UnfilteredPopupCompletion. The
1233 default popup displays the completionColumn().
1234
1235 Ensure that this function is called before the view settings are modified.
1236 This is required since view's properties may require that a model has been
1237 set on the view (for example, hiding columns in the view requires a model
1238 to be set on the view).
1239
1240 \sa popup()
1241*/
1242void QCompleter::setPopup(QAbstractItemView *popup)
1243{
1244 Q_ASSERT(popup);
1245 Q_D(QCompleter);
1246 if (popup == d->popup)
1247 return;
1248
1249 // Remember existing widget's focus policy, default to NoFocus
1250 const Qt::FocusPolicy origPolicy = d->widget ? d->widget->focusPolicy()
1251 : Qt::NoFocus;
1252
1253 // If popup existed already, disconnect signals and delete object
1254 if (d->popup) {
1255 QObject::disconnect(d->popup->selectionModel(), nullptr, this, nullptr);
1256 QObject::disconnect(d->popup, nullptr, this, nullptr);
1257 delete d->popup;
1258 }
1259
1260 // Assign new object, set model and hide
1261 d->popup = popup;
1262 if (d->popup->model() != d->proxy)
1263 d->popup->setModel(d->proxy);
1264 d->popup->hide();
1265
1266 // Mark the widget window as a popup, so that if the last non-popup window is closed by the
1267 // user, the application should not be prevented from exiting. It needs to be set explicitly via
1268 // setWindowFlag(), because passing the flag via setParent(parent, windowFlags) does not call
1269 // QWidgetPrivate::adjustQuitOnCloseAttribute(), and causes an application not to exit if the
1270 // popup ends up being the last window.
1271 d->popup->setParent(nullptr);
1272 d->popup->setWindowFlag(Qt::Popup);
1273 d->popup->setFocusPolicy(Qt::NoFocus);
1274 if (d->widget)
1275 d->widget->setFocusPolicy(origPolicy);
1276
1277 d->popup->setFocusProxy(d->widget);
1278 d->popup->installEventFilter(this);
1279 d->popup->setItemDelegate(new QCompleterItemDelegate(d->popup));
1280#if QT_CONFIG(listview)
1281 if (QListView *listView = qobject_cast<QListView *>(d->popup)) {
1282 listView->setModelColumn(d->column);
1283 }
1284#endif
1285
1286 QObject::connect(d->popup, SIGNAL(clicked(QModelIndex)),
1287 this, SLOT(_q_complete(QModelIndex)));
1288 QObject::connect(this, SIGNAL(activated(QModelIndex)),
1289 d->popup, SLOT(hide()));
1290
1291 QObject::connect(d->popup->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
1292 this, SLOT(_q_completionSelected(QItemSelection)));
1293}
1294
1295/*!
1296 Returns the popup used to display completions.
1297
1298 \sa setPopup()
1299*/
1300QAbstractItemView *QCompleter::popup() const
1301{
1302 Q_D(const QCompleter);
1303#if QT_CONFIG(listview)
1304 if (!d->popup && completionMode() != QCompleter::InlineCompletion) {
1305 QListView *listView = new QListView;
1306 listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
1307 listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1308 listView->setSelectionBehavior(QAbstractItemView::SelectRows);
1309 listView->setSelectionMode(QAbstractItemView::SingleSelection);
1310 listView->setModelColumn(d->column);
1311 QCompleter *that = const_cast<QCompleter*>(this);
1312 that->setPopup(listView);
1313 }
1314#endif // QT_CONFIG(listview)
1315 return d->popup;
1316}
1317
1318/*!
1319 \reimp
1320*/
1321bool QCompleter::event(QEvent *ev)
1322{
1323 return QObject::event(ev);
1324}
1325
1326/*!
1327 \reimp
1328*/
1329bool QCompleter::eventFilter(QObject *o, QEvent *e)
1330{
1331 Q_D(QCompleter);
1332
1333 if (o == d->widget) {
1334 switch (e->type()) {
1335 case QEvent::FocusOut:
1336 if (d->eatFocusOut) {
1337 d->hiddenBecauseNoMatch = false;
1338 if (d->popup && d->popup->isVisible())
1339 return true;
1340 }
1341 break;
1342 case QEvent::Hide:
1343 if (d->popup)
1344 d->popup->hide();
1345 break;
1346 default:
1347 break;
1348 }
1349 }
1350
1351 if (o != d->popup)
1352 return QObject::eventFilter(o, e);
1353
1354 Q_ASSERT(d->popup);
1355 switch (e->type()) {
1356 case QEvent::KeyPress: {
1357 QKeyEvent *ke = static_cast<QKeyEvent *>(e);
1358
1359 QModelIndex curIndex = d->popup->currentIndex();
1360 QModelIndexList selList = d->popup->selectionModel()->selectedIndexes();
1361
1362 const int key = ke->key();
1363 // In UnFilteredPopup mode, select the current item
1364 if ((key == Qt::Key_Up || key == Qt::Key_Down) && selList.isEmpty() && curIndex.isValid()
1365 && d->mode == QCompleter::UnfilteredPopupCompletion) {
1366 d->setCurrentIndex(curIndex);
1367 return true;
1368 }
1369
1370 // Handle popup navigation keys. These are hardcoded because up/down might make the
1371 // widget do something else (lineedit cursor moves to home/end on mac, for instance)
1372 switch (key) {
1373 case Qt::Key_End:
1374 case Qt::Key_Home:
1375 if (ke->modifiers() & Qt::ControlModifier)
1376 return false;
1377 break;
1378
1379 case Qt::Key_Up:
1380 if (!curIndex.isValid()) {
1381 int rowCount = d->proxy->rowCount();
1382 QModelIndex lastIndex = d->proxy->index(rowCount - 1, d->column);
1383 d->setCurrentIndex(lastIndex);
1384 return true;
1385 } else if (curIndex.row() == 0) {
1386 if (d->wrap)
1387 d->setCurrentIndex(QModelIndex());
1388 return true;
1389 }
1390 return false;
1391
1392 case Qt::Key_Down:
1393 if (!curIndex.isValid()) {
1394 QModelIndex firstIndex = d->proxy->index(0, d->column);
1395 d->setCurrentIndex(firstIndex);
1396 return true;
1397 } else if (curIndex.row() == d->proxy->rowCount() - 1) {
1398 if (d->wrap)
1399 d->setCurrentIndex(QModelIndex());
1400 return true;
1401 }
1402 return false;
1403
1404 case Qt::Key_PageUp:
1405 case Qt::Key_PageDown:
1406 return false;
1407 }
1408
1409 if (d->widget) {
1410 // Send the event to the widget. If the widget accepted the event, do nothing
1411 // If the widget did not accept the event, provide a default implementation
1412 d->eatFocusOut = false;
1413 (static_cast<QObject *>(d->widget))->event(ke);
1414 d->eatFocusOut = true;
1415 }
1416 if (!d->widget || e->isAccepted() || !d->popup->isVisible()) {
1417 // widget lost focus, hide the popup
1418 if (d->widget && !d->widget->hasFocus())
1419 d->popup->hide();
1420 if (e->isAccepted())
1421 return true;
1422 }
1423
1424 // default implementation for keys not handled by the widget when popup is open
1425#if QT_CONFIG(shortcut)
1426 if (ke->matches(QKeySequence::Cancel)) {
1427 d->popup->hide();
1428 return true;
1429 }
1430#endif
1431 switch (key) {
1432 case Qt::Key_Return:
1433 case Qt::Key_Enter:
1434 case Qt::Key_Tab:
1435 d->popup->hide();
1436 if (curIndex.isValid())
1437 d->_q_complete(curIndex);
1438 break;
1439
1440 case Qt::Key_F4:
1441 if (ke->modifiers() & Qt::AltModifier)
1442 d->popup->hide();
1443 break;
1444
1445 case Qt::Key_Backtab:
1446 d->popup->hide();
1447 break;
1448
1449 default:
1450 break;
1451 }
1452
1453 return true;
1454 }
1455
1456 case QEvent::MouseButtonPress:
1457 if (!d->popup->underMouse()) {
1458 if (!QGuiApplicationPrivate::maybeForwardEventToVirtualKeyboard(e))
1459 d->popup->hide();
1460 return true;
1461 }
1462 return false;
1463
1464 case QEvent::MouseButtonRelease:
1465 QGuiApplicationPrivate::maybeForwardEventToVirtualKeyboard(e);
1466 return true;
1467 case QEvent::InputMethod:
1468 case QEvent::ShortcutOverride:
1469 if (d->widget)
1470 QCoreApplication::sendEvent(d->widget, e);
1471 break;
1472
1473 default:
1474 return false;
1475 }
1476 return false;
1477}
1478
1479/*!
1480 For QCompleter::PopupCompletion and QCompletion::UnfilteredPopupCompletion
1481 modes, calling this function displays the popup displaying the current
1482 completions. By default, if \a rect is not specified, the popup is displayed
1483 on the bottom of the widget(). If \a rect is specified the popup is
1484 displayed on the left edge of the rectangle.
1485
1486 For QCompleter::InlineCompletion mode, the highlighted() signal is fired
1487 with the current completion.
1488*/
1489void QCompleter::complete(const QRect& rect)
1490{
1491 Q_D(QCompleter);
1492 QModelIndex idx = d->proxy->currentIndex(false);
1493 d->hiddenBecauseNoMatch = false;
1494 if (d->mode == QCompleter::InlineCompletion) {
1495 if (idx.isValid())
1496 d->_q_complete(idx, true);
1497 return;
1498 }
1499
1500 Q_ASSERT(d->widget);
1501 if ((d->mode == QCompleter::PopupCompletion && !idx.isValid())
1502 || (d->mode == QCompleter::UnfilteredPopupCompletion && d->proxy->rowCount() == 0)) {
1503 if (d->popup)
1504 d->popup->hide(); // no suggestion, hide
1505 d->hiddenBecauseNoMatch = true;
1506 return;
1507 }
1508
1509 popup();
1510 if (d->mode == QCompleter::UnfilteredPopupCompletion)
1511 d->setCurrentIndex(idx, false);
1512
1513 d->showPopup(rect);
1514 d->popupRect = rect;
1515}
1516
1517/*!
1518 Sets the current row to the \a row specified. Returns \c true if successful;
1519 otherwise returns \c false.
1520
1521 This function may be used along with currentCompletion() to iterate
1522 through all the possible completions.
1523
1524 \sa currentCompletion(), completionCount()
1525*/
1526bool QCompleter::setCurrentRow(int row)
1527{
1528 Q_D(QCompleter);
1529 return d->proxy->setCurrentRow(row);
1530}
1531
1532/*!
1533 Returns the current row.
1534
1535 \sa setCurrentRow()
1536*/
1537int QCompleter::currentRow() const
1538{
1539 Q_D(const QCompleter);
1540 return d->proxy->currentRow();
1541}
1542
1543/*!
1544 Returns the number of completions for the current prefix. For an unsorted
1545 model with a large number of items this can be expensive. Use setCurrentRow()
1546 and currentCompletion() to iterate through all the completions.
1547*/
1548int QCompleter::completionCount() const
1549{
1550 Q_D(const QCompleter);
1551 return d->proxy->completionCount();
1552}
1553
1554/*!
1555 \enum QCompleter::ModelSorting
1556
1557 This enum specifies how the items in the model are sorted.
1558
1559 \value UnsortedModel The model is unsorted.
1560 \value CaseSensitivelySortedModel The model is sorted case sensitively.
1561 \value CaseInsensitivelySortedModel The model is sorted case insensitively.
1562
1563 \sa setModelSorting()
1564*/
1565
1566/*!
1567 \property QCompleter::modelSorting
1568 \brief the way the model is sorted
1569
1570 By default, no assumptions are made about the order of the items
1571 in the model that provides the completions.
1572
1573 If the model's data for the completionColumn() and completionRole() is sorted in
1574 ascending order, you can set this property to \l CaseSensitivelySortedModel
1575 or \l CaseInsensitivelySortedModel. On large models, this can lead to
1576 significant performance improvements because the completer object can
1577 then use a binary search algorithm instead of linear search algorithm.
1578
1579 The sort order (i.e ascending or descending order) of the model is determined
1580 dynamically by inspecting the contents of the model.
1581
1582 \b{Note:} The performance improvements described above cannot take place
1583 when the completer's \l caseSensitivity is different to the case sensitivity
1584 used by the model's when sorting.
1585
1586 \sa setCaseSensitivity(), QCompleter::ModelSorting
1587*/
1588void QCompleter::setModelSorting(QCompleter::ModelSorting sorting)
1589{
1590 Q_D(QCompleter);
1591 if (d->sorting == sorting)
1592 return;
1593 d->sorting = sorting;
1594 d->proxy->createEngine();
1595 d->proxy->invalidate();
1596}
1597
1598QCompleter::ModelSorting QCompleter::modelSorting() const
1599{
1600 Q_D(const QCompleter);
1601 return d->sorting;
1602}
1603
1604/*!
1605 \property QCompleter::completionColumn
1606 \brief the column in the model in which completions are searched for.
1607
1608 If the popup() is a QListView, it is automatically setup to display
1609 this column.
1610
1611 By default, the match column is 0.
1612
1613 \sa completionRole, caseSensitivity
1614*/
1615void QCompleter::setCompletionColumn(int column)
1616{
1617 Q_D(QCompleter);
1618 if (d->column == column)
1619 return;
1620#if QT_CONFIG(listview)
1621 if (QListView *listView = qobject_cast<QListView *>(d->popup))
1622 listView->setModelColumn(column);
1623#endif
1624 d->column = column;
1625 d->proxy->invalidate();
1626}
1627
1628int QCompleter::completionColumn() const
1629{
1630 Q_D(const QCompleter);
1631 return d->column;
1632}
1633
1634/*!
1635 \property QCompleter::completionRole
1636 \brief the item role to be used to query the contents of items for matching.
1637
1638 The default role is Qt::EditRole.
1639
1640 \sa completionColumn, caseSensitivity
1641*/
1642void QCompleter::setCompletionRole(int role)
1643{
1644 Q_D(QCompleter);
1645 if (d->role == role)
1646 return;
1647 d->role = role;
1648 d->proxy->invalidate();
1649}
1650
1651int QCompleter::completionRole() const
1652{
1653 Q_D(const QCompleter);
1654 return d->role;
1655}
1656
1657/*!
1658 \property QCompleter::wrapAround
1659 \brief the completions wrap around when navigating through items
1660 \since 4.3
1661
1662 The default is true.
1663*/
1664void QCompleter::setWrapAround(bool wrap)
1665{
1666 Q_D(QCompleter);
1667 if (d->wrap == wrap)
1668 return;
1669 d->wrap = wrap;
1670}
1671
1672bool QCompleter::wrapAround() const
1673{
1674 Q_D(const QCompleter);
1675 return d->wrap;
1676}
1677
1678/*!
1679 \property QCompleter::maxVisibleItems
1680 \brief the maximum allowed size on screen of the completer, measured in items
1681 \since 4.6
1682
1683 By default, this property has a value of 7.
1684*/
1685int QCompleter::maxVisibleItems() const
1686{
1687 Q_D(const QCompleter);
1688 return d->maxVisibleItems;
1689}
1690
1691void QCompleter::setMaxVisibleItems(int maxItems)
1692{
1693 Q_D(QCompleter);
1694 if (Q_UNLIKELY(maxItems < 0)) {
1695 qWarning("QCompleter::setMaxVisibleItems: "
1696 "Invalid max visible items (%d) must be >= 0", maxItems);
1697 return;
1698 }
1699 d->maxVisibleItems = maxItems;
1700}
1701
1702/*!
1703 \property QCompleter::caseSensitivity
1704 \brief the case sensitivity of the matching
1705
1706 The default value is \c Qt::CaseSensitive.
1707
1708 \sa completionColumn, completionRole, modelSorting, filterMode
1709*/
1710void QCompleter::setCaseSensitivity(Qt::CaseSensitivity cs)
1711{
1712 Q_D(QCompleter);
1713 if (d->cs == cs)
1714 return;
1715 d->cs = cs;
1716 d->proxy->createEngine();
1717 d->proxy->invalidate();
1718}
1719
1720Qt::CaseSensitivity QCompleter::caseSensitivity() const
1721{
1722 Q_D(const QCompleter);
1723 return d->cs;
1724}
1725
1726/*!
1727 \property QCompleter::completionPrefix
1728 \brief the completion prefix used to provide completions.
1729
1730 The completionModel() is updated to reflect the list of possible
1731 matches for \a prefix.
1732*/
1733void QCompleter::setCompletionPrefix(const QString &prefix)
1734{
1735 Q_D(QCompleter);
1736 d->prefix = prefix;
1737 d->proxy->filter(splitPath(prefix));
1738}
1739
1740QString QCompleter::completionPrefix() const
1741{
1742 Q_D(const QCompleter);
1743 return d->prefix;
1744}
1745
1746/*!
1747 Returns the model index of the current completion in the completionModel().
1748
1749 \sa setCurrentRow(), currentCompletion(), model()
1750*/
1751QModelIndex QCompleter::currentIndex() const
1752{
1753 Q_D(const QCompleter);
1754 return d->proxy->currentIndex(false);
1755}
1756
1757/*!
1758 Returns the current completion string. This includes the \l completionPrefix.
1759 When used alongside setCurrentRow(), it can be used to iterate through
1760 all the matches.
1761
1762 \sa setCurrentRow(), currentIndex()
1763*/
1764QString QCompleter::currentCompletion() const
1765{
1766 Q_D(const QCompleter);
1767 return pathFromIndex(d->proxy->currentIndex(true));
1768}
1769
1770/*!
1771 Returns the completion model. The completion model is a read-only list model
1772 that contains all the possible matches for the current completion prefix.
1773 The completion model is auto-updated to reflect the current completions.
1774
1775 \note The return value of this function is defined to be an QAbstractItemModel
1776 purely for generality. This actual kind of model returned is an instance of an
1777 QAbstractProxyModel subclass.
1778
1779 \sa completionPrefix, model()
1780*/
1781QAbstractItemModel *QCompleter::completionModel() const
1782{
1783 Q_D(const QCompleter);
1784 return d->proxy;
1785}
1786
1787/*!
1788 Returns the path for the given \a index. The completer object uses this to
1789 obtain the completion text from the underlying model.
1790
1791 The default implementation returns the \l{Qt::EditRole}{edit role} of the
1792 item for list models. It returns the absolute file path if the model is a
1793 QFileSystemModel.
1794
1795 \sa splitPath()
1796*/
1797
1798QString QCompleter::pathFromIndex(const QModelIndex& index) const
1799{
1800 Q_D(const QCompleter);
1801 if (!index.isValid())
1802 return QString();
1803
1804 QAbstractItemModel *sourceModel = d->proxy->sourceModel();
1805 if (!sourceModel)
1806 return QString();
1807 bool isFsModel = false;
1808#if QT_CONFIG(filesystemmodel)
1809 isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != nullptr;
1810#endif
1811 if (!isFsModel)
1812 return sourceModel->data(index, d->role).toString();
1813
1814 QModelIndex idx = index;
1815 QStringList list;
1816 do {
1817 QString t;
1818#if QT_CONFIG(filesystemmodel)
1819 t = sourceModel->data(idx, QFileSystemModel::FileNameRole).toString();
1820#endif
1821 list.prepend(t);
1822 QModelIndex parent = idx.parent();
1823 idx = parent.sibling(parent.row(), index.column());
1824 } while (idx.isValid());
1825
1826#if !defined(Q_OS_WIN)
1827 if (list.size() == 1) // only the separator or some other text
1828 return list[0];
1829 list[0].clear() ; // the join below will provide the separator
1830#endif
1831
1832 return list.join(QDir::separator());
1833}
1834
1835/*!
1836 Splits the given \a path into strings that are used to match at each level
1837 in the model().
1838
1839 The default implementation of splitPath() splits a file system path based on
1840 QDir::separator() when the sourceModel() is a QFileSystemModel.
1841
1842 When used with list models, the first item in the returned list is used for
1843 matching.
1844
1845 \sa pathFromIndex(), {Handling Tree Models}
1846*/
1847QStringList QCompleter::splitPath(const QString& path) const
1848{
1849 bool isFsModel = false;
1850#if QT_CONFIG(filesystemmodel)
1851 Q_D(const QCompleter);
1852 isFsModel = qobject_cast<QFileSystemModel *>(d->proxy->sourceModel()) != nullptr;
1853#endif
1854
1855 if (!isFsModel || path.isEmpty())
1856 return QStringList(completionPrefix());
1857
1858 QString pathCopy = QDir::toNativeSeparators(path);
1859#if defined(Q_OS_WIN)
1860 if (pathCopy == "\\"_L1 || pathCopy == "\\\\"_L1)
1861 return QStringList(pathCopy);
1862 const bool startsWithDoubleSlash = pathCopy.startsWith("\\\\"_L1);
1863 if (startsWithDoubleSlash)
1864 pathCopy = pathCopy.mid(2);
1865#endif
1866
1867 const QChar sep = QDir::separator();
1868 QStringList parts = pathCopy.split(sep);
1869
1870#if defined(Q_OS_WIN)
1871 if (startsWithDoubleSlash)
1872 parts[0].prepend("\\\\"_L1);
1873#else
1874 if (pathCopy[0] == sep) // readd the "/" at the beginning as the split removed it
1875 parts[0] = u'/';
1876#endif
1877
1878 return parts;
1879}
1880
1881/*!
1882 \fn void QCompleter::activated(const QModelIndex& index)
1883
1884 This signal is sent when an item in the popup() is activated by the user.
1885 (by clicking or pressing return). The item's \a index in the completionModel()
1886 is given.
1887
1888*/
1889
1890/*!
1891 \fn void QCompleter::activated(const QString &text)
1892
1893 This signal is sent when an item in the popup() is activated by the user (by
1894 clicking or pressing return). The item's \a text is given.
1895
1896*/
1897
1898/*!
1899 \fn void QCompleter::highlighted(const QModelIndex& index)
1900
1901 This signal is sent when an item in the popup() is highlighted by
1902 the user. It is also sent if complete() is called with the completionMode()
1903 set to QCompleter::InlineCompletion. The item's \a index in the completionModel()
1904 is given.
1905*/
1906
1907/*!
1908 \fn void QCompleter::highlighted(const QString &text)
1909
1910 This signal is sent when an item in the popup() is highlighted by
1911 the user. It is also sent if complete() is called with the completionMode()
1912 set to QCompleter::InlineCompletion. The item's \a text is given.
1913*/
1914
1915QT_END_NAMESPACE
1916
1917#include "moc_qcompleter.cpp"
1918
1919#include "moc_qcompleter_p.cpp"
void setCurrentIndex(QModelIndex, bool=true)
void _q_fileSystemModelDirectoryLoaded(const QString &path)
void _q_completionSelected(const QItemSelection &)
void init(QAbstractItemModel *model=nullptr)
QAbstractItemView * popup
void _q_complete(QModelIndex, bool=false)
QCompletionModel * proxy
void showPopup(const QRect &)
void saveInCache(QString, const QModelIndex &, const QMatchData &)
void filter(const QStringList &parts)
QMap< QString, QMatchData > CacheItem
int matchCount() const
bool matchHint(const QString &part, const QModelIndex &parent, QMatchData *m) const
bool lookupCache(const QString &part, const QModelIndex &parent, QMatchData *m) const
QCompleterPrivate * c
QMatchData filterHistory()
QModelIndex index(int row, int column, const QModelIndex &=QModelIndex()) const override
Returns the index of the item in the model specified by the given row, column and parent index.
int rowCount(const QModelIndex &index=QModelIndex()) const override
Returns the number of rows under the given parent.
QVariant data(const QModelIndex &index, int role=Qt::DisplayRole) const override
\reimp
void setFiltered(bool)
int completionCount() const
int columnCount(const QModelIndex &index=QModelIndex()) const override
Returns the number of columns for the children of the given parent.
QCompleterPrivate * c
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override
Reimplement this function to return the model index in the proxy model that corresponds to the source...
bool hasChildren(const QModelIndex &parent=QModelIndex()) const override
\reimp
QModelIndex currentIndex(bool) const
void filter(const QStringList &parts)
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override
Reimplement this function to return the model index in the source model that corresponds to the proxy...
void setSourceModel(QAbstractItemModel *sourceModel) override
Sets the given sourceModel to be processed by the proxy model.
Qt::ItemFlags flags(const QModelIndex &index) const override
\reimp
bool setCurrentRow(int row)
int from() const
int indexOf(int x) const
int count() const
int operator[](int index) const
QIndexMapper(int f, int t)
int to() const
QMatchData filter(const QString &, const QModelIndex &, int) override
Qt::SortOrder sortOrder(const QModelIndex &) const
QIndexMapper indexHint(QString, const QModelIndex &, Qt::SortOrder)
void filterOnDemand(int) override
QMatchData filter(const QString &, const QModelIndex &, int) override
Combined button and popup list for selecting options.
QMatchData(const QIndexMapper &indices, int em, bool p)
int exactMatchIndex
bool isValid() const