QT QCompleter的简单使用

需要四个类:

  • QCompleter
  • QLineEdit
  • QStringList (数据结构、可用其他数据结构)
  • QStringListModel (数据模型、可用其他数据模型或自定义)

    做简单的搜索自动补全,使用最简单的数据结构 QStringList和最简单的数据模型QStringListModel。

使用下面代码完成自动补全功能

QLineEdit *SearchLineEdit = new QLineEdit(this);
QCompleter *completer = new QCompleter();
completer->setFilterMode(Qt::MatchStartsWith);
completer->setCompletionMode(QCompleter::PopupCompletion    );
QStringList valueList;
valueList<<"plan 1"<<"rrm"<<"what"<<"plan 2"<<"what plan"<<"rr_MM";
QStringListModel *listModel; 
listModel = new QStringListModel(valueList, this);  
completer->setModel(listModel);
SearchLineEdit->setCompleter(completer);

自动补全的补全规则和显示形式设置:

  • 设置匹配规则
completer->setFilterMode(Qt::MatchStartsWith);
//Qt::MatchStartsWith //default  开头匹配
//Qt::MatchContains   // 内容匹配
//Qt::MatchEndsWith   //结尾匹配
  • 设置补全形式
completer->setCompletionMode(QCompleter::PopupCompletion    );
//QCompleter::PopupCompletion
//Current completions are displayed in a popup window. 
//default

PopupCompletion(default)

completer->setCompletionMode(QCompleter::InlineCompletion);
//QCompleter::InlineCompletion
//Completions appear inline (as selected text).

InlineCompletion

completer->setCompletionMode(QCompleter::UnfilteredPopupCompletion);
//QCompleter::UnfilteredPopupCompletion
//All possible completions are displayed in a popup window with the most likely suggestion indicated as current.

QT QCompleter的简单使用_第1张图片

  • 设置最大显示数目

默认是7

completer->setMaxVisibleItems(5);//defuat 7

你可能感兴趣的:(qt)