Home

QtCompletor Class Reference

The QtCompletor class provides completions based on a item model. More...

#include <QtCompletor>

Inherits QObject.

Public Types

Properties

Public Functions

Public Slots

Signals

Protected Functions

Additional Inherited Members


Detailed Description

The QtCompletor class provides completions based on a item model.

You can use QtCompletor to add completion support to any Qt widget (e.g. QLineEdit, QTextEdit, or QComboBox). When the user starts typing a word, QtCompletor suggests possible ways of completing the word, based on a word list. The word list is provided as a QAbstractItemModel. (For simple applications, where the word list is static, you can use QStringListModel.)

Topics:

Setting the Source Model

To set the model on which QtCompletor should operate, call setSourceModel(). By default, QtCompletor will attempt to match a given string against the Qt::EditRole data stored in column 0 in the model case sensitively. This can be changed using setMatchRole(), setMatchColumn(), and setCaseSensitivity().

If the source model is sorted on the column and role that are used for completion, you can call setSourceModelSorting() with either QtCompletor::CaseSensitivelySortedModel or QtCompletor::CaseInsensitivelySortedModel as the argument. On large models, this can lead to significant performance improvements, because QtCompletor can then use binary search instead of linear search.

The source model can be a list model, a table model, or a tree model. Completion on tree models is slightly more involved and is covered in the Handling Tree Models section below.

Finding Completions

For the user, there are two main types of completion, sometimes used concurrently:

QtCompletor supports both modes of operation. You can use match() to retrieve the first candidate and retrieve the following matches using match(QtCompletor::MatchNext). Alternatively, you can set up a QListView to display the completionModel() provided by QtCompletor, and call match() to refresh the model. We will review both approaches in the following subsections.

Getting the Matches One at a Time

To retrieve a single candidate string, call match() with the text that needs to be completed.

Example:

    QStringList wordList;
    wordList << "alpha" << "omega" << "omicron" << "zeta";
    QStringListModel *sourceModel = new QStringListModel(wordList, this);

    QtCompletor *completor = new QtCompletor(this);
    completor->setSourceModel(sourceModel,
                              QtCompletor::CaseInsensitivelySortedModel);
    completor->setCaseSensitivity(Qt::CaseInsensitive);

    QModelIndex index = completor->match("OM");
    qDebug() << sourceModel->data(index).toString() << "is omega";

In the above example, we set up a case-insensitive QtCompletor based on a word list consisting of four words. The match() call returns the QModelIndex of the first match in the source model (or an invalid QModelIndex if there is no match). In this case, the first match is "omega". We can continue iterating using the match() overload that takes only a QtCompletor::MatchFlags argument. For example:

    index = completor->match(QtCompletor::MatchNext);
    qDebug() << sourceModel->data(index).toString() << "is omicron";

    index = completor->match(QtCompletor::MatchNext);
    qDebug() << index.isValid() << "is false";

By default, the matches are provided in the order in which they appear in the source model. If you want certain candidates to appear before others when iterating with match(), you can either make sure that they appear in that order in the source model, or you can assign appropriate weight to the items.

The weight is an integer that specifies how important the candidate is, so that higher-weight candidates appear before lower-weight candidates when iterating. Weights are provided by the source model. Call setWeightColumn() and setWeightRole() to specify which column and role provide the items' weight.

The spellcheck example included with this component illustrates how to use weights to provide higher-quality completions based on word frequencies. It also shows how to perform inline completion in a QTextEdit.

Using the Completion Model

completionModel() return a list model that contains all possible completions for the current match text, in the order in which they appear in the source model (irrespective of weight). The match text is specified using match().

Example:

    QStringList wordList;
    wordList << "alpha" << "omega" << "omicron" << "zeta";
    QStringListModel *sourceModel = new QStringListModel(wordList, this);

    QtCompletor *completor = new QtCompletor(this);
    completor->setSourceModel(sourceModel,
                              QtCompletor::CaseInsensitivelySortedModel);
    completor->setCaseSensitivity(Qt::CaseInsensitive);

    QListView *completionView = new QListView(this);
    completionView->setModel(completor->completionModel());

    completor->match("OM");
    qDebug() << completor->completionModel()->rowCount() << "is 2";

The example sets up a QListView that displays the completion model (the list of all candidates). After the call to match(), the completion model is updated to contain all the words that start with "om" ("omega" and "omicron"). As the completion model changes, the QListView is automatically updated. In practice, we would normally call match() every time the user edits the current word that is being completed, to update the completion model (and the view).

Often, we want to select the current match in the view. This can be done as follows:

    QModelIndex sourceIndex = completor->match("OM");
    QModelIndex completionIndex = completor->completionModelIndex(sourceIndex);

    if (completionIndex.isValid()) {
        QItemSelectionModel *selectionModel = completionView->selectionModel();
        selectionModel->select(completionIndex, QItemSelectionModel::ClearAndSelect);
        selectionModel->setCurrentIndex(completionIndex, QItemSelectionModel::Current);
    }

match() returns a QModelIndex in the source model. We use completionModelIndex() to convert this index to an index in the completion model.

The demo example includes CompletingLineEdit, which extends QLineEdit to provide a QListView or QTreeView popup that gets its data from QtCompletor's completion model. In addition, CompletingLineEdit supports inline completion and navigation using the Up and Down arrow keys.

Handling Tree Models

QtCompletor can look for completions in tree models, assuming that any item (or sub-item or sub-sub-item) can be unambiguously represented as a string by specifying the path to the item. The completion is then performed one level at a time.

Let's take the example of a user typing in a file system path. The source model is a (hierarchical) QDirModel. The completion occurs for every element in the path. For example, if the current text is C:\Wind, QtCompletor might suggest Windows to complete the current path element. Similarly, if the current text is C:\Windows\Sy, QtCompletor might suggest System.

For this kind of completion to work, you must specify which characters act as separators using setTreeModelSeparators(). For file system paths, the separator is QDir::separator() (/ or \).

When working with a tree model, by default the completionModel() shows only the matching items in the current level. To show all the items, call setCompletionModelFiltered(false).

See the demo example for an illustration of how to use QtCompletor on a tree model (QDirModel).


Member Type Documentation

enum QtCompletor::MatchFlag
flags QtCompletor::MatchFlags

This enum describes the type of matches that can be used when searching for completions in a model.

ConstantValueDescription
QtCompletor::MatchCurrent0x00000001Returns the current match
QtCompletor::MatchFirst0x00000002Returns the first match
QtCompletor::MatchLast0x00000004Return the last match
QtCompletor::MatchNext0x00000008Returns the next match
QtCompletor::MatchPrevious0x00000010Returns the previous match
QtCompletor::MatchWrap0x00000020Indicates whether matches should be wrapped

The MatchFlags type is a typedef for QFlags<MatchFlag>. It stores an OR combination of MatchFlag values.

enum QtCompletor::SeparatorFlag
flags QtCompletor::SeparatorFlags

This enum specifies how split() should behave when operating on a tree model.

ConstantValueDescription
QtCompletor::RootIsSeparator1Indicates that the root item in the model is a separator. This setting is necessary to support QDirModel on Unix, because the model provides a superfluous '/' root item (which is also the Unix path separator).
QtCompletor::SimplifySeparators2Treat consecutive separators as a single separator. For example, if '/' is a separator and this flag is set, red/green/blue and //red////green//blue refer to the same item in the model.

For convenience, when you call setSourceModel() with a QDirModel, the SimplifySeparators flag is automatically set. In addition, on Unix and Mac OS X, the RootIsSeparator is also set.

The SeparatorFlags type is a typedef for QFlags<SeparatorFlag>. It stores an OR combination of SeparatorFlag values.

See also separatorFlags, treeModelSeparators, and split().

enum QtCompletor::SourceModelSorting

This enum specifies how the items in the source model is sorted

ConstantValueDescription
QtCompletor::UnsortedModel0The source model is unsorted
QtCompletor::CaseSensitivelySortedModel1The source model is sorted case sensitively
QtCompletor::CaseInsensitivelySortedModel2The source model is sorted case insensitively


Property Documentation

caseSensitivity : Qt::CaseSensitivity

This property holds the case sensitivity of the matching.

The default is Qt::CaseSensitive.

Access functions:

See also matchColumn, matchRole, and sourceModelSorting.

completionModelFiltered : bool

This property holds whether the contents of the completion model is filtered on the current match text.

For tree models, the completionModel() returns a list of items at the current level. If this property is false, the list contains all items at the current level, including those that don't match the current text.

If the source model is a list or table model and the property is false, the completionModel() is identical to the sourceModel().

By default, this property is true.

Access functions:

See also completionModel(), matchText(), and Handling Tree Models.

matchColumn : int

This property holds the column in the source model in which completions are searched for.

By default, the match column is 0.

Access functions:

See also matchRole, caseSensitivity, and weightColumn.

matchRole : int

This property holds the item role to be used to query the contents of items for matching.

The default role is Qt::EditRole.

Access functions:

See also matchColumn, caseSensitivity, and weightRole.

separatorFlags : SeparatorFlags

This property holds the flags that control the behavior of split().

When completing on tree models, this flag controls how the matchText() is split into sub-items.

Access functions:

See also split() and treeModelSeparators.

sourceModelSorting : SourceModelSorting

This property holds whether and how the source model is sorted.

By default, no assumptions are made about the order of the items in the source model. If the source model's data for the matchColumn() and matchRole() is sorted in ascending order, you can set this property to CaseSensitivelySortedModel or CaseInsensitivelySortedModel. On large models, this can lead to significant performance improvements, because QtCompletor can then use binary search instead of linear search. (Be aware that these performance improvements cannot take place when QtCompletor's caseSensitivity and the source model's sorting case differ.)

Access functions:

See also setCaseSensitivity().

treeModelSeparators : QString

This property holds the list of separators recognized when completing an item from a tree model.

Each character in the QString is a separator. match() uses these separators to match in the nodes of a heirarchical model. For instance, when using a QDirModel as the sourceModel(), "/\" can be used as separators on Windows to mean slash or backslash.

Access functions:

See also Handling Tree Models.

weightColumn : int

This property holds the column in the source model that store the item weights.

Weights are integers that specify how important candidates are, so that higher-weight candidates appear before lower-weight candidates when iterating. Weights are provided by the source model.

The default is 0. To enable weighted matching, you must set the weightRole (which is -1 by default).

Access functions:

See also weightRole and matchColumn.

weightRole : int

This property holds the item role used to query weight of items.

Weights are integers that specify how important candidates are, so that higher-weight candidates appear before lower-weight candidates when iterating. Weights are provided by the source model.

The default is -1, meaning that weighted matching is disabled (all items are taken to weigh the same).

Access functions:

See also weightColumn and matchRole.


Member Function Documentation

QtCompletor::QtCompletor ( QObject * parent = 0 )

Constructs a QtCompletor object with the given parent.

QtCompletor::~QtCompletor ()

Destroys the QtCompletor object.

QAbstractItemModel * QtCompletor::completionModel () const

Returns the completion model. The completion model is a list model that contains all the possible matches for the current match text.

See also isCompletionModelFiltered() and matchText().

QModelIndex QtCompletor::completionModelIndex ( const QModelIndex & sourceModelIndex ) const

Returns the corresponding index in the completion model given a sourceModelIndex in the source model. This is useful for handling selection of items in views of the completion model.

See also completionModel() and sourceModelIndex().

QModelIndex QtCompletor::match ( const QString & matchText, MatchFlags flags = MatchFirst )   [slot]

Sets the current match text to matchText and returns an index in the source model depending on flags that is a completion for matchText. If matchText is not found, this function returns an invalid index.

The completion model is updated to reflect the list of possible matches for matchText.

See also matched(), completionModel(), weightColumn, and weightRole.

QModelIndex QtCompletor::match ( MatchFlags flags )

This is an overloaded member function, provided for convenience.

Retrieves another candidate after a call to the match() function that takes a QString as its first argument. Which candidate is returned depends on flags.

QString QtCompletor::matchText () const

Returns the current match text.

See also match().

void QtCompletor::matched ( const QModelIndex & matchedIndex )   [signal]

This signal is emitted when match() is called. The matchedIndex is the value returned by match().

See also match().

void QtCompletor::matched ( const QString & matchedText )   [signal]

This is an overloaded member function, provided for convenience.

matchedText is the text for the new candidate.

void QtCompletor::setSourceModel ( QAbstractItemModel * sourceModel, SourceModelSorting sorting = QtCompletor::UnsortedModel )

Sets the source model to sourceModel and the nature of sorting to sorting

For convenience, if sourceModel is a QDirModel, the SimplifySeparators flag is automatically set. In addition, on Unix and Mac OS X, the RootIsSeparator is also set. (On Windows, this isn't required because QDirModel provides drives as its root items instead of a superfluous '/' item.)

See also completionModel() and sourceModelSorting.

QAbstractItemModel * QtCompletor::sourceModel () const

Returns the source model.

See also setSourceModel() and completionModel().

QModelIndex QtCompletor::sourceModelIndex ( const QModelIndex & completionModelIndex ) const

Returns the corresponding index in the source model given a completionModelIndex in the completion model. This is useful for retrieving selections in the completion model.

See also completionModel() and completionModelIndex().

QStringList QtCompletor::split () const   [virtual protected]

Splits the current matchText() using treeModelSeparators(). separatorFlags() controls the behaviour of the split. Reimplement this function and return a string list that will be used for matching text when using a tree model.

See also Handling Tree Models, separatorFlags, and treeModelSeparators.


Copyright © 2008 Nokia Corporation and/or its subsidiary(-ies) Trademarks
Qt Solutions